Advertisement
unfairgamer

JS Send Notif

Jul 6th, 2022
26
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. 'use strict';
  2.  
  3. const functions = require('firebase-functions');
  4. const admin = require('firebase-admin');
  5. admin.initializeApp();
  6.  
  7. /**
  8.  * Triggers when a user gets a new follower and sends a notification.
  9.  *
  10.  * Followers add a flag to `/followers/{followedUid}/{followerUid}`.
  11.  * Users save their device notification tokens to `/users/{followedUid}/notificationTokens/{notificationToken}`.
  12.  */
  13. exports.sendFollowerNotification = functions.database.ref('/followers/{followedUid}/{followerUid}')
  14.     .onWrite((change, context) => {
  15.       const followerUid = context.params.followerUid;
  16.       const followedUid = context.params.followedUid;
  17.       // If un-follow we exit the function.
  18.       if (!change.after.val()) {
  19.         return console.log('User ', followerUid, 'un-followed user', followedUid);
  20.       }
  21.       var convertToUppercase = functions.database.ref('/followers/{followedUid}/device_token').onWrite((changes, context) => {
  22.  const beforeData = changes.before.val(); // data before the write
  23.  const afterData = changes.after.val(); // data after the write
  24. });
  25.  
  26.  
  27. // var tokenNew= admin.database().ref('Users/{followedUid}/device_token').once('value', (snap) => {
  28. //     const device_token = snap.val()
  29. //     console.log(device_token+" this is token"); // Null
  30. //     return device_token;
  31. // });
  32. var device_token;
  33.       // Get the list of device notification tokens.
  34.       const getDeviceTokensPromise = admin.database().ref('Users/'+followedUid+'/device_token').once('value', (snap) => {
  35.     device_token = snap.val()
  36.     console.log(device_token+" this is token in getdevtok"); // Null
  37.     return device_token;
  38. });
  39.       var name;
  40.    const getFollowerName = admin.database().ref('Users/'+followerUid+'/name').once('value', (snap) => {
  41.      name = snap.val()
  42.     console.log(name+" this is follower name"); // Null
  43.     return name;
  44. });
  45. var thumb_image;
  46.     var getFollowerThumb = admin.database().ref('Users/'+followerUid+'/thumb_image').once('value', (snap) => {
  47.     thumb_image =String(snap.val())
  48.     console.log(thumb_image+" this is follower dp photoURL"); // Null
  49.     return thumb_image;
  50. });
  51. //      var favs = snap.val();
  52. //  const getFollowerNumb = admin.database().ref('Users/'+followerUid+'/favs').once('value', (snap) => {
  53. //     favs = snap.val()
  54. //     console.log(favs+" this is number"); // Null
  55. //     return favs;
  56. // });
  57.  
  58.       // Get the follower profile.
  59.       const getFollowerProfilePromise = admin.auth().getUser(followerUid);
  60.  
  61.       // The snapshot to the user's tokens.
  62.       let tokensSnapshot;
  63.  
  64.       // The array containing all the user's tokens.
  65.       let tokens;
  66.  
  67.       return Promise.all([getDeviceTokensPromise, getFollowerProfilePromise]).then(results => {
  68.         tokensSnapshot = results[0];
  69.         const follower = results[1];
  70.  
  71.         // Check if there are any device tokens.
  72.         // if (!tokensSnapshot.hasChildren()) {
  73.         //   return console.log('There are no notification tokens to send to.'+getDeviceTokensPromise);
  74.         // }
  75.  
  76.  
  77.         // Notification details.
  78.         const payload = {
  79.          data: {
  80.             title: 'New follower',
  81.             channel_url: 'followers',
  82.             body: name+' is now following you on LittleGig.',
  83.             message: name+' is now following you.',
  84.              name: 'New follower',
  85.              uid:followerUid,
  86.             channel:'Followers',
  87.                 profiledps: String(thumb_image+''),
  88.      uiduser:followerUid,
  89.        titles: 'New follower',
  90.             channel_urls: 'followers',
  91.             bodys: name+' is now following you on LittleGig.',
  92.             icon:String(thumb_image+''),
  93.      
  94.           }
  95.   //         ,
  96.   // data: {
  97.   //   profiledps: String(thumb_image+''),
  98.   //    uiduser:followerUid,
  99.   //      titles: 'New follower',
  100.   //           channel_urls: 'followers',
  101.   //           bodys: name+' is now following you on LittleGig.',
  102.   //           messages: name+' is now following you.'
  103.   // }
  104.  
  105.     //       ,"data":{
  106.     //    title: 'New follower',
  107.     //         channel_url: 'followers',
  108.     //         body: name+' is now following you on LittleGig.',
  109.     //         message: name+' is now following you.',
  110.     //          name: 'New follower',
  111.     //          uid:followerUid,
  112.     //         channel:'Followers',
  113.     //         icon:String(thumb_image),
  114.          
  115.     // }
  116.  
  117.         };
  118.  
  119.  
  120.         console.log('sending notification to '+ device_token+ ' name follower' +name+ ' pic follower '+thumb_image +' getFollowerThumb '+getFollowerThumb );
  121.         console.log('Fetched follower profile', follower);
  122.         // Listing all tokens as an array.
  123.         // tokens = Object.keys(tokensSnapshot.val());
  124.         // Send notifications to all tokens.
  125.         return admin.messaging().sendToDevice(device_token, payload);
  126.       }).then((response) => {
  127.  
  128.         // For each message check if there was an error.
  129.         const tokensToRemove = [];
  130.         response.results.forEach((result, index) => {
  131.           const error = result.error;
  132.           if (error) {
  133.             console.error('Failure sending notification to', device_token, error);
  134.             // Cleanup the tokens who are not registered anymore.
  135.             if (error.code === 'messaging/invalid-registration-token' ||
  136.                 error.code === 'messaging/registration-token-not-registered') {
  137.               tokensToRemove.push(admin.database().ref('followers/'+followedUid+'/'+followerUid).remove());
  138.             }
  139.           }
  140.         });
  141.  
  142.         return Promise.all(tokensToRemove);
  143.       });
  144. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement