9c105a57530021c7c163d10dc5aeb076d05ff6d5
[oweals/peertube.git] / server / lib / emailer.ts
1 import { createTransport, Transporter } from 'nodemailer'
2 import { UserRight } from '../../shared/models/users'
3 import { isTestInstance } from '../helpers/core-utils'
4 import { bunyanLogger, logger } from '../helpers/logger'
5 import { CONFIG } from '../initializers'
6 import { UserModel } from '../models/account/user'
7 import { VideoModel } from '../models/video/video'
8 import { JobQueue } from './job-queue'
9 import { EmailPayload } from './job-queue/handlers/email'
10 import { readFileSync } from 'fs'
11
12 class Emailer {
13
14   private static instance: Emailer
15   private initialized = false
16   private transporter: Transporter
17
18   private constructor () {}
19
20   init () {
21     // Already initialized
22     if (this.initialized === true) return
23     this.initialized = true
24
25     if (CONFIG.SMTP.HOSTNAME && CONFIG.SMTP.PORT) {
26       logger.info('Using %s:%s as SMTP server.', CONFIG.SMTP.HOSTNAME, CONFIG.SMTP.PORT)
27
28       let tls
29       if (CONFIG.SMTP.CA_FILE) {
30         tls = {
31           ca: [ readFileSync(CONFIG.SMTP.CA_FILE) ]
32         }
33       }
34
35       let auth
36       if (CONFIG.SMTP.USERNAME && CONFIG.SMTP.PASSWORD) {
37         auth = {
38           user: CONFIG.SMTP.USERNAME,
39           pass: CONFIG.SMTP.PASSWORD
40         }
41       }
42
43       this.transporter = createTransport({
44         host: CONFIG.SMTP.HOSTNAME,
45         port: CONFIG.SMTP.PORT,
46         secure: CONFIG.SMTP.TLS,
47         debug: CONFIG.LOG.LEVEL === 'debug',
48         logger: bunyanLogger as any,
49         ignoreTLS: isTestInstance(),
50         tls,
51         auth
52       })
53     } else {
54       if (!isTestInstance()) {
55         logger.error('Cannot use SMTP server because of lack of configuration. PeerTube will not be able to send mails!')
56       }
57     }
58   }
59
60   async checkConnectionOrDie () {
61     if (!this.transporter) return
62
63     try {
64       const success = await this.transporter.verify()
65       if (success !== true) this.dieOnConnectionFailure()
66
67       logger.info('Successfully connected to SMTP server.')
68     } catch (err) {
69       this.dieOnConnectionFailure(err)
70     }
71   }
72
73   addForgetPasswordEmailJob (to: string, resetPasswordUrl: string) {
74     const text = `Hi dear user,\n\n` +
75       `It seems you forgot your password on ${CONFIG.WEBSERVER.HOST}! ` +
76       `Please follow this link to reset it: ${resetPasswordUrl}.\n\n` +
77       `If you are not the person who initiated this request, please ignore this email.\n\n` +
78       `Cheers,\n` +
79       `PeerTube.`
80
81     const emailPayload: EmailPayload = {
82       to: [ to ],
83       subject: 'Reset your PeerTube password',
84       text
85     }
86
87     return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
88   }
89
90   async addVideoAbuseReport (videoId: number) {
91     const video = await VideoModel.load(videoId)
92
93     const text = `Hi,\n\n` +
94       `Your instance received an abuse for video the following video ${video.url}\n\n` +
95       `Cheers,\n` +
96       `PeerTube.`
97
98     const to = await UserModel.listEmailsWithRight(UserRight.MANAGE_VIDEO_ABUSES)
99     const emailPayload: EmailPayload = {
100       to,
101       subject: '[PeerTube] Received a video abuse',
102       text
103     }
104
105     return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
106   }
107
108   sendMail (to: string[], subject: string, text: string) {
109     if (!this.transporter) {
110       throw new Error('Cannot send mail because SMTP is not configured.')
111     }
112
113     return this.transporter.sendMail({
114       from: CONFIG.SMTP.FROM_ADDRESS,
115       to: to.join(','),
116       subject,
117       text
118     })
119   }
120
121   private dieOnConnectionFailure (err?: Error) {
122     logger.error('Failed to connect to SMTP %s:%d.', CONFIG.SMTP.HOSTNAME, CONFIG.SMTP.PORT, err)
123     process.exit(-1)
124   }
125
126   static get Instance () {
127     return this.instance || (this.instance = new this())
128   }
129 }
130
131 // ---------------------------------------------------------------------------
132
133 export {
134   Emailer
135 }