]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/emailer.ts
Update my email
[github/Chocobozzz/PeerTube.git] / server / lib / emailer.ts
1 import { readFileSync } from 'fs-extra'
2 import { merge } from 'lodash'
3 import { createTransport, Transporter } from 'nodemailer'
4 import { join } from 'path'
5 import { VideoChannelModel } from '@server/models/video/video-channel'
6 import { MVideoBlacklistLightVideo, MVideoBlacklistVideo } from '@server/types/models/video/video-blacklist'
7 import { MVideoImport, MVideoImportVideo } from '@server/types/models/video/video-import'
8 import { AbuseState, EmailPayload, UserAbuse } from '@shared/models'
9 import { SendEmailOptions } from '../../shared/models/server/emailer.model'
10 import { isTestInstance, root } from '../helpers/core-utils'
11 import { bunyanLogger, logger } from '../helpers/logger'
12 import { CONFIG, isEmailEnabled } from '../initializers/config'
13 import { WEBSERVER } from '../initializers/constants'
14 import { MAbuseFull, MAbuseMessage, MAccountDefault, MActorFollowActors, MActorFollowFull, MUser } from '../types/models'
15 import { MCommentOwnerVideo, MVideo, MVideoAccountLight } from '../types/models/video'
16 import { JobQueue } from './job-queue'
17
18 const sanitizeHtml = require('sanitize-html')
19 const markdownItEmoji = require('markdown-it-emoji/light')
20 const MarkdownItClass = require('markdown-it')
21 const markdownIt = new MarkdownItClass('default', { linkify: true, breaks: true, html: true })
22
23 markdownIt.enable([
24 'linkify',
25 'autolink',
26 'emphasis',
27 'link',
28 'newline',
29 'list'
30 ])
31
32 markdownIt.use(markdownItEmoji)
33
34 const toSafeHtml = text => {
35 // Restore line feed
36 const textWithLineFeed = text.replace(/<br.?\/?>/g, '\r\n')
37
38 // Convert possible markdown (emojis, emphasis and lists) to html
39 const html = markdownIt.render(textWithLineFeed)
40
41 // Convert to safe Html
42 return sanitizeHtml(html, {
43 allowedTags: [ 'a', 'p', 'span', 'br', 'strong', 'em', 'ul', 'ol', 'li' ],
44 allowedSchemes: [ 'http', 'https' ],
45 allowedAttributes: {
46 a: [ 'href', 'class', 'target', 'rel' ]
47 },
48 transformTags: {
49 a: (tagName, attribs) => {
50 let rel = 'noopener noreferrer'
51 if (attribs.rel === 'me') rel += ' me'
52
53 return {
54 tagName,
55 attribs: Object.assign(attribs, {
56 target: '_blank',
57 rel
58 })
59 }
60 }
61 }
62 })
63 }
64
65 const Email = require('email-templates')
66
67 class Emailer {
68
69 private static instance: Emailer
70 private initialized = false
71 private transporter: Transporter
72
73 private constructor () {
74 }
75
76 init () {
77 // Already initialized
78 if (this.initialized === true) return
79 this.initialized = true
80
81 if (isEmailEnabled()) {
82 if (CONFIG.SMTP.TRANSPORT === 'smtp') {
83 logger.info('Using %s:%s as SMTP server.', CONFIG.SMTP.HOSTNAME, CONFIG.SMTP.PORT)
84
85 let tls
86 if (CONFIG.SMTP.CA_FILE) {
87 tls = {
88 ca: [ readFileSync(CONFIG.SMTP.CA_FILE) ]
89 }
90 }
91
92 let auth
93 if (CONFIG.SMTP.USERNAME && CONFIG.SMTP.PASSWORD) {
94 auth = {
95 user: CONFIG.SMTP.USERNAME,
96 pass: CONFIG.SMTP.PASSWORD
97 }
98 }
99
100 this.transporter = createTransport({
101 host: CONFIG.SMTP.HOSTNAME,
102 port: CONFIG.SMTP.PORT,
103 secure: CONFIG.SMTP.TLS,
104 debug: CONFIG.LOG.LEVEL === 'debug',
105 logger: bunyanLogger as any,
106 ignoreTLS: CONFIG.SMTP.DISABLE_STARTTLS,
107 tls,
108 auth
109 })
110 } else { // sendmail
111 logger.info('Using sendmail to send emails')
112
113 this.transporter = createTransport({
114 sendmail: true,
115 newline: 'unix',
116 path: CONFIG.SMTP.SENDMAIL
117 })
118 }
119 } else {
120 if (!isTestInstance()) {
121 logger.error('Cannot use SMTP server because of lack of configuration. PeerTube will not be able to send mails!')
122 }
123 }
124 }
125
126 static isEnabled () {
127 if (CONFIG.SMTP.TRANSPORT === 'sendmail') {
128 return !!CONFIG.SMTP.SENDMAIL
129 } else if (CONFIG.SMTP.TRANSPORT === 'smtp') {
130 return !!CONFIG.SMTP.HOSTNAME && !!CONFIG.SMTP.PORT
131 } else {
132 return false
133 }
134 }
135
136 async checkConnectionOrDie () {
137 if (!this.transporter || CONFIG.SMTP.TRANSPORT !== 'smtp') return
138
139 logger.info('Testing SMTP server...')
140
141 try {
142 const success = await this.transporter.verify()
143 if (success !== true) this.dieOnConnectionFailure()
144
145 logger.info('Successfully connected to SMTP server.')
146 } catch (err) {
147 this.dieOnConnectionFailure(err)
148 }
149 }
150
151 addNewVideoFromSubscriberNotification (to: string[], video: MVideoAccountLight) {
152 const channelName = video.VideoChannel.getDisplayName()
153 const videoUrl = WEBSERVER.URL + video.getWatchStaticPath()
154
155 const emailPayload: EmailPayload = {
156 to,
157 subject: channelName + ' just published a new video',
158 text: `Your subscription ${channelName} just published a new video: "${video.name}".`,
159 locals: {
160 title: 'New content ',
161 action: {
162 text: 'View video',
163 url: videoUrl
164 }
165 }
166 }
167
168 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
169 }
170
171 addNewFollowNotification (to: string[], actorFollow: MActorFollowFull, followType: 'account' | 'channel') {
172 const followingName = (actorFollow.ActorFollowing.VideoChannel || actorFollow.ActorFollowing.Account).getDisplayName()
173
174 const emailPayload: EmailPayload = {
175 template: 'follower-on-channel',
176 to,
177 subject: `New follower on your channel ${followingName}`,
178 locals: {
179 followerName: actorFollow.ActorFollower.Account.getDisplayName(),
180 followerUrl: actorFollow.ActorFollower.url,
181 followingName,
182 followingUrl: actorFollow.ActorFollowing.url,
183 followType
184 }
185 }
186
187 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
188 }
189
190 addNewInstanceFollowerNotification (to: string[], actorFollow: MActorFollowActors) {
191 const awaitingApproval = actorFollow.state === 'pending' ? ' awaiting manual approval.' : ''
192
193 const emailPayload: EmailPayload = {
194 to,
195 subject: 'New instance follower',
196 text: `Your instance has a new follower: ${actorFollow.ActorFollower.url}${awaitingApproval}.`,
197 locals: {
198 title: 'New instance follower',
199 action: {
200 text: 'Review followers',
201 url: WEBSERVER.URL + '/admin/follows/followers-list'
202 }
203 }
204 }
205
206 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
207 }
208
209 addAutoInstanceFollowingNotification (to: string[], actorFollow: MActorFollowActors) {
210 const instanceUrl = actorFollow.ActorFollowing.url
211 const emailPayload: EmailPayload = {
212 to,
213 subject: 'Auto instance following',
214 text: `Your instance automatically followed a new instance: <a href="${instanceUrl}">${instanceUrl}</a>.`
215 }
216
217 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
218 }
219
220 myVideoPublishedNotification (to: string[], video: MVideo) {
221 const videoUrl = WEBSERVER.URL + video.getWatchStaticPath()
222
223 const emailPayload: EmailPayload = {
224 to,
225 subject: `Your video ${video.name} has been published`,
226 text: `Your video "${video.name}" has been published.`,
227 locals: {
228 title: 'You video is live',
229 action: {
230 text: 'View video',
231 url: videoUrl
232 }
233 }
234 }
235
236 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
237 }
238
239 myVideoImportSuccessNotification (to: string[], videoImport: MVideoImportVideo) {
240 const videoUrl = WEBSERVER.URL + videoImport.Video.getWatchStaticPath()
241
242 const emailPayload: EmailPayload = {
243 to,
244 subject: `Your video import ${videoImport.getTargetIdentifier()} is complete`,
245 text: `Your video "${videoImport.getTargetIdentifier()}" just finished importing.`,
246 locals: {
247 title: 'Import complete',
248 action: {
249 text: 'View video',
250 url: videoUrl
251 }
252 }
253 }
254
255 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
256 }
257
258 myVideoImportErrorNotification (to: string[], videoImport: MVideoImport) {
259 const importUrl = WEBSERVER.URL + '/my-account/video-imports'
260
261 const text =
262 `Your video import "${videoImport.getTargetIdentifier()}" encountered an error.` +
263 '\n\n' +
264 `See your videos import dashboard for more information: <a href="${importUrl}">${importUrl}</a>.`
265
266 const emailPayload: EmailPayload = {
267 to,
268 subject: `Your video import "${videoImport.getTargetIdentifier()}" encountered an error`,
269 text,
270 locals: {
271 title: 'Import failed',
272 action: {
273 text: 'Review imports',
274 url: importUrl
275 }
276 }
277 }
278
279 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
280 }
281
282 addNewCommentOnMyVideoNotification (to: string[], comment: MCommentOwnerVideo) {
283 const video = comment.Video
284 const videoUrl = WEBSERVER.URL + comment.Video.getWatchStaticPath()
285 const commentUrl = WEBSERVER.URL + comment.getCommentStaticPath()
286 const commentHtml = toSafeHtml(comment.text)
287
288 const emailPayload: EmailPayload = {
289 template: 'video-comment-new',
290 to,
291 subject: 'New comment on your video ' + video.name,
292 locals: {
293 accountName: comment.Account.getDisplayName(),
294 accountUrl: comment.Account.Actor.url,
295 comment,
296 commentHtml,
297 video,
298 videoUrl,
299 action: {
300 text: 'View comment',
301 url: commentUrl
302 }
303 }
304 }
305
306 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
307 }
308
309 addNewCommentMentionNotification (to: string[], comment: MCommentOwnerVideo) {
310 const accountName = comment.Account.getDisplayName()
311 const video = comment.Video
312 const videoUrl = WEBSERVER.URL + comment.Video.getWatchStaticPath()
313 const commentUrl = WEBSERVER.URL + comment.getCommentStaticPath()
314 const commentHtml = toSafeHtml(comment.text)
315
316 const emailPayload: EmailPayload = {
317 template: 'video-comment-mention',
318 to,
319 subject: 'Mention on video ' + video.name,
320 locals: {
321 comment,
322 commentHtml,
323 video,
324 videoUrl,
325 accountName,
326 action: {
327 text: 'View comment',
328 url: commentUrl
329 }
330 }
331 }
332
333 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
334 }
335
336 addAbuseModeratorsNotification (to: string[], parameters: {
337 abuse: UserAbuse
338 abuseInstance: MAbuseFull
339 reporter: string
340 }) {
341 const { abuse, abuseInstance, reporter } = parameters
342
343 const action = {
344 text: 'View report #' + abuse.id,
345 url: WEBSERVER.URL + '/admin/moderation/abuses/list?search=%23' + abuse.id
346 }
347
348 let emailPayload: EmailPayload
349
350 if (abuseInstance.VideoAbuse) {
351 const video = abuseInstance.VideoAbuse.Video
352 const videoUrl = WEBSERVER.URL + video.getWatchStaticPath()
353
354 emailPayload = {
355 template: 'video-abuse-new',
356 to,
357 subject: `New video abuse report from ${reporter}`,
358 locals: {
359 videoUrl,
360 isLocal: video.remote === false,
361 videoCreatedAt: new Date(video.createdAt).toLocaleString(),
362 videoPublishedAt: new Date(video.publishedAt).toLocaleString(),
363 videoName: video.name,
364 reason: abuse.reason,
365 videoChannel: abuse.video.channel,
366 reporter,
367 action
368 }
369 }
370 } else if (abuseInstance.VideoCommentAbuse) {
371 const comment = abuseInstance.VideoCommentAbuse.VideoComment
372 const commentUrl = WEBSERVER.URL + comment.Video.getWatchStaticPath() + ';threadId=' + comment.getThreadId()
373
374 emailPayload = {
375 template: 'video-comment-abuse-new',
376 to,
377 subject: `New comment abuse report from ${reporter}`,
378 locals: {
379 commentUrl,
380 videoName: comment.Video.name,
381 isLocal: comment.isOwned(),
382 commentCreatedAt: new Date(comment.createdAt).toLocaleString(),
383 reason: abuse.reason,
384 flaggedAccount: abuseInstance.FlaggedAccount.getDisplayName(),
385 reporter,
386 action
387 }
388 }
389 } else {
390 const account = abuseInstance.FlaggedAccount
391 const accountUrl = account.getClientUrl()
392
393 emailPayload = {
394 template: 'account-abuse-new',
395 to,
396 subject: `New account abuse report from ${reporter}`,
397 locals: {
398 accountUrl,
399 accountDisplayName: account.getDisplayName(),
400 isLocal: account.isOwned(),
401 reason: abuse.reason,
402 reporter,
403 action
404 }
405 }
406 }
407
408 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
409 }
410
411 addAbuseStateChangeNotification (to: string[], abuse: MAbuseFull) {
412 const text = abuse.state === AbuseState.ACCEPTED
413 ? 'Report #' + abuse.id + ' has been accepted'
414 : 'Report #' + abuse.id + ' has been rejected'
415
416 const abuseUrl = WEBSERVER.URL + '/my-account/abuses?search=%23' + abuse.id
417
418 const action = {
419 text,
420 url: abuseUrl
421 }
422
423 const emailPayload: EmailPayload = {
424 template: 'abuse-state-change',
425 to,
426 subject: text,
427 locals: {
428 action,
429 abuseId: abuse.id,
430 abuseUrl,
431 isAccepted: abuse.state === AbuseState.ACCEPTED
432 }
433 }
434
435 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
436 }
437
438 addAbuseNewMessageNotification (
439 to: string[],
440 options: {
441 target: 'moderator' | 'reporter'
442 abuse: MAbuseFull
443 message: MAbuseMessage
444 accountMessage: MAccountDefault
445 }) {
446 const { abuse, target, message, accountMessage } = options
447
448 const text = 'New message on report #' + abuse.id
449 const abuseUrl = target === 'moderator'
450 ? WEBSERVER.URL + '/admin/moderation/abuses/list?search=%23' + abuse.id
451 : WEBSERVER.URL + '/my-account/abuses?search=%23' + abuse.id
452
453 const action = {
454 text,
455 url: abuseUrl
456 }
457
458 const emailPayload: EmailPayload = {
459 template: 'abuse-new-message',
460 to,
461 subject: text,
462 locals: {
463 abuseId: abuse.id,
464 abuseUrl: action.url,
465 messageAccountName: accountMessage.getDisplayName(),
466 messageText: message.message,
467 action
468 }
469 }
470
471 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
472 }
473
474 async addVideoAutoBlacklistModeratorsNotification (to: string[], videoBlacklist: MVideoBlacklistLightVideo) {
475 const VIDEO_AUTO_BLACKLIST_URL = WEBSERVER.URL + '/admin/moderation/video-auto-blacklist/list'
476 const videoUrl = WEBSERVER.URL + videoBlacklist.Video.getWatchStaticPath()
477 const channel = (await VideoChannelModel.loadByIdAndPopulateAccount(videoBlacklist.Video.channelId)).toFormattedSummaryJSON()
478
479 const emailPayload: EmailPayload = {
480 template: 'video-auto-blacklist-new',
481 to,
482 subject: 'A new video is pending moderation',
483 locals: {
484 channel,
485 videoUrl,
486 videoName: videoBlacklist.Video.name,
487 action: {
488 text: 'Review autoblacklist',
489 url: VIDEO_AUTO_BLACKLIST_URL
490 }
491 }
492 }
493
494 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
495 }
496
497 addNewUserRegistrationNotification (to: string[], user: MUser) {
498 const emailPayload: EmailPayload = {
499 template: 'user-registered',
500 to,
501 subject: `a new user registered on ${WEBSERVER.HOST}: ${user.username}`,
502 locals: {
503 user
504 }
505 }
506
507 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
508 }
509
510 addVideoBlacklistNotification (to: string[], videoBlacklist: MVideoBlacklistVideo) {
511 const videoName = videoBlacklist.Video.name
512 const videoUrl = WEBSERVER.URL + videoBlacklist.Video.getWatchStaticPath()
513
514 const reasonString = videoBlacklist.reason ? ` for the following reason: ${videoBlacklist.reason}` : ''
515 const blockedString = `Your video ${videoName} (${videoUrl} on ${WEBSERVER.HOST} has been blacklisted${reasonString}.`
516
517 const emailPayload: EmailPayload = {
518 to,
519 subject: `Video ${videoName} blacklisted`,
520 text: blockedString,
521 locals: {
522 title: 'Your video was blacklisted'
523 }
524 }
525
526 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
527 }
528
529 addVideoUnblacklistNotification (to: string[], video: MVideo) {
530 const videoUrl = WEBSERVER.URL + video.getWatchStaticPath()
531
532 const emailPayload: EmailPayload = {
533 to,
534 subject: `Video ${video.name} unblacklisted`,
535 text: `Your video "${video.name}" (${videoUrl}) on ${WEBSERVER.HOST} has been unblacklisted.`,
536 locals: {
537 title: 'Your video was unblacklisted'
538 }
539 }
540
541 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
542 }
543
544 addPasswordResetEmailJob (username: string, to: string, resetPasswordUrl: string) {
545 const emailPayload: EmailPayload = {
546 template: 'password-reset',
547 to: [ to ],
548 subject: 'Reset your account password',
549 locals: {
550 username,
551 resetPasswordUrl
552 }
553 }
554
555 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
556 }
557
558 addPasswordCreateEmailJob (username: string, to: string, createPasswordUrl: string) {
559 const emailPayload: EmailPayload = {
560 template: 'password-create',
561 to: [ to ],
562 subject: 'Create your account password',
563 locals: {
564 username,
565 createPasswordUrl
566 }
567 }
568
569 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
570 }
571
572 addVerifyEmailJob (username: string, to: string, verifyEmailUrl: string) {
573 const emailPayload: EmailPayload = {
574 template: 'verify-email',
575 to: [ to ],
576 subject: `Verify your email on ${WEBSERVER.HOST}`,
577 locals: {
578 username,
579 verifyEmailUrl
580 }
581 }
582
583 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
584 }
585
586 addUserBlockJob (user: MUser, blocked: boolean, reason?: string) {
587 const reasonString = reason ? ` for the following reason: ${reason}` : ''
588 const blockedWord = blocked ? 'blocked' : 'unblocked'
589
590 const to = user.email
591 const emailPayload: EmailPayload = {
592 to: [ to ],
593 subject: 'Account ' + blockedWord,
594 text: `Your account ${user.username} on ${WEBSERVER.HOST} has been ${blockedWord}${reasonString}.`
595 }
596
597 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
598 }
599
600 addContactFormJob (fromEmail: string, fromName: string, subject: string, body: string) {
601 const emailPayload: EmailPayload = {
602 template: 'contact-form',
603 to: [ CONFIG.ADMIN.EMAIL ],
604 replyTo: `"${fromName}" <${fromEmail}>`,
605 subject: `(contact form) ${subject}`,
606 locals: {
607 fromName,
608 fromEmail,
609 body,
610
611 // There are not notification preferences for the contact form
612 hideNotificationPreferences: true
613 }
614 }
615
616 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
617 }
618
619 async sendMail (options: EmailPayload) {
620 if (!isEmailEnabled()) {
621 throw new Error('Cannot send mail because SMTP is not configured.')
622 }
623
624 const fromDisplayName = options.from
625 ? options.from
626 : WEBSERVER.HOST
627
628 const email = new Email({
629 send: true,
630 message: {
631 from: `"${fromDisplayName}" <${CONFIG.SMTP.FROM_ADDRESS}>`
632 },
633 transport: this.transporter,
634 views: {
635 root: join(root(), 'dist', 'server', 'lib', 'emails')
636 },
637 subjectPrefix: CONFIG.EMAIL.SUBJECT.PREFIX
638 })
639
640 for (const to of options.to) {
641 await email
642 .send(merge(
643 {
644 template: 'common',
645 message: {
646 to,
647 from: options.from,
648 subject: options.subject,
649 replyTo: options.replyTo
650 },
651 locals: { // default variables available in all templates
652 WEBSERVER,
653 EMAIL: CONFIG.EMAIL,
654 text: options.text,
655 subject: options.subject
656 }
657 },
658 options // overriden/new variables given for a specific template in the payload
659 ) as SendEmailOptions)
660 .then(res => logger.debug('Sent email.', { res }))
661 .catch(err => logger.error('Error in email sender.', { err }))
662 }
663 }
664
665 private dieOnConnectionFailure (err?: Error) {
666 logger.error('Failed to connect to SMTP %s:%d.', CONFIG.SMTP.HOSTNAME, CONFIG.SMTP.PORT, { err })
667 process.exit(-1)
668 }
669
670 static get Instance () {
671 return this.instance || (this.instance = new this())
672 }
673 }
674
675 // ---------------------------------------------------------------------------
676
677 export {
678 Emailer
679 }