-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathnotification.ts
More file actions
61 lines (54 loc) · 1.79 KB
/
notification.ts
File metadata and controls
61 lines (54 loc) · 1.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import { DefaultContext, Middleware } from 'koa'
import { appName, appUrl, emailSender } from '../config/index.js'
import { sendMail } from '../services/mailerService.js'
import { generateHtmlMessage } from '../templates/generateMessage.js'
import { getVerifiedEmails } from './status.js'
export type GoodBody = {
'@context': 'https://www.w3.org/ns/activitystreams'
type: 'Create'
actor: { type: 'Person'; id: string; name?: string }
object: { type: 'Note'; id: string; content: string }
target: { type: 'Person'; id: string; name?: string }
}
export const notification: Middleware<
{ user: string; client: string | undefined },
DefaultContext & { request: { body: GoodBody } }
> = async ctx => {
const body: GoodBody = ctx.request.body
if (ctx.state.user !== body.actor.id)
return ctx.throw(403, "You can't send notification as somebody else")
// find email address
const emails = await getVerifiedEmails(body.target.id)
if (emails.length === 0)
return ctx.throw(
404,
"Receiving person doesn't have available email address",
)
for (const email of emails) {
const subject = `${body.actor.name || 'Someone'} wrote you from ${appName}`
await sendMail({
from: {
name: body.actor.name
? `${body.actor.name} (via ${appName})`
: `${appName} notifications`,
address: emailSender,
},
to: {
name: body.target.name ?? '',
address: email,
},
subject,
html: await generateHtmlMessage('message', {
...body,
title: subject,
chatLink: new URL(
`messages?with=${encodeURIComponent(body.actor.id)}`,
appUrl,
).toString(),
}),
text: body.object.content,
})
}
ctx.response.status = 202
ctx.response.body = 'Accepted'
}