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'
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 })
24 markdownIt.enable(TEXT_WITH_HTML_RULES)
26 markdownIt.use(markdownItEmoji)
28 const toSafeHtml = text => {
30 const textWithLineFeed = text.replace(/<br.?\/?>/g, '\r\n')
32 // Convert possible markdown (emojis, emphasis and lists) to html
33 const html = markdownIt.render(textWithLineFeed)
35 // Convert to safe Html
36 return sanitizeHtml(html, SANITIZE_OPTIONS)
39 const Email = require('email-templates')
43 private static instance: Emailer
44 private initialized = false
45 private transporter: Transporter
47 private constructor () {
51 // Already initialized
52 if (this.initialized === true) return
53 this.initialized = true
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!')
63 if (CONFIG.SMTP.TRANSPORT === 'smtp') this.initSMTPTransport()
64 else if (CONFIG.SMTP.TRANSPORT === 'sendmail') this.initSendmailTransport()
67 async checkConnection () {
68 if (!this.transporter || CONFIG.SMTP.TRANSPORT !== 'smtp') return
70 logger.info('Testing SMTP server...')
73 const success = await this.transporter.verify()
74 if (success !== true) this.warnOnConnectionFailure()
76 logger.info('Successfully connected to SMTP server.')
78 this.warnOnConnectionFailure(err)
82 addNewVideoFromSubscriberNotification (to: string[], video: MVideoAccountLight) {
83 const channelName = video.VideoChannel.getDisplayName()
84 const videoUrl = WEBSERVER.URL + video.getWatchStaticPath()
86 const emailPayload: EmailPayload = {
88 subject: channelName + ' just published a new video',
89 text: `Your subscription ${channelName} just published a new video: "${video.name}".`,
91 title: 'New content ',
99 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
102 addNewFollowNotification (to: string[], actorFollow: MActorFollowFull, followType: 'account' | 'channel') {
103 const followingName = (actorFollow.ActorFollowing.VideoChannel || actorFollow.ActorFollowing.Account).getDisplayName()
105 const emailPayload: EmailPayload = {
106 template: 'follower-on-channel',
108 subject: `New follower on your channel ${followingName}`,
110 followerName: actorFollow.ActorFollower.Account.getDisplayName(),
111 followerUrl: actorFollow.ActorFollower.url,
113 followingUrl: actorFollow.ActorFollowing.url,
118 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
121 addNewInstanceFollowerNotification (to: string[], actorFollow: MActorFollowActors) {
122 const awaitingApproval = actorFollow.state === 'pending' ? ' awaiting manual approval.' : ''
124 const emailPayload: EmailPayload = {
126 subject: 'New instance follower',
127 text: `Your instance has a new follower: ${actorFollow.ActorFollower.url}${awaitingApproval}.`,
129 title: 'New instance follower',
131 text: 'Review followers',
132 url: WEBSERVER.URL + '/admin/follows/followers-list'
137 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
140 addAutoInstanceFollowingNotification (to: string[], actorFollow: MActorFollowActors) {
141 const instanceUrl = actorFollow.ActorFollowing.url
142 const emailPayload: EmailPayload = {
144 subject: 'Auto instance following',
145 text: `Your instance automatically followed a new instance: <a href="${instanceUrl}">${instanceUrl}</a>.`
148 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
151 myVideoPublishedNotification (to: string[], video: MVideo) {
152 const videoUrl = WEBSERVER.URL + video.getWatchStaticPath()
154 const emailPayload: EmailPayload = {
156 subject: `Your video ${video.name} has been published`,
157 text: `Your video "${video.name}" has been published.`,
159 title: 'You video is live',
167 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
170 myVideoImportSuccessNotification (to: string[], videoImport: MVideoImportVideo) {
171 const videoUrl = WEBSERVER.URL + videoImport.Video.getWatchStaticPath()
173 const emailPayload: EmailPayload = {
175 subject: `Your video import ${videoImport.getTargetIdentifier()} is complete`,
176 text: `Your video "${videoImport.getTargetIdentifier()}" just finished importing.`,
178 title: 'Import complete',
186 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
189 myVideoImportErrorNotification (to: string[], videoImport: MVideoImport) {
190 const importUrl = WEBSERVER.URL + '/my-library/video-imports'
193 `Your video import "${videoImport.getTargetIdentifier()}" encountered an error.` +
195 `See your videos import dashboard for more information: <a href="${importUrl}">${importUrl}</a>.`
197 const emailPayload: EmailPayload = {
199 subject: `Your video import "${videoImport.getTargetIdentifier()}" encountered an error`,
202 title: 'Import failed',
204 text: 'Review imports',
210 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
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)
219 const emailPayload: EmailPayload = {
220 template: 'video-comment-new',
222 subject: 'New comment on your video ' + video.name,
224 accountName: comment.Account.getDisplayName(),
225 accountUrl: comment.Account.Actor.url,
231 text: 'View comment',
237 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
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)
247 const emailPayload: EmailPayload = {
248 template: 'video-comment-mention',
250 subject: 'Mention on video ' + video.name,
258 text: 'View comment',
264 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
267 addAbuseModeratorsNotification (to: string[], parameters: {
269 abuseInstance: MAbuseFull
272 const { abuse, abuseInstance, reporter } = parameters
275 text: 'View report #' + abuse.id,
276 url: WEBSERVER.URL + '/admin/moderation/abuses/list?search=%23' + abuse.id
279 let emailPayload: EmailPayload
281 if (abuseInstance.VideoAbuse) {
282 const video = abuseInstance.VideoAbuse.Video
283 const videoUrl = WEBSERVER.URL + video.getWatchStaticPath()
286 template: 'video-abuse-new',
288 subject: `New video abuse report from ${reporter}`,
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,
301 } else if (abuseInstance.VideoCommentAbuse) {
302 const comment = abuseInstance.VideoCommentAbuse.VideoComment
303 const commentUrl = WEBSERVER.URL + comment.Video.getWatchStaticPath() + ';threadId=' + comment.getThreadId()
306 template: 'video-comment-abuse-new',
308 subject: `New comment abuse report from ${reporter}`,
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(),
321 const account = abuseInstance.FlaggedAccount
322 const accountUrl = account.getClientUrl()
325 template: 'account-abuse-new',
327 subject: `New account abuse report from ${reporter}`,
330 accountDisplayName: account.getDisplayName(),
331 isLocal: account.isOwned(),
332 reason: abuse.reason,
339 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
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'
347 const abuseUrl = WEBSERVER.URL + '/my-account/abuses?search=%23' + abuse.id
354 const emailPayload: EmailPayload = {
355 template: 'abuse-state-change',
362 isAccepted: abuse.state === AbuseState.ACCEPTED
366 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
369 addAbuseNewMessageNotification (
372 target: 'moderator' | 'reporter'
374 message: MAbuseMessage
375 accountMessage: MAccountDefault
377 const { abuse, target, message, accountMessage } = options
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
389 const emailPayload: EmailPayload = {
390 template: 'abuse-new-message',
395 abuseUrl: action.url,
396 messageAccountName: accountMessage.getDisplayName(),
397 messageText: message.message,
402 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
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()
410 const emailPayload: EmailPayload = {
411 template: 'video-auto-blacklist-new',
413 subject: 'A new video is pending moderation',
417 videoName: videoBlacklist.Video.name,
419 text: 'Review autoblacklist',
420 url: VIDEO_AUTO_BLACKLIST_URL
425 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
428 addNewUserRegistrationNotification (to: string[], user: MUser) {
429 const emailPayload: EmailPayload = {
430 template: 'user-registered',
432 subject: `a new user registered on ${CONFIG.INSTANCE.NAME}: ${user.username}`,
438 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
441 addVideoBlacklistNotification (to: string[], videoBlacklist: MVideoBlacklistVideo) {
442 const videoName = videoBlacklist.Video.name
443 const videoUrl = WEBSERVER.URL + videoBlacklist.Video.getWatchStaticPath()
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}.`
448 const emailPayload: EmailPayload = {
450 subject: `Video ${videoName} blacklisted`,
453 title: 'Your video was blacklisted'
457 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
460 addVideoUnblacklistNotification (to: string[], video: MVideo) {
461 const videoUrl = WEBSERVER.URL + video.getWatchStaticPath()
463 const emailPayload: EmailPayload = {
465 subject: `Video ${video.name} unblacklisted`,
466 text: `Your video "${video.name}" (${videoUrl}) on ${CONFIG.INSTANCE.NAME} has been unblacklisted.`,
468 title: 'Your video was unblacklisted'
472 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
475 addPasswordResetEmailJob (username: string, to: string, resetPasswordUrl: string) {
476 const emailPayload: EmailPayload = {
477 template: 'password-reset',
479 subject: 'Reset your account password',
486 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
489 addPasswordCreateEmailJob (username: string, to: string, createPasswordUrl: string) {
490 const emailPayload: EmailPayload = {
491 template: 'password-create',
493 subject: 'Create your account password',
500 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
503 addVerifyEmailJob (username: string, to: string, verifyEmailUrl: string) {
504 const emailPayload: EmailPayload = {
505 template: 'verify-email',
507 subject: `Verify your email on ${CONFIG.INSTANCE.NAME}`,
514 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
517 addUserBlockJob (user: MUser, blocked: boolean, reason?: string) {
518 const reasonString = reason ? ` for the following reason: ${reason}` : ''
519 const blockedWord = blocked ? 'blocked' : 'unblocked'
521 const to = user.email
522 const emailPayload: EmailPayload = {
524 subject: 'Account ' + blockedWord,
525 text: `Your account ${user.username} on ${CONFIG.INSTANCE.NAME} has been ${blockedWord}${reasonString}.`
528 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
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}`,
542 // There are not notification preferences for the contact form
543 hideNotificationPreferences: true
547 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
550 async sendMail (options: EmailPayload) {
551 if (!isEmailEnabled()) {
552 throw new Error('Cannot send mail because SMTP is not configured.')
555 const fromDisplayName = options.from
557 : CONFIG.INSTANCE.NAME
559 const email = new Email({
562 from: `"${fromDisplayName}" <${CONFIG.SMTP.FROM_ADDRESS}>`
564 transport: this.transporter,
566 root: join(root(), 'dist', 'server', 'lib', 'emails')
568 subjectPrefix: CONFIG.EMAIL.SUBJECT.PREFIX
571 for (const to of options.to) {
579 subject: options.subject,
580 replyTo: options.replyTo
582 locals: { // default variables available in all templates
585 instanceName: CONFIG.INSTANCE.NAME,
587 subject: options.subject
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 }))
597 private warnOnConnectionFailure (err?: Error) {
598 logger.error('Failed to connect to SMTP %s:%d.', CONFIG.SMTP.HOSTNAME, CONFIG.SMTP.PORT, { err })
601 private initSMTPTransport () {
602 logger.info('Using %s:%s as SMTP server.', CONFIG.SMTP.HOSTNAME, CONFIG.SMTP.PORT)
605 if (CONFIG.SMTP.CA_FILE) {
607 ca: [ readFileSync(CONFIG.SMTP.CA_FILE) ]
612 if (CONFIG.SMTP.USERNAME && CONFIG.SMTP.PASSWORD) {
614 user: CONFIG.SMTP.USERNAME,
615 pass: CONFIG.SMTP.PASSWORD
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,
631 private initSendmailTransport () {
632 logger.info('Using sendmail to send emails')
634 this.transporter = createTransport({
637 path: CONFIG.SMTP.SENDMAIL
641 static get Instance () {
642 return this.instance || (this.instance = new this())
646 // ---------------------------------------------------------------------------