Skip to content

Instantly share code, notes, and snippets.

@tablekat
Created June 30, 2016 20:24
Show Gist options
  • Save tablekat/09a00b741c14aca51d18c738070cc545 to your computer and use it in GitHub Desktop.
Save tablekat/09a00b741c14aca51d18c738070cc545 to your computer and use it in GitHub Desktop.
Making gmail push notifications to webhook
import * as request from 'request';
import * as fs from 'fs';
import * as readline from 'readline';
var google = require('googleapis');
var googleAuth = require('google-auth-library');
/*************** STEPS
- made a project on https://console.cloud.google.com/cloudpubsub/topicList?project=testmabs thing?
- made a pubsub topic
- made a subscription to the webhook url
- added that url to the sites i own, i guess? I think I had to do DNS things to confirm i own it, and the error was super vague to figure out that was what i had to do, when trying to add the subscription
- added permission to the topic for "[email protected]" as publisher (I also added ....apps.googleusercontent.com and [email protected] but i dont think I needed them)
- created oauth client info and downloaded it in the credentials section of the google console. (oauthtrash.json)
****************/
var SCOPES = [
'https://mail.google.com/',
'https://www.googleapis.com/auth/gmail.modify',
'https://www.googleapis.com/auth/gmail.readonly'
];
var TOKEN_DIR = './.credentials/';
var TOKEN_PATH = TOKEN_DIR + 'gmail-nodejs-fun.json';
var key = require('../config/oauthtrash.json');
authorize(key, (auth) => {
listLabels(auth);
listEmails(auth);
//watchEmails(auth);
});
// https://developers.google.com/gmail/api/quickstart/nodejs#step_2_install_the_client_library
function authorize(credentials, cb) {
var clientSecret = credentials.installed.client_secret;
var clientId = credentials.installed.client_id;
var redirectUrl = credentials.installed.redirect_uris[0];
var auth = new googleAuth();
var authClient = new auth.OAuth2(clientId, clientSecret, redirectUrl);
//var authClient = new google.auth.JWT(key.client_email, null, key.private_key, SCOPES, null);
// authClient.authorize((err, tokens) => {
// if(err) return console.log(err);
// //cb(authClient);
// console.log(authClient);
// });
//Check if we have previously stored a token.
fs.readFile(TOKEN_PATH, function(err, token) {
if (err) {
getNewToken(authClient, cb);
} else {
authClient.credentials = JSON.parse(token.toString());
cb(authClient);
}
});
}
function getNewToken(oauth2Client, callback) {
var authUrl = oauth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES
});
console.log('Authorize this app by visiting this url: ', authUrl);
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('Enter the code from that page here: ', function(code) {
rl.close();
oauth2Client.getToken(code, function(err, token) {
if (err) {
console.log('Error while trying to retrieve access token', err);
return;
}
oauth2Client.credentials = token;
storeToken(token);
callback(oauth2Client);
});
});
}
function storeToken(token) {
try {
fs.mkdirSync(TOKEN_DIR);
} catch (err) {
if (err.code != 'EEXIST') {
throw err;
}
}
fs.writeFile(TOKEN_PATH, JSON.stringify(token));
console.log('Token stored to ' + TOKEN_PATH);
}
function listLabels(auth) {
var gmail = google.gmail('v1');
gmail.users.labels.list({
auth: auth,
userId: 'me',
}, function(err, response) {
if (err) {
console.log('The API returned an error: ' + err);
return;
}
var labels = response.labels;
if (labels.length == 0) {
console.log('No labels found.');
} else {
console.log('Labels:');
for (var i = 0; i < labels.length; i++) {
var label = labels[i];
console.log('- %s', label.name);
}
}
});
}
function listEmails(auth) {
var gmail = google.gmail({ auth: auth, version: 'v1' });
var emails = gmail.users.history.list({
//maxResults: 5,
startHistoryId: 1392, //1401,
userId: "[email protected]"
}, function (err, results) {
// https://developers.google.com/gmail/api/v1/reference/users/history/list#response
if(err) return console.log(err);
console.log("users.history.list result:", results);
//console.log("-----------------------");
if(!results.history || !results.history.length) console.log("No history");
results.history[0].messages.map((emailInfo, i) => {
gmail.users.messages.get({ userId: "[email protected]", id: emailInfo.id }, (err, results) => {
if(err) return console.log(err);
console.log(`Email ${i} (${emailInfo.id}):`, results);
if(i == 0){
//console.log("----------------------");
//console.log(JSON.stringify(results, null, 2));
}
});
});
});
// var emails = gmail.users.messages.list({
// includeSpamTrash: false,
// //maxResults: 5,
// startHistoryId: 1401,
// q: "",
// userId: "[email protected]"
// }, function (err, results) {
// if(err) return console.log(err);
// console.log(results);
// //console.log("-----------------------");
// results.messages.map((emailInfo, i) => {
// gmail.users.messages.get({ userId: "[email protected]", id: emailInfo.id }, (err, results) => {
// if(err) return console.log(err);
// console.log(`Email ${i} (${emailInfo.id}):`, results);
// if(i == 0){
// //console.log("----------------------");
// //console.log(JSON.stringify(results, null, 2));
// }
// });
// });
// });
}
function watchEmails(auth) {
// https://developers.google.com/gmail/api/guides/push#create_a_topic
var gmail = google.gmail({ auth: auth, version: 'v1' });
gmail.users.watch({
userId: "[email protected]",
resource: {
topicName: "projects/testmabs/topics/testpusho",
}
}, (err, result) => {
console.log("Error:", err);
console.log("Watch reply:", result);
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment