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: abuse.video.channel,
319 } else if (abuseInstance.VideoCommentAbuse) {
320 const comment = abuseInstance.VideoCommentAbuse.VideoComment
321 const commentUrl = WEBSERVER.URL + comment.Video.getWatchStaticPath() + ';threadId=' + comment.getThreadId()
324 template: 'video-comment-abuse-new',
326 subject: `New comment abuse report from ${reporter}`,
329 videoName: comment.Video.name,
330 isLocal: comment.isOwned(),
331 commentCreatedAt: new Date(comment.createdAt).toLocaleString(),
332 reason: abuse.reason,
333 flaggedAccount: abuseInstance.FlaggedAccount.getDisplayName(),
339 const account = abuseInstance.FlaggedAccount
340 const accountUrl = account.getClientUrl()
343 template: 'account-abuse-new',
345 subject: `New account abuse report from ${reporter}`,
348 accountDisplayName: account.getDisplayName(),
349 isLocal: account.isOwned(),
350 reason: abuse.reason,
357 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
360 async addVideoAutoBlacklistModeratorsNotification (to: string[], videoBlacklist: MVideoBlacklistLightVideo) {
361 const VIDEO_AUTO_BLACKLIST_URL = WEBSERVER.URL + '/admin/moderation/video-auto-blacklist/list'
362 const videoUrl = WEBSERVER.URL + videoBlacklist.Video.getWatchStaticPath()
363 const channel = (await VideoChannelModel.loadByIdAndPopulateAccount(videoBlacklist.Video.channelId)).toFormattedSummaryJSON()
365 const emailPayload: EmailPayload = {
366 template: 'video-auto-blacklist-new',
368 subject: 'A new video is pending moderation',
372 videoName: videoBlacklist.Video.name,
374 text: 'Review autoblacklist',
375 url: VIDEO_AUTO_BLACKLIST_URL
380 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
383 addNewUserRegistrationNotification (to: string[], user: MUser) {
384 const emailPayload: EmailPayload = {
385 template: 'user-registered',
387 subject: `a new user registered on ${WEBSERVER.HOST}: ${user.username}`,
393 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
396 addVideoBlacklistNotification (to: string[], videoBlacklist: MVideoBlacklistVideo) {
397 const videoName = videoBlacklist.Video.name
398 const videoUrl = WEBSERVER.URL + videoBlacklist.Video.getWatchStaticPath()
400 const reasonString = videoBlacklist.reason ? ` for the following reason: ${videoBlacklist.reason}` : ''
401 const blockedString = `Your video ${videoName} (${videoUrl} on ${WEBSERVER.HOST} has been blacklisted${reasonString}.`
403 const emailPayload: EmailPayload = {
405 subject: `Video ${videoName} blacklisted`,
408 title: 'Your video was blacklisted'
412 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
415 addVideoUnblacklistNotification (to: string[], video: MVideo) {
416 const videoUrl = WEBSERVER.URL + video.getWatchStaticPath()
418 const emailPayload: EmailPayload = {
420 subject: `Video ${video.name} unblacklisted`,
421 text: `Your video "${video.name}" (${videoUrl}) on ${WEBSERVER.HOST} has been unblacklisted.`,
423 title: 'Your video was unblacklisted'
427 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
430 addPasswordResetEmailJob (username: string, to: string, resetPasswordUrl: string) {
431 const emailPayload: EmailPayload = {
432 template: 'password-reset',
434 subject: 'Reset your account password',
441 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
444 addPasswordCreateEmailJob (username: string, to: string, createPasswordUrl: string) {
445 const emailPayload: EmailPayload = {
446 template: 'password-create',
448 subject: 'Create your account password',
455 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
458 addVerifyEmailJob (username: string, to: string, verifyEmailUrl: string) {
459 const emailPayload: EmailPayload = {
460 template: 'verify-email',
462 subject: `Verify your email on ${WEBSERVER.HOST}`,
469 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
472 addUserBlockJob (user: MUser, blocked: boolean, reason?: string) {
473 const reasonString = reason ? ` for the following reason: ${reason}` : ''
474 const blockedWord = blocked ? 'blocked' : 'unblocked'
476 const to = user.email
477 const emailPayload: EmailPayload = {
479 subject: 'Account ' + blockedWord,
480 text: `Your account ${user.username} on ${WEBSERVER.HOST} has been ${blockedWord}${reasonString}.`
483 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
486 addContactFormJob (fromEmail: string, fromName: string, subject: string, body: string) {
487 const emailPayload: EmailPayload = {
488 template: 'contact-form',
489 to: [ CONFIG.ADMIN.EMAIL ],
490 replyTo: `"${fromName}" <${fromEmail}>`,
491 subject: `(contact form) ${subject}`,
499 return JobQueue.Instance.createJob({ type: 'email', payload: emailPayload })
502 async sendMail (options: EmailPayload) {
503 if (!isEmailEnabled()) {
504 throw new Error('Cannot send mail because SMTP is not configured.')
507 const fromDisplayName = options.from
511 const email = new Email({
514 from: `"${fromDisplayName}" <${CONFIG.SMTP.FROM_ADDRESS}>`
516 transport: this.transporter,
518 root: join(root(), 'dist', 'server', 'lib', 'emails')
520 subjectPrefix: CONFIG.EMAIL.SUBJECT.PREFIX
523 for (const to of options.to) {
531 subject: options.subject,
532 replyTo: options.replyTo
534 locals: { // default variables available in all templates
538 subject: options.subject
541 options // overriden/new variables given for a specific template in the payload
542 ) as SendEmailOptions)
543 .then(res => logger.debug('Sent email.', { res }))
544 .catch(err => logger.error('Error in email sender.', { err }))
548 private dieOnConnectionFailure (err?: Error) {
549 logger.error('Failed to connect to SMTP %s:%d.', CONFIG.SMTP.HOSTNAME, CONFIG.SMTP.PORT, { err })
553 static get Instance () {
554 return this.instance || (this.instance = new this())
558 // ---------------------------------------------------------------------------