Navigation

    Logo
    • Register
    • Login
    • Search
    • Recent
    • Tags
    • Unread
    • Categories
    • Unreplied
    • Popular
    • GitHub
    • Docu
    • Hilfe
    1. Home
    2. Deutsch
    3. Skripten / Logik
    4. JavaScript
    5. Cannot find module 'googleapis' / Authentifizierungsproblem

    NEWS

    • Neuer Blog: Fotos und Eindrücke aus Solingen

    • ioBroker@Smart Living Forum Solingen, 14.06. - Agenda added

    • ioBroker goes Matter ... Matter Adapter in Stable

    Cannot find module 'googleapis' / Authentifizierungsproblem

    This topic has been deleted. Only users with topic management privileges can see it.
    • M
      maxpd last edited by maxpd

      Hi,

      kann mir jemand erklären, wie ich das googleapis Modul in iobroker bringe?

      Ich möchte die Google Fotos API ansprechen und beginne so:

      // Zugriff auf Google Fotos API
      const googlePhotos = require('googleapis').google.photos('v1');
      
      // Authentifizierung mit OAuth 2.0
      const OAuth2 = google.auth.OAuth2;
      const oauth2Client = new OAuth2();
      oauth2Client.setCredentials({
      

      Aber da springt der quasi schon an der ersten Stelle raus mit der Meldung

      10:55:59.774	error	javascript.0 (382470) script.js.Dev.Google_Fotos: Error: Cannot find module 'googleapis'
      

      Gehe ich nach dieser Anleitung: https://stackoverflow.com/questions/44818791/cant-find-module-googleapis

      und lege mir den Order googleapis an (es gibt schon einen Order googleapis-common)

      bekomme ich diese Fehlermeldung

      iobroker:/opt/iobroker/node_modules $ cd googleapis
      iobroker:/opt/iobroker/node_modules/googleapis $ npm i typescript -g
      npm notice
      npm notice New minor version of npm available! 10.2.3 -> 10.5.0
      npm notice Changelog: https://github.com/npm/cli/releases/tag/v10.5.0
      npm notice Run npm install -g npm@10.5.0 to update!
      npm notice
      npm ERR! code EACCES
      npm ERR! syscall mkdir
      npm ERR! path /usr/lib/node_modules/typescript
      npm ERR! errno -13
      npm ERR! Error: EACCES: permission denied, mkdir '/usr/lib/node_modules/typescri                                                                                                             pt'
      npm ERR!  [Error: EACCES: permission denied, mkdir '/usr/lib/node_modules/typesc                                                                                                             ript'] {
      npm ERR!   errno: -13,
      npm ERR!   code: 'EACCES',
      npm ERR!   syscall: 'mkdir',
      npm ERR!   path: '/usr/lib/node_modules/typescript'
      npm ERR! }
      npm ERR!
      npm ERR! The operation was rejected by your operating system.
      npm ERR! It is likely you do not have the permissions to access this file as the                                                                                                              current user
      npm ERR!
      npm ERR! If you believe this might be a permissions issue, please double-check t                                                                                                             he
      npm ERR! permissions of the file and its containing directories, or try running
      npm ERR! the command again as root/Administrator.
      
      npm ERR! A complete log of this run can be found in: /home/iobroker/.npm/_logs/2                                                                                                             024-03-04T10_22_40_582Z-debug-0.log
      
      

      Nutze ich wiederum im Script anstatt googleapis -> googleapis-common kommt die Meldung

      11:25:22.231	error	javascript.0 (382470) script.js.Dev.Google_Fotos: TypeError: Cannot read properties of undefined (reading 'photos')
      

      Gruß
      maxpd

      Codierknecht 1 Reply Last reply Reply Quote 0
      • Codierknecht
        Codierknecht Developer Most Active @maxpd last edited by Codierknecht

        @maxpd

        es gibt schon einen Order googleapis-common

        Wenn es den Ordner bereits gibt, würde ich das so versuchen:

        const googlePhotos = require('googleapis-common').google.photos('v1');
        

        Zusätzliche Module installiert man auch nicht direkt über NPM, sondern trägt die in die JS-Instanz ein.

        M 1 Reply Last reply Reply Quote 0
        • M
          maxpd @Codierknecht last edited by

          @codierknecht schau mal, das habe ich oben schon versucht mit der letzten Fehlermeldung.

          , sondern trägt die in die JS-Instanz ein.

          Wie meinst du das?

          Codierknecht 1 Reply Last reply Reply Quote 0
          • Codierknecht
            Codierknecht Developer Most Active @maxpd last edited by

            @maxpd sagte in Error: Cannot find module 'googleapis':

            Wie meinst du das?

            39fe212f-d59b-4f6b-9c56-81ddfc7d9f68-image.png

            1 Reply Last reply Reply Quote 0
            • M
              maxpd last edited by maxpd

              @codierknecht das hat schonmal geholfen. Danke dafür. Zum Laufen bekomme ich den Code aber leider noch nicht.

              Ich will einmal wöchentlich die Bilder einer gesamten Woche bei Google Fotos von vor 1226 Tagen in ein Album taggen.

              // Zugriff auf Google Fotos API
              
              const {google} = require('googleapis');
              const Photos = require('googlephotos');
              const CronJob = require('cron').CronJob;
              
              // Authentifizierung mit OAuth 2.0
              const OAuth2 = google.auth.OAuth2;
              const oauth2Client = new OAuth2();
              oauth2Client.setCredentials({
                access_token: '',
                refresh_token: '',
                client_id: '',
                client_secret: '',
              });
              
              // Funktion zum Prüfen der OAuth2-Autorisierung
              async function checkAuthorization() {
                try {
                  // Access Token prüfen
                  if (!oauth2Client.credentials || !oauth2Client.credentials.access_token) {
                    console.error('Kein Access Token vorhanden. Autorisierung fehlgeschlagen.');
                    return false;
                  }
              
                  // Gültigkeit des Access Tokens prüfen
                  const expiryDate = new Date(oauth2Client.credentials.expiry_date);
                  if (expiryDate < new Date()) {
                    console.error('Access Token abgelaufen. Autorisierung fehlgeschlagen.');
                    return false;
                  }
              
                  console.info('OAuth2-Autorisierung erfolgreich!');
                  return true;
                } catch (error) {
                  console.error(`Autorisierungsfehler: ${error.message}`);
                  return false;
                }
              }
              
              // Aktuelles Datum
              const today = new Date();
              const todayStr = today.toLocaleDateString('de-DE');
              
              // Albumname für die Bilder der Woche
              const albumName = `Woche vom ${todayStr}`;
              
              // Funktion zum Abrufen der Fotos von vor 1226 Tagen
              async function getPhotosFrom1226DaysAgo() {
                const startDate = new Date(today.getFullYear(), today.getMonth(), today.getDate() - 1226);
                const endDate = new Date(startDate.getFullYear(), startDate.getMonth(), startDate.getDate() + 7);
              
                try {
                  const response = await Photos.mediaItems.list({
                    auth: oauth2Client,
                    searchQuery: `date >= '${startDate.toISOString()}' AND date <= '${endDate.toISOString()}'`,
                    pageSize: 100, // Anzahl der Fotos pro Seite
                  });
              
                  // Extrahieren der Foto-IDs aus der Antwort
                  const photoIds = response.data.mediaItems.map(item => item.id);
                  return photoIds;
                } catch (error) {
                  console.error(`Fehler beim Abrufen von Fotos: ${error.message}`);
                  return []; // Leere Liste zurückgeben, falls Fehler auftreten
                }
              }
              
              // Funktion zum Erstellen eines neuen Albums
              async function createAlbum(albumName) {
                const createAlbumRequest = {
                  album: {
                    title: albumName,
                  },
                };
              
                const response = await Photos.albums.create(createAlbumRequest);
              
                return response.data.id;
              }
              
              // Funktion zum Taggen der Fotos mit dem neuen Album
              async function tagPhotosWithAlbum(albumId, photoIds) {
                const tagPhotosRequest = {
                  albumId: albumId,
                  newMediaItemIds: photoIds,
                };
              
                await Photos.mediaItems.batchAddMediaItemsToAlbum(tagPhotosRequest);
              }
              
              // Hauptfunktion
              async function main() {
              
                // Prüfung der OAuth2-Autorisierung
                const isAuthorized = await checkAuthorization
              
                // Fotos von vor 1226 Tagen abrufen
                const photos = await getPhotosFrom1226DaysAgo();
              
                // Neues Album erstellen
                const albumId = await createAlbum(albumName);
              
                // Fotos mit dem neuen Album taggen
                await tagPhotosWithAlbum(albumId, photos.map((photo) => photo.id));
              
                console.info('Die Bilder der Woche wurden erfolgreich in das neue Album ' + albumName + ' getaggt.');
              }
              
              // Cron-Job-Zeitsteuerung
              
              const cronJob = new CronJob('05 21 * * *', async function() {
                await main();
              });
              
              // Starten des Cron-Jobs
              cronJob.start();
              
              
              

              Die Credentials sind dabei natürlich gepflegt.

              Raus kommt dabei

              21:28:00.018	error	javascript.0 (831843) script.js.Dev.Google_Fotos: Fehler beim Abrufen von Fotos: Cannot read properties of undefined (reading 'list')
              21:28:00.021	error	javascript.0 (831843) script.js.Dev.Google_Fotos: TypeError: Cannot read properties of undefined (reading 'create')
              21:28:00.021	error	javascript.0 (831843) at createAlbum (script.js.Dev.Google_Fotos:54:40)
              21:28:00.021	error	javascript.0 (831843) at main (script.js.Dev.Google_Fotos:75:25)
              21:28:00.023	error	javascript.0 (831843) at CronJob.<anonymous> (script.js.Dev.Google_Fotos:86:3)
              

              Also ich glaube die Authentifizierung klappt nicht. Ich sehe auch keinen Traffic in der Google Cloud.

              Vielleicht weil ich keine Authorisierte JS Quelle angegeben habe?

              00c645db-5618-47f6-a017-e321dd74f9f2-image.png

              Aber mein iobroker hängt nicht öffentlich im Netz und hat keine Portfreigabe (hoffe ich). Hab da keine URL

              1 Reply Last reply Reply Quote 0
              • First post
                Last post

              Support us

              ioBroker
              Community Adapters
              Donate

              538
              Online

              31.8k
              Users

              80.0k
              Topics

              1.3m
              Posts

              2
              5
              223
              Loading More Posts
              • Oldest to Newest
              • Newest to Oldest
              • Most Votes
              Reply
              • Reply as topic
              Log in to reply
              Community
              Impressum | Datenschutz-Bestimmungen | Nutzungsbedingungen
              The ioBroker Community 2014-2023
              logo