Advertisement
Guest User

Untitled

a guest
Feb 3rd, 2017
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var fs = require('fs');
  2. var readline = require('readline');
  3. var googleApi = require('googleapis');
  4. var googleAuth = require('google-auth-library');
  5. var email;
  6. var verLink;
  7.  
  8. // If modifying these scopes, delete your previously saved credentials
  9. // at ~/.credentials/gmail-nodejs-quickstart.json
  10. var SCOPES = ['https://www.googleapis.com/auth/gmail.readonly'];
  11. var TOKEN_DIR = './token/';
  12. var TOKEN_PATH = TOKEN_DIR + 'gmail-nodejs-quickstart.json';
  13.  
  14. // Load client secrets from a local file.
  15. module.exports = {
  16.     verificationLink: function (forEmail, cb)
  17.     {
  18.         fs.readFileSync('./token/client_secret.json', function processClientSecrets(err, content) {
  19.             if (err) {
  20.                 console.log('Error loading client secret file: ' + err);
  21.                 return;
  22.             }
  23.  
  24.             // Authorize a client with the loaded credentials, then call the
  25.             // Gmail API.
  26.            
  27.             var secret = JSON.parse(content);
  28.             email = forEmail;
  29.             authorize(secret, function (auth) {
  30.                 getVerificationLink(auth, cb);
  31.             });
  32.         });
  33.     }
  34. };
  35.  
  36. /**
  37.  * Create an OAuth2 client with the given credentials, and then execute the
  38.  * given callback function.
  39.  *
  40.  * @param {Object} credentials The authorization client credentials.
  41.  * @param {function} callback The callback to call with the authorized client.
  42.  */
  43. function authorize(credentials, callback) {
  44.     var clientSecret = credentials.installed.client_secret;
  45.     var clientId = credentials.installed.client_id;
  46.     var redirectUrl = credentials.installed.redirect_uris[0];
  47.     var auth = new googleAuth();
  48.     var oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);
  49.  
  50.     // Check if we have previously stored a token.
  51.     fs.readFile(TOKEN_PATH, function(err, token) {
  52.         if (err) {
  53.             getNewToken(oauth2Client, callback);
  54.         } else {
  55.             oauth2Client.credentials = JSON.parse(token);
  56.             callback(oauth2Client);
  57.         }
  58.     });
  59. }
  60.  
  61. /**
  62.  * Get and store new token after prompting for user authorization, and then
  63.  * execute the given callback with the authorized OAuth2 client.
  64.  *
  65.  * @param {google.auth.OAuth2} oauth2Client The OAuth2 client to get token for.
  66.  * @param {getEventsCallback} callback The callback to call with the authorized
  67.  *     client.
  68.  */
  69. function getNewToken(oauth2Client, callback) {
  70.     var authUrl = oauth2Client.generateAuthUrl({
  71.         access_type: 'offline',
  72.         scope: SCOPES
  73.     });
  74.     console.log('Authorize this app by visiting this url: ', authUrl);
  75.     var rl = readline.createInterface({
  76.         input: process.stdin,
  77.         output: process.stdout
  78.     });
  79.     rl.question('Enter the code from that page here: ', function(code) {
  80.         rl.close();
  81.         oauth2Client.getToken(code, function(err, token) {
  82.             if (err) {
  83.                 console.log('Error while trying to retrieve access token', err);
  84.                 return;
  85.             }
  86.             oauth2Client.credentials = token;
  87.             storeToken(token);
  88.             callback(oauth2Client);
  89.         });
  90.     });
  91. }
  92.  
  93. /**
  94.  * Store token to disk be used in later program executions.
  95.  *
  96.  * @param {Object} token The token to store to disk.
  97.  */
  98. function storeToken(token) {
  99.     try {
  100.         fs.mkdirSync(TOKEN_DIR);
  101.     } catch (err) {
  102.         if (err.code != 'EEXIST') {
  103.             throw err;
  104.         }
  105.     }
  106.     fs.writeFile(TOKEN_PATH, JSON.stringify(token));
  107.     console.log('Token stored to ' + TOKEN_PATH);
  108. }
  109.  
  110. /**
  111.  * Gets the verification link
  112.  * @param {google.auth.OAuth2} auth An authorized OAuth2 client.
  113.  */
  114. function getVerificationLink(auth, cb) {
  115.     var gmail = googleApi.gmail('v1');
  116.     //call list of emails
  117.     gmail.users.messages.list({
  118.         auth: auth,
  119.         userId: 'me'
  120.     }, function(err, response) {
  121.         if (err) {
  122.             console.log('The API returned an error: ' + err);
  123.             return;
  124.         }
  125.         var messages = response.messages;
  126.         if (response == null) {
  127.             console.log('No messages found.');
  128.         } else {
  129.             //iterates over list of messages
  130.             for (var i = 0; i < messages.length; i++) {
  131.                 var msg = messages[i];
  132.                 //for each message from the list gets details
  133.                 var a = gmail.users.messages.get({
  134.                     format: 'full',
  135.                     id: msg.id,
  136.                     auth: auth,
  137.                     userId: 'me'
  138.                 }, function(err, response) {
  139.                     if (err) {
  140.                         console.log('The API returned an error: ' + err);
  141.                         return;
  142.                     } else {
  143.                         //find target email by delivery adress
  144.                         if(getHeader(response.payload.headers, 'Delivered-To') == email){
  145.                             cb(getBody(response.payload).match('[^<a]* href="([^"]*)"')[1]);
  146.                        }
  147.                    }
  148.                });
  149.            }
  150.        }
  151.    });
  152. }
  153.  
  154. /**
  155. * Message parsing helpers
  156. */
  157. function getHeader(headers, index) {
  158.    var header = '';
  159.    headers.forEach(function(singleHeader) {
  160.        if(singleHeader.name === index){
  161.            header = singleHeader.value;
  162.        }
  163.    });
  164.  
  165.    return header;
  166. }
  167.  
  168. function getBody(message) {
  169.    var encodedBody = '';
  170.    if(typeof message.parts === 'undefined')
  171.    {
  172.        encodedBody = message.body.data;
  173.    }
  174.    else
  175.    {
  176.        encodedBody = getHTMLPart(message.parts);
  177.    }
  178.    encodedBody = encodedBody.replace(/-/g, '+').replace(/_/g, '/').replace(/\s/g, '');
  179.    var res = new Buffer(encodedBody, 'base64').toString('ascii');
  180.    return res;
  181. }
  182.  
  183. function getHTMLPart(arr) {
  184.    for(var x = 0; x <= arr.length; x++)
  185.    {
  186.        if(typeof arr[x].parts === 'undefined')
  187.        {
  188.            if(arr[x].mimeType === 'text/html')
  189.            {
  190.                return arr[x].body.data;
  191.            }
  192.        }
  193.        else
  194.        {
  195.            return getHTMLPart(arr[x].parts);
  196.        }
  197.    }
  198.    return '';
  199. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement