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