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