1 | const fetch = require('node-fetch')
|
2 | const chalk = require('chalk')
|
3 | const simpleParser = require('mailparser').simpleParser
|
4 |
|
5 | const headers = token => ({
|
6 | Authorization: `Bearer ${token}`,
|
7 | 'User-Agent': 'google-api-nodejs-client/0.10.0',
|
8 | host: 'www.googleapis.com',
|
9 | accept: 'application/json'
|
10 | })
|
11 |
|
12 | const deleteMessage = ({ id, accessToken }) => {
|
13 | const url = `https://www.googleapis.com/gmail/v1/users/me/messages/${id}/trash`
|
14 | return fetch(url, {
|
15 | method: 'POST',
|
16 | headers: headers(accessToken)
|
17 | })
|
18 | }
|
19 |
|
20 | const prettyPrint = (text) => {
|
21 | console.log(chalk.greenBright(text))
|
22 | }
|
23 |
|
24 | const parseMessage = (raw) => {
|
25 | const subject = raw.payload.headers.find(header => header.name === 'Subject').value
|
26 | const messageId = raw.payload.headers.find(header => header.name === 'Message-Id').value
|
27 | const sender = raw.payload.headers.find(header => header.name === 'From').value
|
28 | const to = raw.payload.headers.find(header => header.name === 'To').value
|
29 |
|
30 | return { subject, messageId, from: sender, to }
|
31 | }
|
32 |
|
33 | const quickMailParse = source => simpleParser(source)
|
34 |
|
35 | const parseAndFormatMail = async (source) => {
|
36 | const mail = await simpleParser(source)
|
37 | mail.html = 'undefined'
|
38 | mail.textAsHtml = 'undefined'
|
39 | const lines = []
|
40 | for (let key in mail) {
|
41 | if (typeof mail[key] === 'string' && mail[key] !== 'undefined') {
|
42 | lines.push(`${chalk.green(`${key}: `)}${mail[key]}`)
|
43 | } else if (mail[key].hasOwnProperty('value')) {
|
44 | lines.push(`${chalk.green(`${key}: `)}${mail[key].value[0].address}`)
|
45 | }
|
46 | }
|
47 | return lines
|
48 | }
|
49 |
|
50 | const printHeader = (account, messages) => {
|
51 | console.log(chalk.bold(`Welcome ${account.emailAddress}!`))
|
52 | console.log(chalk.bold(`Total messages: ${account.messagesTotal}`))
|
53 | console.log(chalk.yellow(`Messages in view: ${messages.length}`))
|
54 | }
|
55 |
|
56 | module.exports = {
|
57 | deleteMessage,
|
58 | headers,
|
59 | prettyPrint,
|
60 | printHeader,
|
61 | parseMessage,
|
62 | quickMailParse,
|
63 | parseAndFormatMail
|
64 | }
|