]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/emailer.ts
Feature/password reset link expiration (#2305)
[github/Chocobozzz/PeerTube.git] / server / lib / emailer.ts
1 import { createTransport, Transporter } from 'nodemailer'
2 import { isTestInstance } from '../helpers/core-utils'
3 import { bunyanLogger, logger } from '../helpers/logger'
4 import { CONFIG } from '../initializers/config'
5 import { JobQueue } from './job-queue'
6 import { EmailPayload } from './job-queue/handlers/email'
7 import { readFileSync } from 'fs-extra'
8 import { WEBSERVER } from '../initializers/constants'
9 import {
10 MCommentOwnerVideo,
11 MVideo,
12 MVideoAbuseVideo,
13 MVideoAccountLight,
14 MVideoBlacklistLightVideo,
15 MVideoBlacklistVideo
16 } from '../typings/models/video'
17 import { MActorFollowActors, MActorFollowFull, MUser } from '../typings/models'
18 import { MVideoImport, MVideoImportVideo } from '@server/typings/models/video/video-import'
19
20 type SendEmailOptions = {
21 to: string[]
22 subject: string
23 text: string
24
25 fromDisplayName?: string
26 replyTo?: string
27 }
28
29 class Emailer {
30
31 private static instance: Emailer
32 private initialized = false
33 private transporter: Transporter
34
35 private constructor () {}
36
37 init () {
38 // Already initialized
39 if (this.initialized === true) return
40 this.initialized = true
41
42 if (Emailer.isEnabled()) {
43 logger.info('Using %s:%s as SMTP server.', CONFIG.SMTP.HOSTNAME, CONFIG.SMTP.PORT)
44
45 let tls
46 if (CONFIG.SMTP.CA_FILE) {
47 tls = {
48 ca: [ readFileSync(CONFIG.SMTP.CA_FILE) ]
49 }
50 }
51
52 let auth
53 if (CONFIG.SMTP.USERNAME && CONFIG.SMTP.PASSWORD) {
54 auth = {
55 user: CONFIG.SMTP.USERNAME,
56 pass: CONFIG.SMTP.PASSWORD
57 }
58 }
59
60 this.transporter = createTransport({
61 host: CONFIG.SMTP.HOSTNAME,
62 port: CONFIG.SMTP.PORT,
63 secure: CONFIG.SMTP.TLS,
64 debug: CONFIG.LOG.LEVEL === 'debug',
65 logger: bunyanLogger as any,
66 ignoreTLS: CONFIG.SMTP.DISABLE_STARTTLS,
67 tls,
68 auth
69 })
70 } else {
71 if (!isTestInstance()) {
72 logger.error('Cannot use SMTP server because of lack of configuration. PeerTube will not be able to send mails!')
73 }
74 }
75 }
76
77 static isEnabled () {
78 return !!CONFIG.SMTP.HOSTNAME && !!CONFIG.SMTP.PORT
79 }
80
81 async checkConnectionOrDie () {
82 if (!this.transporter) return
83
84 logger.info('Testing SMTP server...')
85
86 try {
87 const success = await this.transporter.verify()
88 if (success !== true) this.dieOnConnectionFailure()
89
90 logger.info('Successfully connected to SMTP server.')
91 } catch (err) {
92 this.dieOnConnectionFailure(err)
93 }
94 }
95
96 addNewVideoFromSubscriberNotification (to: string[], video: MVideoAccountLight) {
97 const channelName = video.VideoChannel.getDisplayName()
98 const videoUrl = WEBSERVER.URL + video.getWatchStaticPath()
99
100 const text = `Hi dear user,\n\n` +
101 `Your subscription ${channelName} just published a new video: ${video.name}` +
102 `\n\n` +
103 `You can view it on ${videoUrl} ` +
104 `\n\n` +
105 `Cheers,\n` +
106 `${CONFIG.EMAIL.BODY.SIGNATURE}`
107
108 const emailPayload: EmailPayload = {
109 to,
110 subject: CONFIG.EMAIL.SUBJECT.PREFIX + channelName + ' just published a new video',
111 text
112 }
113
114 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
115 }
116
117 addNewFollowNotification (to: string[], actorFollow: MActorFollowFull, followType: 'account' | 'channel') {
118 const followerName = actorFollow.ActorFollower.Account.getDisplayName()
119 const followingName = (actorFollow.ActorFollowing.VideoChannel || actorFollow.ActorFollowing.Account).getDisplayName()
120
121 const text = `Hi dear user,\n\n` +
122 `Your ${followType} ${followingName} has a new subscriber: ${followerName}` +
123 `\n\n` +
124 `Cheers,\n` +
125 `${CONFIG.EMAIL.BODY.SIGNATURE}`
126
127 const emailPayload: EmailPayload = {
128 to,
129 subject: CONFIG.EMAIL.SUBJECT.PREFIX + 'New follower on your channel ' + followingName,
130 text
131 }
132
133 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
134 }
135
136 addNewInstanceFollowerNotification (to: string[], actorFollow: MActorFollowActors) {
137 const awaitingApproval = actorFollow.state === 'pending' ? ' awaiting manual approval.' : ''
138
139 const text = `Hi dear admin,\n\n` +
140 `Your instance has a new follower: ${actorFollow.ActorFollower.url}${awaitingApproval}` +
141 `\n\n` +
142 `Cheers,\n` +
143 `${CONFIG.EMAIL.BODY.SIGNATURE}`
144
145 const emailPayload: EmailPayload = {
146 to,
147 subject: CONFIG.EMAIL.SUBJECT.PREFIX + 'New instance follower',
148 text
149 }
150
151 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
152 }
153
154 addAutoInstanceFollowingNotification (to: string[], actorFollow: MActorFollowActors) {
155 const text = `Hi dear admin,\n\n` +
156 `Your instance automatically followed a new instance: ${actorFollow.ActorFollowing.url}` +
157 `\n\n` +
158 `Cheers,\n` +
159 `${CONFIG.EMAIL.BODY.SIGNATURE}`
160
161 const emailPayload: EmailPayload = {
162 to,
163 subject: CONFIG.EMAIL.SUBJECT.PREFIX + 'Auto instance following',
164 text
165 }
166
167 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
168 }
169
170 myVideoPublishedNotification (to: string[], video: MVideo) {
171 const videoUrl = WEBSERVER.URL + video.getWatchStaticPath()
172
173 const text = `Hi dear user,\n\n` +
174 `Your video ${video.name} has been published.` +
175 `\n\n` +
176 `You can view it on ${videoUrl} ` +
177 `\n\n` +
178 `Cheers,\n` +
179 `${CONFIG.EMAIL.BODY.SIGNATURE}`
180
181 const emailPayload: EmailPayload = {
182 to,
183 subject: CONFIG.EMAIL.SUBJECT.PREFIX + `Your video ${video.name} is published`,
184 text
185 }
186
187 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
188 }
189
190 myVideoImportSuccessNotification (to: string[], videoImport: MVideoImportVideo) {
191 const videoUrl = WEBSERVER.URL + videoImport.Video.getWatchStaticPath()
192
193 const text = `Hi dear user,\n\n` +
194 `Your video import ${videoImport.getTargetIdentifier()} is finished.` +
195 `\n\n` +
196 `You can view the imported video on ${videoUrl} ` +
197 `\n\n` +
198 `Cheers,\n` +
199 `${CONFIG.EMAIL.BODY.SIGNATURE}`
200
201 const emailPayload: EmailPayload = {
202 to,
203 subject: CONFIG.EMAIL.SUBJECT.PREFIX + `Your video import ${videoImport.getTargetIdentifier()} is finished`,
204 text
205 }
206
207 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
208 }
209
210 myVideoImportErrorNotification (to: string[], videoImport: MVideoImport) {
211 const importUrl = WEBSERVER.URL + '/my-account/video-imports'
212
213 const text = `Hi dear user,\n\n` +
214 `Your video import ${videoImport.getTargetIdentifier()} encountered an error.` +
215 `\n\n` +
216 `See your videos import dashboard for more information: ${importUrl}` +
217 `\n\n` +
218 `Cheers,\n` +
219 `${CONFIG.EMAIL.BODY.SIGNATURE}`
220
221 const emailPayload: EmailPayload = {
222 to,
223 subject: CONFIG.EMAIL.SUBJECT.PREFIX + `Your video import ${videoImport.getTargetIdentifier()} encountered an error`,
224 text
225 }
226
227 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
228 }
229
230 addNewCommentOnMyVideoNotification (to: string[], comment: MCommentOwnerVideo) {
231 const accountName = comment.Account.getDisplayName()
232 const video = comment.Video
233 const commentUrl = WEBSERVER.URL + comment.getCommentStaticPath()
234
235 const text = `Hi dear user,\n\n` +
236 `A new comment has been posted by ${accountName} on your video ${video.name}` +
237 `\n\n` +
238 `You can view it on ${commentUrl} ` +
239 `\n\n` +
240 `Cheers,\n` +
241 `${CONFIG.EMAIL.BODY.SIGNATURE}`
242
243 const emailPayload: EmailPayload = {
244 to,
245 subject: CONFIG.EMAIL.SUBJECT.PREFIX + 'New comment on your video ' + video.name,
246 text
247 }
248
249 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
250 }
251
252 addNewCommentMentionNotification (to: string[], comment: MCommentOwnerVideo) {
253 const accountName = comment.Account.getDisplayName()
254 const video = comment.Video
255 const commentUrl = WEBSERVER.URL + comment.getCommentStaticPath()
256
257 const text = `Hi dear user,\n\n` +
258 `${accountName} mentioned you on video ${video.name}` +
259 `\n\n` +
260 `You can view the comment on ${commentUrl} ` +
261 `\n\n` +
262 `Cheers,\n` +
263 `${CONFIG.EMAIL.BODY.SIGNATURE}`
264
265 const emailPayload: EmailPayload = {
266 to,
267 subject: CONFIG.EMAIL.SUBJECT.PREFIX + 'Mention on video ' + video.name,
268 text
269 }
270
271 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
272 }
273
274 addVideoAbuseModeratorsNotification (to: string[], videoAbuse: MVideoAbuseVideo) {
275 const videoUrl = WEBSERVER.URL + videoAbuse.Video.getWatchStaticPath()
276
277 const text = `Hi,\n\n` +
278 `${WEBSERVER.HOST} received an abuse for the following video ${videoUrl}\n\n` +
279 `Cheers,\n` +
280 `${CONFIG.EMAIL.BODY.SIGNATURE}`
281
282 const emailPayload: EmailPayload = {
283 to,
284 subject: CONFIG.EMAIL.SUBJECT.PREFIX + 'Received a video abuse',
285 text
286 }
287
288 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
289 }
290
291 addVideoAutoBlacklistModeratorsNotification (to: string[], videoBlacklist: MVideoBlacklistLightVideo) {
292 const VIDEO_AUTO_BLACKLIST_URL = WEBSERVER.URL + '/admin/moderation/video-auto-blacklist/list'
293 const videoUrl = WEBSERVER.URL + videoBlacklist.Video.getWatchStaticPath()
294
295 const text = `Hi,\n\n` +
296 `A recently added video was auto-blacklisted and requires moderator review before publishing.` +
297 `\n\n` +
298 `You can view it and take appropriate action on ${videoUrl}` +
299 `\n\n` +
300 `A full list of auto-blacklisted videos can be reviewed here: ${VIDEO_AUTO_BLACKLIST_URL}` +
301 `\n\n` +
302 `Cheers,\n` +
303 `${CONFIG.EMAIL.BODY.SIGNATURE}`
304
305 const emailPayload: EmailPayload = {
306 to,
307 subject: CONFIG.EMAIL.SUBJECT.PREFIX + 'An auto-blacklisted video is awaiting review',
308 text
309 }
310
311 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
312 }
313
314 addNewUserRegistrationNotification (to: string[], user: MUser) {
315 const text = `Hi,\n\n` +
316 `User ${user.username} just registered on ${WEBSERVER.HOST} PeerTube instance.\n\n` +
317 `Cheers,\n` +
318 `${CONFIG.EMAIL.BODY.SIGNATURE}`
319
320 const emailPayload: EmailPayload = {
321 to,
322 subject: CONFIG.EMAIL.SUBJECT.PREFIX + 'New user registration on ' + WEBSERVER.HOST,
323 text
324 }
325
326 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
327 }
328
329 addVideoBlacklistNotification (to: string[], videoBlacklist: MVideoBlacklistVideo) {
330 const videoName = videoBlacklist.Video.name
331 const videoUrl = WEBSERVER.URL + videoBlacklist.Video.getWatchStaticPath()
332
333 const reasonString = videoBlacklist.reason ? ` for the following reason: ${videoBlacklist.reason}` : ''
334 const blockedString = `Your video ${videoName} (${videoUrl} on ${WEBSERVER.HOST} has been blacklisted${reasonString}.`
335
336 const text = 'Hi,\n\n' +
337 blockedString +
338 '\n\n' +
339 'Cheers,\n' +
340 `${CONFIG.EMAIL.BODY.SIGNATURE}`
341
342 const emailPayload: EmailPayload = {
343 to,
344 subject: CONFIG.EMAIL.SUBJECT.PREFIX + `Video ${videoName} blacklisted`,
345 text
346 }
347
348 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
349 }
350
351 addVideoUnblacklistNotification (to: string[], video: MVideo) {
352 const videoUrl = WEBSERVER.URL + video.getWatchStaticPath()
353
354 const text = 'Hi,\n\n' +
355 `Your video ${video.name} (${videoUrl}) on ${WEBSERVER.HOST} has been unblacklisted.` +
356 '\n\n' +
357 'Cheers,\n' +
358 `${CONFIG.EMAIL.BODY.SIGNATURE}`
359
360 const emailPayload: EmailPayload = {
361 to,
362 subject: CONFIG.EMAIL.SUBJECT.PREFIX + `Video ${video.name} unblacklisted`,
363 text
364 }
365
366 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
367 }
368
369 addPasswordResetEmailJob (to: string, resetPasswordUrl: string) {
370 const text = `Hi dear user,\n\n` +
371 `A reset password procedure for your account ${to} has been requested on ${WEBSERVER.HOST} ` +
372 `Please follow this link to reset it: ${resetPasswordUrl} (the link will expire within 1 hour)\n\n` +
373 `If you are not the person who initiated this request, please ignore this email.\n\n` +
374 `Cheers,\n` +
375 `${CONFIG.EMAIL.BODY.SIGNATURE}`
376
377 const emailPayload: EmailPayload = {
378 to: [ to ],
379 subject: CONFIG.EMAIL.SUBJECT.PREFIX + 'Reset your password',
380 text
381 }
382
383 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
384 }
385
386 addVerifyEmailJob (to: string, verifyEmailUrl: string) {
387 const text = `Welcome to PeerTube,\n\n` +
388 `To start using PeerTube on ${WEBSERVER.HOST} you must verify your email! ` +
389 `Please follow this link to verify this email belongs to you: ${verifyEmailUrl}\n\n` +
390 `If you are not the person who initiated this request, please ignore this email.\n\n` +
391 `Cheers,\n` +
392 `${CONFIG.EMAIL.BODY.SIGNATURE}`
393
394 const emailPayload: EmailPayload = {
395 to: [ to ],
396 subject: CONFIG.EMAIL.SUBJECT.PREFIX + 'Verify your email',
397 text
398 }
399
400 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
401 }
402
403 addUserBlockJob (user: MUser, blocked: boolean, reason?: string) {
404 const reasonString = reason ? ` for the following reason: ${reason}` : ''
405 const blockedWord = blocked ? 'blocked' : 'unblocked'
406 const blockedString = `Your account ${user.username} on ${WEBSERVER.HOST} has been ${blockedWord}${reasonString}.`
407
408 const text = 'Hi,\n\n' +
409 blockedString +
410 '\n\n' +
411 'Cheers,\n' +
412 `${CONFIG.EMAIL.BODY.SIGNATURE}`
413
414 const to = user.email
415 const emailPayload: EmailPayload = {
416 to: [ to ],
417 subject: CONFIG.EMAIL.SUBJECT.PREFIX + 'Account ' + blockedWord,
418 text
419 }
420
421 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
422 }
423
424 addContactFormJob (fromEmail: string, fromName: string, subject: string, body: string) {
425 const text = 'Hello dear admin,\n\n' +
426 fromName + ' sent you a message' +
427 '\n\n---------------------------------------\n\n' +
428 body +
429 '\n\n---------------------------------------\n\n' +
430 'Cheers,\n' +
431 'PeerTube.'
432
433 const emailPayload: EmailPayload = {
434 fromDisplayName: fromEmail,
435 replyTo: fromEmail,
436 to: [ CONFIG.ADMIN.EMAIL ],
437 subject: CONFIG.EMAIL.SUBJECT.PREFIX + subject,
438 text
439 }
440
441 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
442 }
443
444 async sendMail (options: EmailPayload) {
445 if (!Emailer.isEnabled()) {
446 throw new Error('Cannot send mail because SMTP is not configured.')
447 }
448
449 const fromDisplayName = options.fromDisplayName
450 ? options.fromDisplayName
451 : WEBSERVER.HOST
452
453 for (const to of options.to) {
454 await this.transporter.sendMail({
455 from: `"${fromDisplayName}" <${CONFIG.SMTP.FROM_ADDRESS}>`,
456 replyTo: options.replyTo,
457 to,
458 subject: options.subject,
459 text: options.text
460 })
461 }
462 }
463
464 private dieOnConnectionFailure (err?: Error) {
465 logger.error('Failed to connect to SMTP %s:%d.', CONFIG.SMTP.HOSTNAME, CONFIG.SMTP.PORT, { err })
466 process.exit(-1)
467 }
468
469 static get Instance () {
470 return this.instance || (this.instance = new this())
471 }
472 }
473
474 // ---------------------------------------------------------------------------
475
476 export {
477 Emailer,
478 SendEmailOptions
479 }