]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/emailer.ts
Use bullmq job dependency
[github/Chocobozzz/PeerTube.git] / server / lib / emailer.ts
1 import { readFileSync } from 'fs-extra'
2 import { isArray, merge } from 'lodash'
3 import { createTransport, Transporter } from 'nodemailer'
4 import { join } from 'path'
5 import { root } from '@shared/core-utils'
6 import { EmailPayload } from '@shared/models'
7 import { SendEmailDefaultOptions } from '../../shared/models/server/emailer.model'
8 import { isTestOrDevInstance } from '../helpers/core-utils'
9 import { bunyanLogger, logger } from '../helpers/logger'
10 import { CONFIG, isEmailEnabled } from '../initializers/config'
11 import { WEBSERVER } from '../initializers/constants'
12 import { MUser } from '../types/models'
13 import { JobQueue } from './job-queue'
14
15 const Email = require('email-templates')
16
17 class Emailer {
18
19 private static instance: Emailer
20 private initialized = false
21 private transporter: Transporter
22
23 private constructor () {
24 }
25
26 init () {
27 // Already initialized
28 if (this.initialized === true) return
29 this.initialized = true
30
31 if (!isEmailEnabled()) {
32 if (!isTestOrDevInstance()) {
33 logger.error('Cannot use SMTP server because of lack of configuration. PeerTube will not be able to send mails!')
34 }
35
36 return
37 }
38
39 if (CONFIG.SMTP.TRANSPORT === 'smtp') this.initSMTPTransport()
40 else if (CONFIG.SMTP.TRANSPORT === 'sendmail') this.initSendmailTransport()
41 }
42
43 async checkConnection () {
44 if (!this.transporter || CONFIG.SMTP.TRANSPORT !== 'smtp') return
45
46 logger.info('Testing SMTP server...')
47
48 try {
49 const success = await this.transporter.verify()
50 if (success !== true) this.warnOnConnectionFailure()
51
52 logger.info('Successfully connected to SMTP server.')
53 } catch (err) {
54 this.warnOnConnectionFailure(err)
55 }
56 }
57
58 addPasswordResetEmailJob (username: string, to: string, resetPasswordUrl: string) {
59 const emailPayload: EmailPayload = {
60 template: 'password-reset',
61 to: [ to ],
62 subject: 'Reset your account password',
63 locals: {
64 username,
65 resetPasswordUrl
66 }
67 }
68
69 return JobQueue.Instance.createJobAsync({ type: 'email', payload: emailPayload })
70 }
71
72 addPasswordCreateEmailJob (username: string, to: string, createPasswordUrl: string) {
73 const emailPayload: EmailPayload = {
74 template: 'password-create',
75 to: [ to ],
76 subject: 'Create your account password',
77 locals: {
78 username,
79 createPasswordUrl
80 }
81 }
82
83 return JobQueue.Instance.createJobAsync({ type: 'email', payload: emailPayload })
84 }
85
86 addVerifyEmailJob (username: string, to: string, verifyEmailUrl: string) {
87 const emailPayload: EmailPayload = {
88 template: 'verify-email',
89 to: [ to ],
90 subject: `Verify your email on ${CONFIG.INSTANCE.NAME}`,
91 locals: {
92 username,
93 verifyEmailUrl
94 }
95 }
96
97 return JobQueue.Instance.createJobAsync({ type: 'email', payload: emailPayload })
98 }
99
100 addUserBlockJob (user: MUser, blocked: boolean, reason?: string) {
101 const reasonString = reason ? ` for the following reason: ${reason}` : ''
102 const blockedWord = blocked ? 'blocked' : 'unblocked'
103
104 const to = user.email
105 const emailPayload: EmailPayload = {
106 to: [ to ],
107 subject: 'Account ' + blockedWord,
108 text: `Your account ${user.username} on ${CONFIG.INSTANCE.NAME} has been ${blockedWord}${reasonString}.`
109 }
110
111 return JobQueue.Instance.createJobAsync({ type: 'email', payload: emailPayload })
112 }
113
114 addContactFormJob (fromEmail: string, fromName: string, subject: string, body: string) {
115 const emailPayload: EmailPayload = {
116 template: 'contact-form',
117 to: [ CONFIG.ADMIN.EMAIL ],
118 replyTo: `"${fromName}" <${fromEmail}>`,
119 subject: `(contact form) ${subject}`,
120 locals: {
121 fromName,
122 fromEmail,
123 body,
124
125 // There are not notification preferences for the contact form
126 hideNotificationPreferences: true
127 }
128 }
129
130 return JobQueue.Instance.createJobAsync({ type: 'email', payload: emailPayload })
131 }
132
133 async sendMail (options: EmailPayload) {
134 if (!isEmailEnabled()) {
135 logger.info('Cannot send mail because SMTP is not configured.')
136 return
137 }
138
139 const fromDisplayName = options.from
140 ? options.from
141 : CONFIG.INSTANCE.NAME
142
143 const email = new Email({
144 send: true,
145 htmlToText: {
146 selectors: [
147 { selector: 'img', format: 'skip' },
148 { selector: 'a', options: { hideLinkHrefIfSameAsText: true } }
149 ]
150 },
151 message: {
152 from: `"${fromDisplayName}" <${CONFIG.SMTP.FROM_ADDRESS}>`
153 },
154 transport: this.transporter,
155 views: {
156 root: join(root(), 'dist', 'server', 'lib', 'emails')
157 },
158 subjectPrefix: CONFIG.EMAIL.SUBJECT.PREFIX
159 })
160
161 const toEmails = isArray(options.to)
162 ? options.to
163 : [ options.to ]
164
165 for (const to of toEmails) {
166 const baseOptions: SendEmailDefaultOptions = {
167 template: 'common',
168 message: {
169 to,
170 from: options.from,
171 subject: options.subject,
172 replyTo: options.replyTo
173 },
174 locals: { // default variables available in all templates
175 WEBSERVER,
176 EMAIL: CONFIG.EMAIL,
177 instanceName: CONFIG.INSTANCE.NAME,
178 text: options.text,
179 subject: options.subject
180 }
181 }
182
183 // overridden/new variables given for a specific template in the payload
184 const sendOptions = merge(baseOptions, options)
185
186 await email.send(sendOptions)
187 .then(res => logger.debug('Sent email.', { res }))
188 .catch(err => logger.error('Error in email sender.', { err }))
189 }
190 }
191
192 private warnOnConnectionFailure (err?: Error) {
193 logger.error('Failed to connect to SMTP %s:%d.', CONFIG.SMTP.HOSTNAME, CONFIG.SMTP.PORT, { err })
194 }
195
196 private initSMTPTransport () {
197 logger.info('Using %s:%s as SMTP server.', CONFIG.SMTP.HOSTNAME, CONFIG.SMTP.PORT)
198
199 let tls
200 if (CONFIG.SMTP.CA_FILE) {
201 tls = {
202 ca: [ readFileSync(CONFIG.SMTP.CA_FILE) ]
203 }
204 }
205
206 let auth
207 if (CONFIG.SMTP.USERNAME && CONFIG.SMTP.PASSWORD) {
208 auth = {
209 user: CONFIG.SMTP.USERNAME,
210 pass: CONFIG.SMTP.PASSWORD
211 }
212 }
213
214 this.transporter = createTransport({
215 host: CONFIG.SMTP.HOSTNAME,
216 port: CONFIG.SMTP.PORT,
217 secure: CONFIG.SMTP.TLS,
218 debug: CONFIG.LOG.LEVEL === 'debug',
219 logger: bunyanLogger as any,
220 ignoreTLS: CONFIG.SMTP.DISABLE_STARTTLS,
221 tls,
222 auth
223 })
224 }
225
226 private initSendmailTransport () {
227 logger.info('Using sendmail to send emails')
228
229 this.transporter = createTransport({
230 sendmail: true,
231 newline: 'unix',
232 path: CONFIG.SMTP.SENDMAIL,
233 logger: bunyanLogger
234 })
235 }
236
237 static get Instance () {
238 return this.instance || (this.instance = new this())
239 }
240 }
241
242 // ---------------------------------------------------------------------------
243
244 export {
245 Emailer
246 }