Advertisement
Boquete

Untitled

May 24th, 2017
601
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 google = require('googleapis');
  4. var googleAuth = require('google-auth-library');
  5. var atob = require('atob');
  6. var pg = require('pg');
  7. const Language = require('@google-cloud/language');
  8. const language = Language({
  9.     projectId: 'fine-balm-165720',
  10.     keyFilename: 'MyProject.json'
  11. });
  12.  
  13.  
  14. global.fetch = require('node-fetch');
  15. var cc = require('cryptocompare');
  16.  
  17. // If modifying these scopes, delete your previously saved credentials
  18. // at ~/.credentials/gmail-nodejs-quickstart.json
  19. var SCOPES = ['https://mail.google.com/'];
  20. var TOKEN_DIR = (process.env.HOME || process.env.HOMEPATH ||
  21.     process.env.USERPROFILE) + '/.credentials/';
  22. var TOKEN_PATH = TOKEN_DIR + 'gmail-nodejs-quickstart.json';
  23.  
  24. // Load client secrets from a local file.
  25. fs.readFile('client_secret.json', function processClientSecrets(err, content) {
  26.     if (err) {
  27.         console.log('Error loading client secret file: ' + err);
  28.         return;
  29.     }
  30.     // Authorize a client with the loaded credentials, then call the
  31.     // Gmail API.
  32.     authorize(JSON.parse(content), listMessages);
  33. });
  34.  
  35. /**
  36.  * Create an OAuth2 client with the given credentials, and then execute the
  37.  * given callback function.
  38.  *
  39.  * @param {Object} credentials The authorization client credentials.
  40.  * @param {function} callback The callback to call with the authorized client.
  41.  */
  42. function authorize(credentials, callback) {
  43.     var clientSecret = credentials.installed.client_secret;
  44.     var clientId = credentials.installed.client_id;
  45.     var redirectUrl = credentials.installed.redirect_uris[0];
  46.     var auth = new googleAuth();
  47.     var oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);
  48.  
  49.     // Check if we have previously stored a token.
  50.     fs.readFile(TOKEN_PATH, function (err, token) {
  51.         if (err) {
  52.             getNewToken(oauth2Client, callback);
  53.         } else {
  54.             oauth2Client.credentials = JSON.parse(token);
  55.             callback(oauth2Client);
  56.         }
  57.     });
  58. }
  59.  
  60. /**
  61.  * Get and store new token after prompting for user authorization, and then
  62.  * execute the given callback with the authorized OAuth2 client.
  63.  *
  64.  * @param {google.auth.OAuth2} oauth2Client The OAuth2 client to get token for.
  65.  * @param {getEventsCallback} callback The callback to call with the authorized
  66.  *     client.
  67.  */
  68. function getNewToken(oauth2Client, callback) {
  69.     var authUrl = oauth2Client.generateAuthUrl({
  70.         access_type: 'offline',
  71.         scope: SCOPES
  72.     });
  73.     console.log('Authorize this app by visiting this url: ', authUrl);
  74.     var rl = readline.createInterface({
  75.         input: process.stdin,
  76.         output: process.stdout
  77.     });
  78.     rl.question('Enter the code from that page here: ', function (code) {
  79.         rl.close();
  80.         oauth2Client.getToken(code, function (err, token) {
  81.             if (err) {
  82.                 console.log('Error while trying to retrieve access token', err);
  83.                 return;
  84.             }
  85.             oauth2Client.credentials = token;
  86.             storeToken(token);
  87.             callback(oauth2Client);
  88.         });
  89.     });
  90. }
  91.  
  92. /**
  93.  * Store token to disk be used in later program executions.
  94.  *
  95.  * @param {Object} token The token to store to disk.
  96.  */
  97. function storeToken(token) {
  98.     try {
  99.         fs.mkdirSync(TOKEN_DIR);
  100.     } catch (err) {
  101.         if (err.code != 'EEXIST') {
  102.             throw err;
  103.         }
  104.     }
  105.     fs.writeFile(TOKEN_PATH, JSON.stringify(token));
  106.     console.log('Token stored to ' + TOKEN_PATH);
  107. }
  108.  
  109. /**
  110.  * Lists the messages content in the user's account.
  111.  *
  112.  * @param {google.auth.OAuth2} auth An authorized OAuth2 client.
  113.  * @param {labelIds} messages only from this label are displayed
  114.  */
  115. var gmail = google.gmail('v1');
  116.  
  117. function listMessages(auth) {
  118.     gmail.users.messages.list({
  119.         auth: auth,
  120.         userId: 'me',
  121.         maxResults: '500',
  122.         q: 'newsletter@coindesk.com',
  123.         labelIds: 'INBOX'
  124.     }, function (err, response) {
  125.         if (err) {
  126.             console.log('The API returned an error: ' + err);
  127.             return;
  128.         }
  129.         var messages = response.messages;
  130.         if (undefined !== messages && messages.length == 0) {
  131.             console.log('Messages not found.');
  132.         } else {
  133.             getMessageBody(messages, auth)
  134.         }
  135.     });
  136. }
  137.  
  138. function getMessageBody(messages, auth) {
  139.     if (undefined !== messages) {
  140.         for (var i = 0; i < messages.length; i++) {
  141.             var message = messages[i];
  142.             gmail.users.messages.get({
  143.                     auth: auth,
  144.                     'userId': 'me',
  145.                     'id': message.id
  146.                 }, function (err, response) {
  147.                     if (err) {
  148.                         console.log('The API returned an error: ' + err);
  149.                         return;
  150.                     }
  151.                     var message = response.id;
  152.                     //modifyMessage(message, auth); // Label change
  153.                     var body = response.payload.parts[0].body.data;
  154.  
  155.                     cc.price('BTC', 'USD')
  156.                         .then(prices => {
  157.                             language.detectSentiment(atob(body).split('(http://www.facebook.com')[0])
  158.                                 .then((results) => {
  159.                                     const sentiment = results[0];
  160.                                     console.log(`Text: ${atob(body)}`); // VIEW TEXT MESSAGE
  161.                                     console.log(atob(body).split('(http://www.facebook.com')[0]);
  162.                                     console.log('ID:' + message + `  Sentiment score: ${sentiment.score}`);
  163.                                     console.log(`Sentiment magnitude: ${sentiment.magnitude}`);
  164.                                     console.log('');
  165.                                     var sentimentScore = sentiment.score;
  166.                                     sql(message, sentimentScore, prices)
  167.  
  168.  
  169.                                 })
  170.                                 .catch((err) => {
  171.                                     console.error('ERROR:', err);
  172.                                 });
  173.                         });
  174.                 }
  175.             );
  176.         }
  177.     }
  178. }
  179.  
  180.  
  181. function modifyMessage(message, auth) {
  182.     gmail.users.messages.modify({
  183.             'auth': auth,
  184.             'userId': 'me',
  185.             'id': message,
  186.             'resource': {
  187.                 "addLabelIds": [
  188.                     "Label_2"
  189.                 ],
  190.                 "removeLabelIds": [
  191.                     "INBOX"
  192.                 ]
  193.             }
  194.         }, function (err, response) {
  195.             if (err) {
  196.                 console.log('The API returned an error: ' + err);
  197.                 return;
  198.             }
  199.             console.log('Success, label changed for message: ' + message)
  200.         }
  201.     );
  202. }
  203.  
  204.  
  205. // TODO ADD EVERYTHING TO THIS FUCKING DATABASE
  206. function sql(message, sentiment, price) {
  207.     var username = 'kfpyhrzizvnthq';
  208.     var password = '23fb755df500316578d72b2a62b443e2d638e1b17e60407f1838804eba1d7897';
  209.     var host = 'ec2-184-73-199-72.compute-1.amazonaws.com';
  210.     var conStringPri = 'postgres://' + username + ':' + password + '@' + host +
  211.         ':5432/d4et7h51ifgegu';
  212.     pg.defaults.ssl = true;
  213.  
  214.     var today = new Date().toISOString().replace(/T/, ' ').// replace T with a space
  215.     replace(/\..+/, '');     // delete the dot and everything after
  216.  
  217.     pg.connect(conStringPri, function (err, client, done) {
  218.             client.query('INSERT INTO antek(ID, DATE, SCORE, PRICE) values($1, $2, $3, $4)',
  219.                 [message, today, sentiment, price]);
  220.  
  221.         }
  222.     );
  223. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement