Advertisement
Guest User

Relogin.js

a guest
Oct 27th, 2021
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* Setup.js
  2.  * Module: MMM-RemoteCompliments
  3.  *
  4.  * By Mitchell Marino https://github.com/mitchelltmarino
  5.  * MIT Licensed.
  6.  */
  7. const fs = require('fs');
  8. const readline = require('readline');
  9. const { google } = require('googleapis');
  10.  
  11. // If modifying these scopes, delete credentials.json.
  12. const SCOPES = ['https://www.googleapis.com/auth/drive'];
  13.  
  14. // Factors to determine whether setup was a success.
  15. global.successFactors = {
  16.   allFilesCreated: undefined,
  17.   driveFileIDsSaved: undefined,
  18.   scheduledComplimentsSetup: undefined,
  19.   configurationSetup: undefined,
  20. }
  21.  
  22. // Get Authorization.
  23. authorization = new Promise(function (resolve, reject) {
  24.  
  25.   // Read the Auth file, and load it.
  26.   fs.readFile('Auth.json', (err, content) => {
  27.  
  28.     // Handle errors.
  29.     if (err) {
  30.       console.log("Error opening Auth.json. Please make sure it exists.");
  31.       return reject(err);
  32.     }
  33.  
  34.     // Extract credentials.
  35.     credentials = JSON.parse(content);
  36.     const { client_secret, client_id, redirect_uris } = credentials.installed;
  37.     const oAuth2Client = new google.auth.OAuth2(client_id, client_secret, redirect_uris[0]);
  38.  
  39.     //Check for existing token.
  40.     fs.readFile('Token.json', (err, token) => {
  41.       // If read failed, obtain access token via request & Authorization.
  42.         getAccessToken(oAuth2Client).then(
  43.           (oAuth2Client) => {
  44.             // If token was obtained.
  45.             resolve(oAuth2Client);
  46.           },
  47.           (err) => {
  48.             // If token cannot be obtained.
  49.             console.log("Could not obtain an access token.");
  50.             return reject(err);
  51.           });
  52.     });
  53.   });
  54.  
  55. }).then((auth) => {
  56. }, (err) => {
  57.   // Handle rejection of authorizaiton.
  58.   console.log(err);
  59.   console.log("Something went wrong with the setup. It is recommended you delete the files created on your Google Drive (if any have been created) and try setup again after fixing the above error.");
  60. }).catch((err) => {
  61.   // Handle errors that are thrown.
  62.   console.log(err);
  63.   console.log("Something went wrong with the setup. It is recommended you delete the files created on your Google Drive (if any have been created) and try setup again after fixing the above error.");
  64. });
  65.  
  66. /**
  67.  * Obtain an access token which provides authorization for reads and writes to Google Drive.
  68.  * Will provide a user with a secure external URL which will allow them to authorize this Application
  69.  * if they follow the instructions properly.
  70.  * @param {google.auth.OAuth2} oAuth2Client a Google OAuth 2 object to be populated with authorization credentials.
  71.  */
  72. function getAccessToken(oAuth2Client) {
  73.   return new Promise(function (resolve, reject) {
  74.     //Authorization webpage.
  75.     const authUrl = oAuth2Client.generateAuthUrl({
  76.       access_type: 'offline',
  77.       scope: SCOPES,
  78.     });
  79.     console.log('Authorize this app by visiting this url:', authUrl);
  80.     const rl = readline.createInterface({
  81.       input: process.stdin,
  82.       output: process.stdout,
  83.     });
  84.     //Receive code for authorization.
  85.     rl.question('Enter the code from that page here: ', (code) => {
  86.       rl.close();
  87.       oAuth2Client.getToken(code, (err, token) => {
  88.         if (err) return reject(err);
  89.         //Set oAuth2Client credentials, respective to the token.
  90.         oAuth2Client.setCredentials(token);
  91.         // Store the token to disk for later program executions
  92.         fs.writeFile('Token.json', JSON.stringify(token, null, 4), (err) => {
  93.           if (err) return reject(err);
  94.           console.log("Token stored to: Token.json");
  95.           // Resolve once all operations have completed successfully.
  96.           resolve(oAuth2Client);
  97.         });
  98.       });
  99.     });
  100.   });
  101. };
  102.  
  103. /**
  104.  * Create a file (or folder) on Google Drive.
  105.  * @param {google.drive} drive a Google Drive connection. (Through Google APIs)
  106.  * @param {JSON} fileMetadata the metadata for the file to be created.
  107.  */
  108. function createDriveFile(drive, fileMetadata) {
  109.   return new Promise(function (resolve, reject) {
  110.     // Create the file.
  111.     drive.files.create({
  112.       resource: fileMetadata,
  113.       fields: 'id'
  114.     }, function (err, payload) {
  115.       if (err) return reject(err);
  116.       // On success, continue with Id of directory parent.
  117.       resolve(payload.data.id);
  118.     });
  119.   });
  120. };
  121.  
  122. /**
  123.  * Setup the Configuration File. (i.e. populate the configuration file with data and defaults).
  124.  * @param {google.auth.OAuth2} auth a Google OAuth 2 object containing authorization credentials.
  125.  * @param {String} fileId the unique fileId of the Configuration File to be setup.
  126.  */
  127. function setupConfigFile(auth, fileId) {
  128.   var sheets = google.sheets({ version: 'v4', auth });
  129.   var values = [
  130.     ['Enable Functions'],
  131.     ['Function', 'Is Active (True / False)'],
  132.     ['Scheduled Compliments', true],
  133.     ['Current Compliment', true],
  134.     ['Random Compliments', true],
  135.     ['Images', true],
  136.     [],
  137.     [],
  138.     ['Random Compliments Variables'],
  139.     ['Variable', 'Value'],
  140.     ['Morning Start Time', 3],
  141.     ['Morning End Time', 12],
  142.     ['Afternoon Start Time', 12],
  143.     ['Afternoon End Time', 17],
  144.     [],
  145.     [],
  146.     ['Update Intervals'],
  147.     ['Variable', 'Minutes', 'Seconds'],
  148.     ['Random Compliments', 30, 0],
  149.     ['Images', 0, 30],
  150.     [],
  151.     [],
  152.     ['Miscellaneous'],
  153.     ['Variable', 'Value'],
  154.     ['Header Content', 'MMM-RemoteCompliments'],
  155.     ['Image Max Width', 500],
  156.     ['Image Max Height', 500],
  157.     ['Append Period', false]
  158.   ];
  159.   sheets.spreadsheets.values.update({
  160.     spreadsheetId: fileId,
  161.     range: 'A1:C28',
  162.     valueInputOption: 2,
  163.     resource: { values },
  164.   }, (err, result) => {
  165.     if (err) {
  166.       console.log('An error occurred while setting up Configuration file:\n', err);
  167.       global.successFactors.configurationSetup = false;
  168.       return checkSetupSuccess();
  169.     }
  170.     console.log('Setup configuration file, %d cells updated.', result.data.updatedCells);
  171.     global.successFactors.configurationSetup = true;
  172.     return checkSetupSuccess();
  173.   });
  174. };
  175.  
  176. /**
  177.  * Setup the Scheduled Compliments File. (i.e. populate the Scheduled Compliments file with header data).
  178.  * @param {google.auth.OAuth2} auth a Google OAuth 2 object containing authorization credentials.
  179.  * @param {String} fileId the unique fileId of the Configuration File to be setup.
  180.  */
  181. function setupScheduledComplimentsFile(auth, fileId) {
  182.   var sheets = google.sheets({ version: 'v4', auth });
  183.   let values = [['Start Date', 'Start Time', 'End Date', 'End Time', 'Compliment']];
  184.   sheets.spreadsheets.values.update({
  185.     spreadsheetId: fileId,
  186.     range: 'A1:E1',
  187.     valueInputOption: 2,
  188.     resource: { values },
  189.   }, (err, result) => {
  190.     if (err) {
  191.       console.log('An error occurred while setting up Scheduled Compliments file:\n', err);
  192.       global.successFactors.scheduledComplimentsSetup = false;
  193.       return checkSetupSuccess();
  194.     }
  195.     console.log('Setup scheduled compliments file, %d cells updated.', result.data.updatedCells);
  196.     global.successFactors.scheduledComplimentsSetup = true;
  197.     return checkSetupSuccess();
  198.   });
  199. };
  200.  
  201. /**
  202.  * Check if conditions are met for setup to qualify as Success.
  203.  * If there was a failure in an operation, notify the user and then exit.
  204.  */
  205. function checkSetupSuccess() {
  206.   // Conditionals.
  207.   var hasUndefined = false;
  208.   var hasFalse = false;
  209.   // Iterate through global successFactors JSON object.
  210.   for (var key in global.successFactors) {
  211.     if (global.successFactors[key] === undefined) {
  212.       hasUndefined = true;
  213.       break;
  214.     }
  215.     if (global.successFactors[key] === false) {
  216.       console.log('key: ',key);
  217.       hasFalse = true;
  218.       break;
  219.     }
  220.   }
  221.   // If no undefined and no false, print success.
  222.   if (!hasUndefined && !hasFalse) {
  223.     console.log("---\nSetup was a success! Please enjoy MMM-RemoteCompliments!");
  224.   }
  225.   // If false, let user know and exit.
  226.   if (hasFalse){
  227.     console.log("---\nSomething went wrong with the setup. It is recommended you delete the files created on your Google Drive and try setup again after fixing the above error.");
  228.     process.exit(1);
  229.   }
  230. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement