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 { Abuse, EmailPayload } 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, MActorFollowActors, MActorFollowFull, MUser } from '../types/models'
15 import { MCommentOwnerVideo, MVideo, MVideoAccountLight } from '../types/models/video'
16 import { JobQueue } from './job-queue'
18 const Email = require('email-templates')
22 private static instance: Emailer
23 private initialized = false
24 private transporter: Transporter
26 private constructor () {
30 // Already initialized
31 if (this.initialized === true) return
32 this.initialized = true
34 if (isEmailEnabled()) {
35 if (CONFIG.SMTP.TRANSPORT === 'smtp') {
36 logger.info('Using %s:%s as SMTP server.', CONFIG.SMTP.HOSTNAME, CONFIG.SMTP.PORT)
39 if (CONFIG.SMTP.CA_FILE) {
41 ca: [ readFileSync(CONFIG.SMTP.CA_FILE) ]
46 if (CONFIG.SMTP.USERNAME && CONFIG.SMTP.PASSWORD) {
48 user: CONFIG.SMTP.USERNAME,
49 pass: CONFIG.SMTP.PASSWORD
53 this.transporter = createTransport({
54 host: CONFIG.SMTP.HOSTNAME,
55 port: CONFIG.SMTP.PORT,
56 secure: CONFIG.SMTP.TLS,
57 debug: CONFIG.LOG.LEVEL === 'debug',
58 logger: bunyanLogger as any,
59 ignoreTLS: CONFIG.SMTP.DISABLE_STARTTLS,
64 logger.info('Using sendmail to send emails')
66 this.transporter = createTransport({
69 path: CONFIG.SMTP.SENDMAIL
73 if (!isTestInstance()) {
74 logger.error('Cannot use SMTP server because of lack of configuration. PeerTube will not be able to send mails!')
80 if (CONFIG.SMTP.TRANSPORT === 'sendmail') {
81 return !!CONFIG.SMTP.SENDMAIL
82 } else if (CONFIG.SMTP.TRANSPORT === 'smtp') {
83 return !!CONFIG.SMTP.HOSTNAME && !!CONFIG.SMTP.PORT
89 async checkConnectionOrDie () {
90 if (!this.transporter || CONFIG.SMTP.TRANSPORT !== 'smtp') return
92 logger.info('Testing SMTP server...')
95 const success = await this.transporter.verify()
96 if (success !== true) this.dieOnConnectionFailure()
98 logger.info('Successfully connected to SMTP server.')
100 this.dieOnConnectionFailure(err)
104 addNewVideoFromSubscriberNotification (to: string[], video: MVideoAccountLight) {
105 const channelName = video.VideoChannel.getDisplayName()
106 const videoUrl = WEBSERVER.URL + video.getWatchStaticPath()
108 const emailPayload: EmailPayload = {
110 subject: channelName + ' just published a new video',
111 text: `Your subscription ${channelName} just published a new video: "${video.name}".`,
113 title: 'New content ',
121 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
124 addNewFollowNotification (to: string[], actorFollow: MActorFollowFull, followType: 'account' | 'channel') {
125 const followingName = (actorFollow.ActorFollowing.VideoChannel || actorFollow.ActorFollowing.Account).getDisplayName()
127 const emailPayload: EmailPayload = {
128 template: 'follower-on-channel',
130 subject: `New follower on your channel ${followingName}`,
132 followerName: actorFollow.ActorFollower.Account.getDisplayName(),
133 followerUrl: actorFollow.ActorFollower.url,
135 followingUrl: actorFollow.ActorFollowing.url,
140 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
143 addNewInstanceFollowerNotification (to: string[], actorFollow: MActorFollowActors) {
144 const awaitingApproval = actorFollow.state === 'pending' ? ' awaiting manual approval.' : ''
146 const emailPayload: EmailPayload = {
148 subject: 'New instance follower',
149 text: `Your instance has a new follower: ${actorFollow.ActorFollower.url}${awaitingApproval}.`,
151 title: 'New instance follower',
153 text: 'Review followers',
154 url: WEBSERVER.URL + '/admin/follows/followers-list'
159 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
162 addAutoInstanceFollowingNotification (to: string[], actorFollow: MActorFollowActors) {
163 const instanceUrl = actorFollow.ActorFollowing.url
164 const emailPayload: EmailPayload = {
166 subject: 'Auto instance following',
167 text: `Your instance automatically followed a new instance: <a href="${instanceUrl}">${instanceUrl}</a>.`
170 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
173 myVideoPublishedNotification (to: string[], video: MVideo) {
174 const videoUrl = WEBSERVER.URL + video.getWatchStaticPath()
176 const emailPayload: EmailPayload = {
178 subject: `Your video ${video.name} has been published`,
179 text: `Your video "${video.name}" has been published.`,
181 title: 'You video is live',
189 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
192 myVideoImportSuccessNotification (to: string[], videoImport: MVideoImportVideo) {
193 const videoUrl = WEBSERVER.URL + videoImport.Video.getWatchStaticPath()
195 const emailPayload: EmailPayload = {
197 subject: `Your video import ${videoImport.getTargetIdentifier()} is complete`,
198 text: `Your video "${videoImport.getTargetIdentifier()}" just finished importing.`,
200 title: 'Import complete',
208 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
211 myVideoImportErrorNotification (to: string[], videoImport: MVideoImport) {
212 const importUrl = WEBSERVER.URL + '/my-account/video-imports'
215 `Your video import "${videoImport.getTargetIdentifier()}" encountered an error.` +
217 `See your videos import dashboard for more information: <a href="${importUrl}">${importUrl}</a>.`
219 const emailPayload: EmailPayload = {
221 subject: `Your video import "${videoImport.getTargetIdentifier()}" encountered an error`,
224 title: 'Import failed',
226 text: 'Review imports',
232 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
235 addNewCommentOnMyVideoNotification (to: string[], comment: MCommentOwnerVideo) {
236 const video = comment.Video
237 const videoUrl = WEBSERVER.URL + comment.Video.getWatchStaticPath()
238 const commentUrl = WEBSERVER.URL + comment.getCommentStaticPath()
240 const emailPayload: EmailPayload = {
241 template: 'video-comment-new',
243 subject: 'New comment on your video ' + video.name,
245 accountName: comment.Account.getDisplayName(),
246 accountUrl: comment.Account.Actor.url,
251 text: 'View comment',
257 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
260 addNewCommentMentionNotification (to: string[], comment: MCommentOwnerVideo) {
261 const accountName = comment.Account.getDisplayName()
262 const video = comment.Video
263 const videoUrl = WEBSERVER.URL + comment.Video.getWatchStaticPath()
264 const commentUrl = WEBSERVER.URL + comment.getCommentStaticPath()
266 const emailPayload: EmailPayload = {
267 template: 'video-comment-mention',
269 subject: 'Mention on video ' + video.name,
276 text: 'View comment',
282 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
285 addAbuseModeratorsNotification (to: string[], parameters: {
287 abuseInstance: MAbuseFull
290 const { abuse, abuseInstance, reporter } = parameters
293 text: 'View report #' + abuse.id,
294 url: WEBSERVER.URL + '/admin/moderation/abuses/list?search=%23' + abuse.id
297 let emailPayload: EmailPayload
299 if (abuseInstance.VideoAbuse) {
300 const video = abuseInstance.VideoAbuse.Video
301 const videoUrl = WEBSERVER.URL + video.getWatchStaticPath()
304 template: 'video-abuse-new',
306 subject: `New video abuse report from ${reporter}`,
309 isLocal: video.remote === false,
310 videoCreatedAt: new Date(video.createdAt).toLocaleString(),
311 videoPublishedAt: new Date(video.publishedAt).toLocaleString(),
312 videoName: video.name,
313 reason: abuse.reason,
314 videoChannel: video.VideoChannel,
318 } else if (abuseInstance.VideoCommentAbuse) {
319 const comment = abuseInstance.VideoCommentAbuse.VideoComment
320 const commentUrl = WEBSERVER.URL + comment.Video.getWatchStaticPath() + ';threadId=' + comment.getThreadId()
323 template: 'video-comment-abuse-new',
325 subject: `New comment abuse report from ${reporter}`,
328 isLocal: comment.isOwned(),
329 commentCreatedAt: new Date(comment.createdAt).toLocaleString(),
330 reason: abuse.reason,
331 flaggedAccount: abuseInstance.FlaggedAccount.getDisplayName(),
336 const account = abuseInstance.FlaggedAccount
337 const accountUrl = account.getClientUrl()
340 template: 'account-abuse-new',
342 subject: `New account abuse report from ${reporter}`,
345 accountDisplayName: account.getDisplayName(),
346 isLocal: account.isOwned(),
347 reason: abuse.reason,
353 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
356 async addVideoAutoBlacklistModeratorsNotification (to: string[], videoBlacklist: MVideoBlacklistLightVideo) {
357 const VIDEO_AUTO_BLACKLIST_URL = WEBSERVER.URL + '/admin/moderation/video-auto-blacklist/list'
358 const videoUrl = WEBSERVER.URL + videoBlacklist.Video.getWatchStaticPath()
359 const channel = (await VideoChannelModel.loadByIdAndPopulateAccount(videoBlacklist.Video.channelId)).toFormattedSummaryJSON()
361 const emailPayload: EmailPayload = {
362 template: 'video-auto-blacklist-new',
364 subject: 'A new video is pending moderation',
368 videoName: videoBlacklist.Video.name,
370 text: 'Review autoblacklist',
371 url: VIDEO_AUTO_BLACKLIST_URL
376 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
379 addNewUserRegistrationNotification (to: string[], user: MUser) {
380 const emailPayload: EmailPayload = {
381 template: 'user-registered',
383 subject: `a new user registered on ${WEBSERVER.HOST}: ${user.username}`,
389 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
392 addVideoBlacklistNotification (to: string[], videoBlacklist: MVideoBlacklistVideo) {
393 const videoName = videoBlacklist.Video.name
394 const videoUrl = WEBSERVER.URL + videoBlacklist.Video.getWatchStaticPath()
396 const reasonString = videoBlacklist.reason ? ` for the following reason: ${videoBlacklist.reason}` : ''
397 const blockedString = `Your video ${videoName} (${videoUrl} on ${WEBSERVER.HOST} has been blacklisted${reasonString}.`
399 const emailPayload: EmailPayload = {
401 subject: `Video ${videoName} blacklisted`,
404 title: 'Your video was blacklisted'
408 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
411 addVideoUnblacklistNotification (to: string[], video: MVideo) {
412 const videoUrl = WEBSERVER.URL + video.getWatchStaticPath()
414 const emailPayload: EmailPayload = {
416 subject: `Video ${video.name} unblacklisted`,
417 text: `Your video "${video.name}" (${videoUrl}) on ${WEBSERVER.HOST} has been unblacklisted.`,
419 title: 'Your video was unblacklisted'
423 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
426 addPasswordResetEmailJob (to: string, resetPasswordUrl: string) {
427 const emailPayload: EmailPayload = {
428 template: 'password-reset',
430 subject: 'Reset your account password',
436 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
439 addPasswordCreateEmailJob (username: string, to: string, createPasswordUrl: string) {
440 const emailPayload: EmailPayload = {
441 template: 'password-create',
443 subject: 'Create your account password',
450 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
453 addVerifyEmailJob (to: string, verifyEmailUrl: string) {
454 const emailPayload: EmailPayload = {
455 template: 'verify-email',
457 subject: `Verify your email on ${WEBSERVER.HOST}`,
463 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
466 addUserBlockJob (user: MUser, blocked: boolean, reason?: string) {
467 const reasonString = reason ? ` for the following reason: ${reason}` : ''
468 const blockedWord = blocked ? 'blocked' : 'unblocked'
470 const to = user.email
471 const emailPayload: EmailPayload = {
473 subject: 'Account ' + blockedWord,
474 text: `Your account ${user.username} on ${WEBSERVER.HOST} has been ${blockedWord}${reasonString}.`
477 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
480 addContactFormJob (fromEmail: string, fromName: string, subject: string, body: string) {
481 const emailPayload: EmailPayload = {
482 template: 'contact-form',
483 to: [ CONFIG.ADMIN.EMAIL ],
484 replyTo: `"${fromName}" <${fromEmail}>`,
485 subject: `(contact form) ${subject}`,
493 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
496 async sendMail (options: EmailPayload) {
497 if (!isEmailEnabled()) {
498 throw new Error('Cannot send mail because SMTP is not configured.')
501 const fromDisplayName = options.from
505 const email = new Email({
508 from: `"${fromDisplayName}" <${CONFIG.SMTP.FROM_ADDRESS}>`
510 transport: this.transporter,
512 root: join(root(), 'dist', 'server', 'lib', 'emails')
514 subjectPrefix: CONFIG.EMAIL.SUBJECT.PREFIX
517 for (const to of options.to) {
525 subject: options.subject,
526 replyTo: options.replyTo
528 locals: { // default variables available in all templates
532 subject: options.subject
535 options // overriden/new variables given for a specific template in the payload
536 ) as SendEmailOptions)
537 .then(res => logger.debug('Sent email.', { res }))
538 .catch(err => logger.error('Error in email sender.', { err }))
542 private dieOnConnectionFailure (err?: Error) {
543 logger.error('Failed to connect to SMTP %s:%d.', CONFIG.SMTP.HOSTNAME, CONFIG.SMTP.PORT, { err })
547 static get Instance () {
548 return this.instance || (this.instance = new this())
552 // ---------------------------------------------------------------------------