]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/emailer.ts
Bumped to version v5.2.1
[github/Chocobozzz/PeerTube.git] / server / lib / emailer.ts
1 import { readFileSync } from 'fs-extra'
2 import { merge } from 'lodash'
3 import { createTransport, Transporter } from 'nodemailer'
4 import { join } from 'path'
5 import { arrayify, root } from '@shared/core-utils'
6 import { EmailPayload, UserRegistrationState } 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 { MRegistration, 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 hideNotificationPreferencesLink: true
68 }
69 }
70
71 return JobQueue.Instance.createJobAsync({ type: 'email', payload: emailPayload })
72 }
73
74 addPasswordCreateEmailJob (username: string, to: string, createPasswordUrl: string) {
75 const emailPayload: EmailPayload = {
76 template: 'password-create',
77 to: [ to ],
78 subject: 'Create your account password',
79 locals: {
80 username,
81 createPasswordUrl,
82
83 hideNotificationPreferencesLink: true
84 }
85 }
86
87 return JobQueue.Instance.createJobAsync({ type: 'email', payload: emailPayload })
88 }
89
90 addVerifyEmailJob (options: {
91 username: string
92 isRegistrationRequest: boolean
93 to: string
94 verifyEmailUrl: string
95 }) {
96 const { username, isRegistrationRequest, to, verifyEmailUrl } = options
97
98 const emailPayload: EmailPayload = {
99 template: 'verify-email',
100 to: [ to ],
101 subject: `Verify your email on ${CONFIG.INSTANCE.NAME}`,
102 locals: {
103 username,
104 verifyEmailUrl,
105 isRegistrationRequest,
106
107 hideNotificationPreferencesLink: true
108 }
109 }
110
111 return JobQueue.Instance.createJobAsync({ type: 'email', payload: emailPayload })
112 }
113
114 addUserBlockJob (user: MUser, blocked: boolean, reason?: string) {
115 const reasonString = reason ? ` for the following reason: ${reason}` : ''
116 const blockedWord = blocked ? 'blocked' : 'unblocked'
117
118 const to = user.email
119 const emailPayload: EmailPayload = {
120 to: [ to ],
121 subject: 'Account ' + blockedWord,
122 text: `Your account ${user.username} on ${CONFIG.INSTANCE.NAME} has been ${blockedWord}${reasonString}.`
123 }
124
125 return JobQueue.Instance.createJobAsync({ type: 'email', payload: emailPayload })
126 }
127
128 addContactFormJob (fromEmail: string, fromName: string, subject: string, body: string) {
129 const emailPayload: EmailPayload = {
130 template: 'contact-form',
131 to: [ CONFIG.ADMIN.EMAIL ],
132 replyTo: `"${fromName}" <${fromEmail}>`,
133 subject: `(contact form) ${subject}`,
134 locals: {
135 fromName,
136 fromEmail,
137 body,
138
139 // There are not notification preferences for the contact form
140 hideNotificationPreferencesLink: true
141 }
142 }
143
144 return JobQueue.Instance.createJobAsync({ type: 'email', payload: emailPayload })
145 }
146
147 addUserRegistrationRequestProcessedJob (registration: MRegistration) {
148 let template: string
149 let subject: string
150 if (registration.state === UserRegistrationState.ACCEPTED) {
151 template = 'user-registration-request-accepted'
152 subject = `Your registration request for ${registration.username} has been accepted`
153 } else {
154 template = 'user-registration-request-rejected'
155 subject = `Your registration request for ${registration.username} has been rejected`
156 }
157
158 const to = registration.email
159 const emailPayload: EmailPayload = {
160 to: [ to ],
161 template,
162 subject,
163 locals: {
164 username: registration.username,
165 moderationResponse: registration.moderationResponse,
166 loginLink: WEBSERVER.URL + '/login'
167 }
168 }
169
170 return JobQueue.Instance.createJobAsync({ type: 'email', payload: emailPayload })
171 }
172
173 async sendMail (options: EmailPayload) {
174 if (!isEmailEnabled()) {
175 logger.info('Cannot send mail because SMTP is not configured.')
176 return
177 }
178
179 const fromDisplayName = options.from
180 ? options.from
181 : CONFIG.INSTANCE.NAME
182
183 const email = new Email({
184 send: true,
185 htmlToText: {
186 selectors: [
187 { selector: 'img', format: 'skip' },
188 { selector: 'a', options: { hideLinkHrefIfSameAsText: true } }
189 ]
190 },
191 message: {
192 from: `"${fromDisplayName}" <${CONFIG.SMTP.FROM_ADDRESS}>`
193 },
194 transport: this.transporter,
195 views: {
196 root: join(root(), 'dist', 'server', 'lib', 'emails')
197 },
198 subjectPrefix: CONFIG.EMAIL.SUBJECT.PREFIX
199 })
200
201 const toEmails = arrayify(options.to)
202
203 for (const to of toEmails) {
204 const baseOptions: SendEmailDefaultOptions = {
205 template: 'common',
206 message: {
207 to,
208 from: options.from,
209 subject: options.subject,
210 replyTo: options.replyTo
211 },
212 locals: { // default variables available in all templates
213 WEBSERVER,
214 EMAIL: CONFIG.EMAIL,
215 instanceName: CONFIG.INSTANCE.NAME,
216 text: options.text,
217 subject: options.subject
218 }
219 }
220
221 // overridden/new variables given for a specific template in the payload
222 const sendOptions = merge(baseOptions, options)
223
224 await email.send(sendOptions)
225 .then(res => logger.debug('Sent email.', { res }))
226 .catch(err => logger.error('Error in email sender.', { err }))
227 }
228 }
229
230 private warnOnConnectionFailure (err?: Error) {
231 logger.error('Failed to connect to SMTP %s:%d.', CONFIG.SMTP.HOSTNAME, CONFIG.SMTP.PORT, { err })
232 }
233
234 private initSMTPTransport () {
235 logger.info('Using %s:%s as SMTP server.', CONFIG.SMTP.HOSTNAME, CONFIG.SMTP.PORT)
236
237 let tls
238 if (CONFIG.SMTP.CA_FILE) {
239 tls = {
240 ca: [ readFileSync(CONFIG.SMTP.CA_FILE) ]
241 }
242 }
243
244 let auth
245 if (CONFIG.SMTP.USERNAME && CONFIG.SMTP.PASSWORD) {
246 auth = {
247 user: CONFIG.SMTP.USERNAME,
248 pass: CONFIG.SMTP.PASSWORD
249 }
250 }
251
252 this.transporter = createTransport({
253 host: CONFIG.SMTP.HOSTNAME,
254 port: CONFIG.SMTP.PORT,
255 secure: CONFIG.SMTP.TLS,
256 debug: CONFIG.LOG.LEVEL === 'debug',
257 logger: bunyanLogger as any,
258 ignoreTLS: CONFIG.SMTP.DISABLE_STARTTLS,
259 tls,
260 auth
261 })
262 }
263
264 private initSendmailTransport () {
265 logger.info('Using sendmail to send emails')
266
267 this.transporter = createTransport({
268 sendmail: true,
269 newline: 'unix',
270 path: CONFIG.SMTP.SENDMAIL,
271 logger: bunyanLogger
272 })
273 }
274
275 static get Instance () {
276 return this.instance || (this.instance = new this())
277 }
278 }
279
280 // ---------------------------------------------------------------------------
281
282 export {
283 Emailer
284 }