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 (CONFIG.SMTP.TRANSPORT === 'smtp') {
57 logger.info('Using %s:%s as SMTP server.', CONFIG.SMTP.HOSTNAME, CONFIG.SMTP.PORT)
60 if (CONFIG.SMTP.CA_FILE) {
62 ca: [ readFileSync(CONFIG.SMTP.CA_FILE) ]
67 if (CONFIG.SMTP.USERNAME && CONFIG.SMTP.PASSWORD) {
69 user: CONFIG.SMTP.USERNAME,
70 pass: CONFIG.SMTP.PASSWORD
74 this.transporter = createTransport({
75 host: CONFIG.SMTP.HOSTNAME,
76 port: CONFIG.SMTP.PORT,
77 secure: CONFIG.SMTP.TLS,
78 debug: CONFIG.LOG.LEVEL === 'debug',
79 logger: bunyanLogger as any,
80 ignoreTLS: CONFIG.SMTP.DISABLE_STARTTLS,
85 logger.info('Using sendmail to send emails')
87 this.transporter = createTransport({
90 path: CONFIG.SMTP.SENDMAIL
94 if (!isTestInstance()) {
95 logger.error('Cannot use SMTP server because of lack of configuration. PeerTube will not be able to send mails!')
100 static isEnabled () {
101 if (CONFIG.SMTP.TRANSPORT === 'sendmail') {
102 return !!CONFIG.SMTP.SENDMAIL
103 } else if (CONFIG.SMTP.TRANSPORT === 'smtp') {
104 return !!CONFIG.SMTP.HOSTNAME && !!CONFIG.SMTP.PORT
110 async checkConnection () {
111 if (!this.transporter || CONFIG.SMTP.TRANSPORT !== 'smtp') return
113 logger.info('Testing SMTP server...')
116 const success = await this.transporter.verify()
117 if (success !== true) this.warnOnConnectionFailure()
119 logger.info('Successfully connected to SMTP server.')
121 this.warnOnConnectionFailure(err)
125 addNewVideoFromSubscriberNotification (to: string[], video: MVideoAccountLight) {
126 const channelName = video.VideoChannel.getDisplayName()
127 const videoUrl = WEBSERVER.URL + video.getWatchStaticPath()
129 const emailPayload: EmailPayload = {
131 subject: channelName + ' just published a new video',
132 text: `Your subscription ${channelName} just published a new video: "${video.name}".`,
134 title: 'New content ',
142 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
145 addNewFollowNotification (to: string[], actorFollow: MActorFollowFull, followType: 'account' | 'channel') {
146 const followingName = (actorFollow.ActorFollowing.VideoChannel || actorFollow.ActorFollowing.Account).getDisplayName()
148 const emailPayload: EmailPayload = {
149 template: 'follower-on-channel',
151 subject: `New follower on your channel ${followingName}`,
153 followerName: actorFollow.ActorFollower.Account.getDisplayName(),
154 followerUrl: actorFollow.ActorFollower.url,
156 followingUrl: actorFollow.ActorFollowing.url,
161 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
164 addNewInstanceFollowerNotification (to: string[], actorFollow: MActorFollowActors) {
165 const awaitingApproval = actorFollow.state === 'pending' ? ' awaiting manual approval.' : ''
167 const emailPayload: EmailPayload = {
169 subject: 'New instance follower',
170 text: `Your instance has a new follower: ${actorFollow.ActorFollower.url}${awaitingApproval}.`,
172 title: 'New instance follower',
174 text: 'Review followers',
175 url: WEBSERVER.URL + '/admin/follows/followers-list'
180 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
183 addAutoInstanceFollowingNotification (to: string[], actorFollow: MActorFollowActors) {
184 const instanceUrl = actorFollow.ActorFollowing.url
185 const emailPayload: EmailPayload = {
187 subject: 'Auto instance following',
188 text: `Your instance automatically followed a new instance: <a href="${instanceUrl}">${instanceUrl}</a>.`
191 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
194 myVideoPublishedNotification (to: string[], video: MVideo) {
195 const videoUrl = WEBSERVER.URL + video.getWatchStaticPath()
197 const emailPayload: EmailPayload = {
199 subject: `Your video ${video.name} has been published`,
200 text: `Your video "${video.name}" has been published.`,
202 title: 'You video is live',
210 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
213 myVideoImportSuccessNotification (to: string[], videoImport: MVideoImportVideo) {
214 const videoUrl = WEBSERVER.URL + videoImport.Video.getWatchStaticPath()
216 const emailPayload: EmailPayload = {
218 subject: `Your video import ${videoImport.getTargetIdentifier()} is complete`,
219 text: `Your video "${videoImport.getTargetIdentifier()}" just finished importing.`,
221 title: 'Import complete',
229 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
232 myVideoImportErrorNotification (to: string[], videoImport: MVideoImport) {
233 const importUrl = WEBSERVER.URL + '/my-library/video-imports'
236 `Your video import "${videoImport.getTargetIdentifier()}" encountered an error.` +
238 `See your videos import dashboard for more information: <a href="${importUrl}">${importUrl}</a>.`
240 const emailPayload: EmailPayload = {
242 subject: `Your video import "${videoImport.getTargetIdentifier()}" encountered an error`,
245 title: 'Import failed',
247 text: 'Review imports',
253 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
256 addNewCommentOnMyVideoNotification (to: string[], comment: MCommentOwnerVideo) {
257 const video = comment.Video
258 const videoUrl = WEBSERVER.URL + comment.Video.getWatchStaticPath()
259 const commentUrl = WEBSERVER.URL + comment.getCommentStaticPath()
260 const commentHtml = toSafeHtml(comment.text)
262 const emailPayload: EmailPayload = {
263 template: 'video-comment-new',
265 subject: 'New comment on your video ' + video.name,
267 accountName: comment.Account.getDisplayName(),
268 accountUrl: comment.Account.Actor.url,
274 text: 'View comment',
280 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
283 addNewCommentMentionNotification (to: string[], comment: MCommentOwnerVideo) {
284 const accountName = comment.Account.getDisplayName()
285 const video = comment.Video
286 const videoUrl = WEBSERVER.URL + comment.Video.getWatchStaticPath()
287 const commentUrl = WEBSERVER.URL + comment.getCommentStaticPath()
288 const commentHtml = toSafeHtml(comment.text)
290 const emailPayload: EmailPayload = {
291 template: 'video-comment-mention',
293 subject: 'Mention on video ' + video.name,
301 text: 'View comment',
307 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
310 addAbuseModeratorsNotification (to: string[], parameters: {
312 abuseInstance: MAbuseFull
315 const { abuse, abuseInstance, reporter } = parameters
318 text: 'View report #' + abuse.id,
319 url: WEBSERVER.URL + '/admin/moderation/abuses/list?search=%23' + abuse.id
322 let emailPayload: EmailPayload
324 if (abuseInstance.VideoAbuse) {
325 const video = abuseInstance.VideoAbuse.Video
326 const videoUrl = WEBSERVER.URL + video.getWatchStaticPath()
329 template: 'video-abuse-new',
331 subject: `New video abuse report from ${reporter}`,
334 isLocal: video.remote === false,
335 videoCreatedAt: new Date(video.createdAt).toLocaleString(),
336 videoPublishedAt: new Date(video.publishedAt).toLocaleString(),
337 videoName: video.name,
338 reason: abuse.reason,
339 videoChannel: abuse.video.channel,
344 } else if (abuseInstance.VideoCommentAbuse) {
345 const comment = abuseInstance.VideoCommentAbuse.VideoComment
346 const commentUrl = WEBSERVER.URL + comment.Video.getWatchStaticPath() + ';threadId=' + comment.getThreadId()
349 template: 'video-comment-abuse-new',
351 subject: `New comment abuse report from ${reporter}`,
354 videoName: comment.Video.name,
355 isLocal: comment.isOwned(),
356 commentCreatedAt: new Date(comment.createdAt).toLocaleString(),
357 reason: abuse.reason,
358 flaggedAccount: abuseInstance.FlaggedAccount.getDisplayName(),
364 const account = abuseInstance.FlaggedAccount
365 const accountUrl = account.getClientUrl()
368 template: 'account-abuse-new',
370 subject: `New account abuse report from ${reporter}`,
373 accountDisplayName: account.getDisplayName(),
374 isLocal: account.isOwned(),
375 reason: abuse.reason,
382 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
385 addAbuseStateChangeNotification (to: string[], abuse: MAbuseFull) {
386 const text = abuse.state === AbuseState.ACCEPTED
387 ? 'Report #' + abuse.id + ' has been accepted'
388 : 'Report #' + abuse.id + ' has been rejected'
390 const abuseUrl = WEBSERVER.URL + '/my-account/abuses?search=%23' + abuse.id
397 const emailPayload: EmailPayload = {
398 template: 'abuse-state-change',
405 isAccepted: abuse.state === AbuseState.ACCEPTED
409 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
412 addAbuseNewMessageNotification (
415 target: 'moderator' | 'reporter'
417 message: MAbuseMessage
418 accountMessage: MAccountDefault
420 const { abuse, target, message, accountMessage } = options
422 const text = 'New message on report #' + abuse.id
423 const abuseUrl = target === 'moderator'
424 ? WEBSERVER.URL + '/admin/moderation/abuses/list?search=%23' + abuse.id
425 : WEBSERVER.URL + '/my-account/abuses?search=%23' + abuse.id
432 const emailPayload: EmailPayload = {
433 template: 'abuse-new-message',
438 abuseUrl: action.url,
439 messageAccountName: accountMessage.getDisplayName(),
440 messageText: message.message,
445 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
448 async addVideoAutoBlacklistModeratorsNotification (to: string[], videoBlacklist: MVideoBlacklistLightVideo) {
449 const VIDEO_AUTO_BLACKLIST_URL = WEBSERVER.URL + '/admin/moderation/video-auto-blacklist/list'
450 const videoUrl = WEBSERVER.URL + videoBlacklist.Video.getWatchStaticPath()
451 const channel = (await VideoChannelModel.loadByIdAndPopulateAccount(videoBlacklist.Video.channelId)).toFormattedSummaryJSON()
453 const emailPayload: EmailPayload = {
454 template: 'video-auto-blacklist-new',
456 subject: 'A new video is pending moderation',
460 videoName: videoBlacklist.Video.name,
462 text: 'Review autoblacklist',
463 url: VIDEO_AUTO_BLACKLIST_URL
468 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
471 addNewUserRegistrationNotification (to: string[], user: MUser) {
472 const emailPayload: EmailPayload = {
473 template: 'user-registered',
475 subject: `a new user registered on ${CONFIG.INSTANCE.NAME}: ${user.username}`,
481 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
484 addVideoBlacklistNotification (to: string[], videoBlacklist: MVideoBlacklistVideo) {
485 const videoName = videoBlacklist.Video.name
486 const videoUrl = WEBSERVER.URL + videoBlacklist.Video.getWatchStaticPath()
488 const reasonString = videoBlacklist.reason ? ` for the following reason: ${videoBlacklist.reason}` : ''
489 const blockedString = `Your video ${videoName} (${videoUrl} on ${CONFIG.INSTANCE.NAME} has been blacklisted${reasonString}.`
491 const emailPayload: EmailPayload = {
493 subject: `Video ${videoName} blacklisted`,
496 title: 'Your video was blacklisted'
500 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
503 addVideoUnblacklistNotification (to: string[], video: MVideo) {
504 const videoUrl = WEBSERVER.URL + video.getWatchStaticPath()
506 const emailPayload: EmailPayload = {
508 subject: `Video ${video.name} unblacklisted`,
509 text: `Your video "${video.name}" (${videoUrl}) on ${CONFIG.INSTANCE.NAME} has been unblacklisted.`,
511 title: 'Your video was unblacklisted'
515 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
518 addPasswordResetEmailJob (username: string, to: string, resetPasswordUrl: string) {
519 const emailPayload: EmailPayload = {
520 template: 'password-reset',
522 subject: 'Reset your account password',
529 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
532 addPasswordCreateEmailJob (username: string, to: string, createPasswordUrl: string) {
533 const emailPayload: EmailPayload = {
534 template: 'password-create',
536 subject: 'Create your account password',
543 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
546 addVerifyEmailJob (username: string, to: string, verifyEmailUrl: string) {
547 const emailPayload: EmailPayload = {
548 template: 'verify-email',
550 subject: `Verify your email on ${CONFIG.INSTANCE.NAME}`,
557 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
560 addUserBlockJob (user: MUser, blocked: boolean, reason?: string) {
561 const reasonString = reason ? ` for the following reason: ${reason}` : ''
562 const blockedWord = blocked ? 'blocked' : 'unblocked'
564 const to = user.email
565 const emailPayload: EmailPayload = {
567 subject: 'Account ' + blockedWord,
568 text: `Your account ${user.username} on ${CONFIG.INSTANCE.NAME} has been ${blockedWord}${reasonString}.`
571 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
574 addContactFormJob (fromEmail: string, fromName: string, subject: string, body: string) {
575 const emailPayload: EmailPayload = {
576 template: 'contact-form',
577 to: [ CONFIG.ADMIN.EMAIL ],
578 replyTo: `"${fromName}" <${fromEmail}>`,
579 subject: `(contact form) ${subject}`,
585 // There are not notification preferences for the contact form
586 hideNotificationPreferences: true
590 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
593 async sendMail (options: EmailPayload) {
594 if (!isEmailEnabled()) {
595 throw new Error('Cannot send mail because SMTP is not configured.')
598 const fromDisplayName = options.from
600 : CONFIG.INSTANCE.NAME
602 const email = new Email({
605 from: `"${fromDisplayName}" <${CONFIG.SMTP.FROM_ADDRESS}>`
607 transport: this.transporter,
609 root: join(root(), 'dist', 'server', 'lib', 'emails')
611 subjectPrefix: CONFIG.EMAIL.SUBJECT.PREFIX
614 for (const to of options.to) {
622 subject: options.subject,
623 replyTo: options.replyTo
625 locals: { // default variables available in all templates
628 instanceName: CONFIG.INSTANCE.NAME,
630 subject: options.subject
633 options // overriden/new variables given for a specific template in the payload
634 ) as SendEmailOptions)
635 .then(res => logger.debug('Sent email.', { res }))
636 .catch(err => logger.error('Error in email sender.', { err }))
640 private warnOnConnectionFailure (err?: Error) {
641 logger.error('Failed to connect to SMTP %s:%d.', CONFIG.SMTP.HOSTNAME, CONFIG.SMTP.PORT, { err })
644 static get Instance () {
645 return this.instance || (this.instance = new this())
649 // ---------------------------------------------------------------------------