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'
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 })
32 markdownIt.use(markdownItEmoji)
34 const toSafeHtml = text => {
36 const textWithLineFeed = text.replace(/<br.?\/?>/g, '\r\n')
38 // Convert possible markdown (emojis, emphasis and lists) to html
39 const html = markdownIt.render(textWithLineFeed)
41 // Convert to safe Html
42 return sanitizeHtml(html, {
43 allowedTags: [ 'a', 'p', 'span', 'br', 'strong', 'em', 'ul', 'ol', 'li' ],
44 allowedSchemes: [ 'http', 'https' ],
46 a: [ 'href', 'class', 'target', 'rel' ]
49 a: (tagName, attribs) => {
50 let rel = 'noopener noreferrer'
51 if (attribs.rel === 'me') rel += ' me'
55 attribs: Object.assign(attribs, {
65 const Email = require('email-templates')
69 private static instance: Emailer
70 private initialized = false
71 private transporter: Transporter
73 private constructor () {
77 // Already initialized
78 if (this.initialized === true) return
79 this.initialized = true
81 if (isEmailEnabled()) {
82 if (CONFIG.SMTP.TRANSPORT === 'smtp') {
83 logger.info('Using %s:%s as SMTP server.', CONFIG.SMTP.HOSTNAME, CONFIG.SMTP.PORT)
86 if (CONFIG.SMTP.CA_FILE) {
88 ca: [ readFileSync(CONFIG.SMTP.CA_FILE) ]
93 if (CONFIG.SMTP.USERNAME && CONFIG.SMTP.PASSWORD) {
95 user: CONFIG.SMTP.USERNAME,
96 pass: CONFIG.SMTP.PASSWORD
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,
111 logger.info('Using sendmail to send emails')
113 this.transporter = createTransport({
116 path: CONFIG.SMTP.SENDMAIL
120 if (!isTestInstance()) {
121 logger.error('Cannot use SMTP server because of lack of configuration. PeerTube will not be able to send mails!')
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
136 async checkConnectionOrDie () {
137 if (!this.transporter || CONFIG.SMTP.TRANSPORT !== 'smtp') return
139 logger.info('Testing SMTP server...')
142 const success = await this.transporter.verify()
143 if (success !== true) this.dieOnConnectionFailure()
145 logger.info('Successfully connected to SMTP server.')
147 this.dieOnConnectionFailure(err)
151 addNewVideoFromSubscriberNotification (to: string[], video: MVideoAccountLight) {
152 const channelName = video.VideoChannel.getDisplayName()
153 const videoUrl = WEBSERVER.URL + video.getWatchStaticPath()
155 const emailPayload: EmailPayload = {
157 subject: channelName + ' just published a new video',
158 text: `Your subscription ${channelName} just published a new video: "${video.name}".`,
160 title: 'New content ',
168 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
171 addNewFollowNotification (to: string[], actorFollow: MActorFollowFull, followType: 'account' | 'channel') {
172 const followingName = (actorFollow.ActorFollowing.VideoChannel || actorFollow.ActorFollowing.Account).getDisplayName()
174 const emailPayload: EmailPayload = {
175 template: 'follower-on-channel',
177 subject: `New follower on your channel ${followingName}`,
179 followerName: actorFollow.ActorFollower.Account.getDisplayName(),
180 followerUrl: actorFollow.ActorFollower.url,
182 followingUrl: actorFollow.ActorFollowing.url,
187 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
190 addNewInstanceFollowerNotification (to: string[], actorFollow: MActorFollowActors) {
191 const awaitingApproval = actorFollow.state === 'pending' ? ' awaiting manual approval.' : ''
193 const emailPayload: EmailPayload = {
195 subject: 'New instance follower',
196 text: `Your instance has a new follower: ${actorFollow.ActorFollower.url}${awaitingApproval}.`,
198 title: 'New instance follower',
200 text: 'Review followers',
201 url: WEBSERVER.URL + '/admin/follows/followers-list'
206 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
209 addAutoInstanceFollowingNotification (to: string[], actorFollow: MActorFollowActors) {
210 const instanceUrl = actorFollow.ActorFollowing.url
211 const emailPayload: EmailPayload = {
213 subject: 'Auto instance following',
214 text: `Your instance automatically followed a new instance: <a href="${instanceUrl}">${instanceUrl}</a>.`
217 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
220 myVideoPublishedNotification (to: string[], video: MVideo) {
221 const videoUrl = WEBSERVER.URL + video.getWatchStaticPath()
223 const emailPayload: EmailPayload = {
225 subject: `Your video ${video.name} has been published`,
226 text: `Your video "${video.name}" has been published.`,
228 title: 'You video is live',
236 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
239 myVideoImportSuccessNotification (to: string[], videoImport: MVideoImportVideo) {
240 const videoUrl = WEBSERVER.URL + videoImport.Video.getWatchStaticPath()
242 const emailPayload: EmailPayload = {
244 subject: `Your video import ${videoImport.getTargetIdentifier()} is complete`,
245 text: `Your video "${videoImport.getTargetIdentifier()}" just finished importing.`,
247 title: 'Import complete',
255 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
258 myVideoImportErrorNotification (to: string[], videoImport: MVideoImport) {
259 const importUrl = WEBSERVER.URL + '/my-account/video-imports'
262 `Your video import "${videoImport.getTargetIdentifier()}" encountered an error.` +
264 `See your videos import dashboard for more information: <a href="${importUrl}">${importUrl}</a>.`
266 const emailPayload: EmailPayload = {
268 subject: `Your video import "${videoImport.getTargetIdentifier()}" encountered an error`,
271 title: 'Import failed',
273 text: 'Review imports',
279 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
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)
288 const emailPayload: EmailPayload = {
289 template: 'video-comment-new',
291 subject: 'New comment on your video ' + video.name,
293 accountName: comment.Account.getDisplayName(),
294 accountUrl: comment.Account.Actor.url,
300 text: 'View comment',
306 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
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)
316 const emailPayload: EmailPayload = {
317 template: 'video-comment-mention',
319 subject: 'Mention on video ' + video.name,
327 text: 'View comment',
333 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
336 addAbuseModeratorsNotification (to: string[], parameters: {
338 abuseInstance: MAbuseFull
341 const { abuse, abuseInstance, reporter } = parameters
344 text: 'View report #' + abuse.id,
345 url: WEBSERVER.URL + '/admin/moderation/abuses/list?search=%23' + abuse.id
348 let emailPayload: EmailPayload
350 if (abuseInstance.VideoAbuse) {
351 const video = abuseInstance.VideoAbuse.Video
352 const videoUrl = WEBSERVER.URL + video.getWatchStaticPath()
355 template: 'video-abuse-new',
357 subject: `New video abuse report from ${reporter}`,
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,
370 } else if (abuseInstance.VideoCommentAbuse) {
371 const comment = abuseInstance.VideoCommentAbuse.VideoComment
372 const commentUrl = WEBSERVER.URL + comment.Video.getWatchStaticPath() + ';threadId=' + comment.getThreadId()
375 template: 'video-comment-abuse-new',
377 subject: `New comment abuse report from ${reporter}`,
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(),
390 const account = abuseInstance.FlaggedAccount
391 const accountUrl = account.getClientUrl()
394 template: 'account-abuse-new',
396 subject: `New account abuse report from ${reporter}`,
399 accountDisplayName: account.getDisplayName(),
400 isLocal: account.isOwned(),
401 reason: abuse.reason,
408 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
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'
416 const abuseUrl = WEBSERVER.URL + '/my-account/abuses?search=%23' + abuse.id
423 const emailPayload: EmailPayload = {
424 template: 'abuse-state-change',
431 isAccepted: abuse.state === AbuseState.ACCEPTED
435 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
438 addAbuseNewMessageNotification (
441 target: 'moderator' | 'reporter'
443 message: MAbuseMessage
444 accountMessage: MAccountDefault
446 const { abuse, target, message, accountMessage } = options
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
458 const emailPayload: EmailPayload = {
459 template: 'abuse-new-message',
464 abuseUrl: action.url,
465 messageAccountName: accountMessage.getDisplayName(),
466 messageText: message.message,
471 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
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()
479 const emailPayload: EmailPayload = {
480 template: 'video-auto-blacklist-new',
482 subject: 'A new video is pending moderation',
486 videoName: videoBlacklist.Video.name,
488 text: 'Review autoblacklist',
489 url: VIDEO_AUTO_BLACKLIST_URL
494 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
497 addNewUserRegistrationNotification (to: string[], user: MUser) {
498 const emailPayload: EmailPayload = {
499 template: 'user-registered',
501 subject: `a new user registered on ${WEBSERVER.HOST}: ${user.username}`,
507 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
510 addVideoBlacklistNotification (to: string[], videoBlacklist: MVideoBlacklistVideo) {
511 const videoName = videoBlacklist.Video.name
512 const videoUrl = WEBSERVER.URL + videoBlacklist.Video.getWatchStaticPath()
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}.`
517 const emailPayload: EmailPayload = {
519 subject: `Video ${videoName} blacklisted`,
522 title: 'Your video was blacklisted'
526 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
529 addVideoUnblacklistNotification (to: string[], video: MVideo) {
530 const videoUrl = WEBSERVER.URL + video.getWatchStaticPath()
532 const emailPayload: EmailPayload = {
534 subject: `Video ${video.name} unblacklisted`,
535 text: `Your video "${video.name}" (${videoUrl}) on ${WEBSERVER.HOST} has been unblacklisted.`,
537 title: 'Your video was unblacklisted'
541 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
544 addPasswordResetEmailJob (username: string, to: string, resetPasswordUrl: string) {
545 const emailPayload: EmailPayload = {
546 template: 'password-reset',
548 subject: 'Reset your account password',
555 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
558 addPasswordCreateEmailJob (username: string, to: string, createPasswordUrl: string) {
559 const emailPayload: EmailPayload = {
560 template: 'password-create',
562 subject: 'Create your account password',
569 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
572 addVerifyEmailJob (username: string, to: string, verifyEmailUrl: string) {
573 const emailPayload: EmailPayload = {
574 template: 'verify-email',
576 subject: `Verify your email on ${WEBSERVER.HOST}`,
583 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
586 addUserBlockJob (user: MUser, blocked: boolean, reason?: string) {
587 const reasonString = reason ? ` for the following reason: ${reason}` : ''
588 const blockedWord = blocked ? 'blocked' : 'unblocked'
590 const to = user.email
591 const emailPayload: EmailPayload = {
593 subject: 'Account ' + blockedWord,
594 text: `Your account ${user.username} on ${WEBSERVER.HOST} has been ${blockedWord}${reasonString}.`
597 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
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}`,
611 // There are not notification preferences for the contact form
612 hideNotificationPreferences: true
616 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
619 async sendMail (options: EmailPayload) {
620 if (!isEmailEnabled()) {
621 throw new Error('Cannot send mail because SMTP is not configured.')
624 const fromDisplayName = options.from
628 const email = new Email({
631 from: `"${fromDisplayName}" <${CONFIG.SMTP.FROM_ADDRESS}>`
633 transport: this.transporter,
635 root: join(root(), 'dist', 'server', 'lib', 'emails')
637 subjectPrefix: CONFIG.EMAIL.SUBJECT.PREFIX
640 for (const to of options.to) {
648 subject: options.subject,
649 replyTo: options.replyTo
651 locals: { // default variables available in all templates
655 subject: options.subject
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 }))
665 private dieOnConnectionFailure (err?: Error) {
666 logger.error('Failed to connect to SMTP %s:%d.', CONFIG.SMTP.HOSTNAME, CONFIG.SMTP.PORT, { err })
670 static get Instance () {
671 return this.instance || (this.instance = new this())
675 // ---------------------------------------------------------------------------