1 | const http = require('http')
|
2 | const opn = require('opn')
|
3 | const getPort = require('get-port')
|
4 | const url = require('url')
|
5 | const oauth2Client = require('./auth')
|
6 | const { PORT = 3000 } = process.env
|
7 | const { getToken, getProfile } = require('./client')
|
8 | const Gmail = require('./gmail')
|
9 | const db = require('./db')
|
10 |
|
11 | const handler = async (req, res) => {
|
12 | console.log(req.url)
|
13 | const parsed = url.parse(req.url, true)
|
14 | console.log(parsed)
|
15 | if (!req.url.startsWith('/callback')) return
|
16 | const { tokens } = await getToken(parsed.query.code)
|
17 | const profile = await getProfile(tokens.access_token)
|
18 |
|
19 | let accounts = {
|
20 | [profile.emailAddress]: {
|
21 | profile,
|
22 | tokens
|
23 | }
|
24 | }
|
25 | db.set('prefs.accounts', accounts).write()
|
26 | let gmail = new Gmail(accounts)
|
27 | gmail.homeMenu()
|
28 | res.writeHead(200, { 'Content-Type': 'text/html' })
|
29 | res.end('<script> window.close(); </script>')
|
30 | }
|
31 |
|
32 | const server = http.createServer(handler)
|
33 |
|
34 | const scopes = [
|
35 | 'https://mail.google.com/',
|
36 | 'https://www.googleapis.com/auth/gmail.compose',
|
37 | 'https://www.googleapis.com/auth/gmail.modify',
|
38 | 'https://www.googleapis.com/auth/gmail.send'
|
39 | ]
|
40 |
|
41 | getPort({ port: PORT }).then(port => {
|
42 | console.log('http://localhost:' + port)
|
43 | server.listen(port, async () => {
|
44 | const auth = await oauth2Client()
|
45 | const url = await auth.generateAuthUrl({
|
46 | access_type: 'offline',
|
47 | scope: scopes
|
48 | })
|
49 | opn(url)
|
50 | })
|
51 | })
|