Created
September 16, 2020 17:44
-
-
Save JaiParakh/c31e4670b452ad55c8b572f26f70e6f8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const {google} = require('googleapis'); | |
var base64 = require('js-base64').Base64; | |
const parse = require('node-html-parser').parse; | |
const cheerio = require('cheerio'); | |
var open = require('open'); | |
var Mailparser = require('mailparser').MailParser; | |
class Check{ | |
constructor(auth){ | |
this.me = 'emailid@gmail.com'; | |
this.gmail = google.gmail({version: 'v1', auth}); | |
this.auth = auth; | |
} | |
// Checks the Inbox for mails. | |
checkInbox(){ | |
this.gmail.users.messages.list({ | |
userId: this.me | |
}, (err, res) => { | |
if(!err){ | |
console.log(res.data); | |
} | |
else{ | |
console.log(err); | |
} | |
}) | |
} | |
// Searches for Medium Daily Digest Mails. | |
checkForMediumMails(){ | |
var query = "from:noreply@medium.com is:unread"; | |
this.gmail.users.messages.list({ | |
userId: this.me, | |
q: query | |
}, (err, res) => { | |
if(!err){ | |
var mails = res.data.messages; | |
mails.forEach(m => { | |
this.getMail(m.id); | |
}) | |
} | |
else{ | |
console.log(err); | |
} | |
}); | |
} | |
// Fetches mails by id and filters out the blog links from the medium daily digest mails. | |
getMail(msgId){ | |
this.gmail.users.messages.get({ | |
'userId': this.me, | |
'id': msgId | |
}, (err, res) => { | |
if(!err){ | |
var body = res.data.payload.parts[0].body.data; | |
var htmlBody = base64.decode(body.replace(/-/g, '+').replace(/_/g, '/')); | |
var mailparser = new Mailparser(); | |
mailparser.on("end", (err,res) => { | |
console.log(res); | |
}) | |
mailparser.on('data', (dat) => { | |
if(dat.type === 'text'){ | |
const $ = cheerio.load(dat.textAsHtml); | |
var links = []; | |
var modLinks = []; | |
$('a').each(function(i, elem) { | |
links[i] = $(this).attr('href'); | |
}); | |
var pat = /------[0-9]-[0-9][0-9]/; | |
var k =0; | |
modLinks = links.filter(li => { | |
if(li.match(pat) !== null){ | |
return true; | |
} | |
else{ | |
return false; | |
} | |
}); | |
console.log(modLinks); | |
this.openAllLinks(modLinks); | |
} | |
}) | |
mailparser.write(htmlBody); | |
mailparser.end(); | |
} | |
}); | |
} | |
// Opens all links in the browser. | |
openAllLinks(arr){ | |
arr.forEach(e => { | |
open(e); | |
}); | |
} | |
} | |
module.exports = Check; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment