Navigation

    Logo
    • Register
    • Login
    • Search
    • Recent
    • Tags
    • Unread
    • Categories
    • Unreplied
    • Popular
    • GitHub
    • Docu
    • Hilfe
    1. Home
    2. Deutsch
    3. Skripten / Logik
    4. JavaScript
    5. Skript lässt Javascript Adapter neustarten...

    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

    Skript lässt Javascript Adapter neustarten...

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

      Hallo zusammen

      Ich versuche, über Firebase Push-Nachrichten an meine eigene Smarthome-App zu pushen.
      Dazu braucht man OAUTH-Authentification.
      Das Ganze funktioniert selten, aber meistens lässt es den Adapter abstürzen.
      es verwendet https und googleapis - die sind beide registriert in der Instance.

      Wenn ich das Skript direkt auf meinem Server ausführe mit 'node push.js', dann gehts.
      Kann es sein, dass der Code zu aufwändig ist für den Adapter?

      Es wird ein AccessToken generiert und danach damit die Push-Meldung abgesetzt.
      Wie gesagt - selten geht es - zumeist aber nicht.

      var registrationToken = 'mytoken';
      const https = require('https');
      
      const { google } = require('googleapis');
      
      const PROJECT_ID = 'ff-a78f0';
      const HOST = 'fcm.googleapis.com';
      const PATH = '/v1/projects/' + PROJECT_ID + '/messages:send';
      const MESSAGING_SCOPE = 'https://www.googleapis.com/auth/firebase.messaging';
      const SCOPES = [MESSAGING_SCOPE];
      
      /**
       * Get a valid access token.
       */
      // [START retrieve_access_token]
      function getAccessToken() {
        return new Promise(function(resolve, reject) {
      
            //// KEY ist JSON-Account-Datei aus firebase
          const key = {
        "type": "x",
        "project_id": "y",
        "private_key_id": "z",
        "private_key": "-----BEGIN PRIVATE KEY-----",
        "client_email": "firebase-adminsdk-86kq0@ff-a78f0.iam.gserviceaccount.com",
        "client_id": "4",
        "auth_uri": "https://accounts.google.com/o/oauth2/auth",
        "token_uri": "https://oauth2.googleapis.com/token",
        "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
        "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-86kq0%ff-a78f0.iam.gserviceaccount.com"
      }
            const jwtClient = new google.auth.JWT(
            key.client_email,
            null,
            key.private_key,
            SCOPES,
            null
          );
          jwtClient.authorize(function(err, tokens) {
            if (err) {
              reject(err);
              return;
            }
            resolve(tokens.access_token);
          });
        });
      }
      // [END retrieve_access_token]
      
      /**
       * Send HTTP request to FCM with given message.
       *
       * @param {object} fcmMessage will make up the body of the request.
       */
      function sendFcmMessage(fcmMessage) {
        getAccessToken().then(function(accessToken) {
          const options = {
            hostname: HOST,
            path: PATH,
            method: 'POST',
            // [START use_access_token]
            headers: {
              'Authorization': 'Bearer ' + accessToken
            }
            // [END use_access_token]
          };
      
          const request = https.request(options, function(resp) {
            resp.setEncoding('utf8');
            resp.on('data', function(data) {
              console.log('Message sent to Firebase for delivery, response:');
              console.log(data);
            });
          });
      
          request.on('error', function(err) {
            console.log('Unable to send message to Firebase');
            console.log(err);
          });
      
          request.write(JSON.stringify(fcmMessage));
          request.end();
        });
      }
      
      /**
       * Construct a JSON object that will be used to customize
       * the messages sent to iOS and Android devices.
       */
      function buildOverrideMessage() {
        const fcmMessage = buildCommonMessage();
        const apnsOverride = {
          'payload': {
            'aps': {
              'badge': 4
            }
          },
          'headers': {
            'apns-priority': '10'
          }
        }; 
        /* Standard-Werte*/
        const androidOverride = {
          'notification': {
            'click_action': 'android.intent.action.MAIN',
            'icon':'icon',
            'color':'FFFFFF'
          }
        };
      
        fcmMessage['message']['android'] = androidOverride;
        fcmMessage['message']['apns'] = apnsOverride;
      
        return fcmMessage;
      }
      
      /**
       * Construct a JSON object that will be used to define the
       * common parts of a notification message that will be sent
       * to any app instance subscribed to the news topic.
       */
      function buildCommonMessage() {
        return {
          'message': {
              'token':'mytoken',
                  'notification': {
              'title': 'title',
              'body': 'text',
                'image':'largeimage'
          
            },
            'android': {
          'notification': {
            'icon': 'icon',
             'click_action': ''
          }
        }
          }
        };
      }
      
          console.log('Init');
          const message = 'common-message';
          if (message && message == 'common-message') {
              const commonMessage = buildCommonMessage();
              console.log('FCM request body for message using common notification object:');
              // console.log(JSON.stringify(commonMessage, null, 2));
              sendFcmMessage(buildCommonMessage());
          } else {
              console.log('Invalid command. Please use one of the following:\n'
            + 'node index.js common-message\n'
            + 'node index.js override-message');
          }
      
      
      Dominic Reber 1 Reply Last reply Reply Quote 0
      • Dominic Reber
        Dominic Reber @Dominic Reber last edited by

        @dominic-reber Kann ich irgendwie das funktionierende Skript wo hinkopieren und aus dem IoBroker-Javascript-Script starten?

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

        Support us

        ioBroker
        Community Adapters
        Donate

        635
        Online

        31.8k
        Users

        80.0k
        Topics

        1.3m
        Posts

        1
        2
        151
        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