| 1 | import { type Database, schema } from '@ghost/db'; |
| 2 | import { parseReferences } |
| 3 | import { Inject, Injectable |
| 4 | import { and, eq |
| 5 | |
| 6 | import { DATABASE } |
| 7 | import type { RepositoryEvent |
| 8 | import { ownerNameOf } |
| 9 | import { teamSlug } |
| 10 | import { MailService, type |
| 11 | import type { NotificationReason |
| 12 | import { RepositoryAccessService } |
| 13 | import { excluded } |
| 14 | |
| 15 | // Long enough to read the point of a comment in the email, short enough that nobody reads a whole essay there. |
| 16 | const EXCERPT_LENGTH = 1000 |
| 17 | |
| 18 | // GitHub's limit too: one comment cannot page a whole user base. |
| 19 | const MAX_MENTIONS = 50 |
| 20 | |
| 21 | const STATES = { |
| 22 | 'issue.closed': 'closed', |
| 23 | 'issue.reopened': 'reopened', |
| 24 | 'pull_request.merged': 'merged', |
| 25 | } as const; |
| 26 | |
| 27 | type Thread |
| 28 | |
| 29 | /** What an event says, as far as notifications care. */ |
| 30 | type Activity |
| 31 | /** Text whose `@user` and `@org/team` mentions notify, and subscribe, whoever they name. */ |
| 32 | text: string |
| 33 | assigneeIds: string |
| 34 | /** Whether the actor joined the conversation, and so subscribes to it. */ |
| 35 | participates: boolean |
| 36 | template: ThreadTemplate |
| 37 | context: Record |
| 38 | }; |
| 39 | |
| 40 | /** Turns repository events into inbox rows and emails. */ |
| 41 | @Injectable() |
| 42 | export class NotifierService |
| 43 | private readonly logger |
| 44 | |
| 45 | constructor( |
| 46 | @Inject(DATABASE) |
| 47 | private readonly access |
| 48 | private readonly mail |
| 49 | ) {} |
| 50 | |
| 51 | async handle(event |
| 52 | const thread = |
| 53 | if (!thread) |
| 54 | const activity = |
| 55 | if (!activity) |
| 56 | |
| 57 | const recipients = |
| 58 | if (recipients.size |
| 59 | |
| 60 | await this.db |
| 61 | .insert(schema.notification |
| 62 | .values( |
| 63 | [...recipients].map |
| 64 | userId, |
| 65 | issueId: thread.id |
| 66 | reason, |
| 67 | eventType: event.type |
| 68 | actorId: event.actorId |
| 69 | })), |
| 70 | ) |
| 71 | .onConflictDoUpdate({ |
| 72 | target: [schema.notification |
| 73 | set: { |
| 74 | reason: excluded(schema |
| 75 | eventType: excluded(schema |
| 76 | actorId: excluded(schema |
| 77 | unread: true, |
| 78 | updatedAt: sql`now()` |
| 79 | }, |
| 80 | }); |
| 81 | |
| 82 | await this.email |
| 83 | } |
| 84 | |
| 85 | private async loadThread |
| 86 | const [thread] |
| 87 | .select({ |
| 88 | id: schema.issue |
| 89 | number: schema.issue |
| 90 | title: schema.issue |
| 91 | body: schema.issue |
| 92 | isPullRequest: schema.issue |
| 93 | authorId: schema.issue |
| 94 | repositoryId: schema.issue |
| 95 | organizationId: schema.repository |
| 96 | repository: sql<string |
| 97 | }) |
| 98 | .from(schema.issue |
| 99 | .innerJoin( |
| 100 | schema.repository, |
| 101 | eq(schema.repository |
| 102 | ) |
| 103 | .innerJoin(schema.user |
| 104 | .leftJoin( |
| 105 | schema.organization, |
| 106 | eq(schema.organization |
| 107 | ) |
| 108 | .where(eq(schema |
| 109 | return thread; |
| 110 | } |
| 111 | |
| 112 | /** Null when what the event points at is gone, such as a comment deleted before its event was handled. */ |
| 113 | private async activityOf |
| 114 | event: RepositoryEvent |
| 115 | thread: Thread |
| 116 | ): Promise<Activity |
| 117 | switch (event.type |
| 118 | case 'issue.opened': { |
| 119 | const assignees = |
| 120 | .select({ userId: |
| 121 | .from(schema.issueAssignee |
| 122 | .where(eq(schema |
| 123 | return { |
| 124 | text: thread.body |
| 125 | assigneeIds: assignees.map |
| 126 | participates: true, |
| 127 | template: 'thread-opened', |
| 128 | context: { body: thread |
| 129 | }; |
| 130 | } |
| 131 | case 'issue.commented': { |
| 132 | const [comment] |
| 133 | .select({ body: |
| 134 | .from(schema.issueComment |
| 135 | .where(eq(schema |
| 136 | if (!comment) |
| 137 | return { |
| 138 | text: comment.body |
| 139 | assigneeIds: [], |
| 140 | participates: true, |
| 141 | template: 'thread-comment', |
| 142 | context: { body: excerpt |
| 143 | }; |
| 144 | } |
| 145 | case 'pull_request.review_commented': { |
| 146 | const [comment] |
| 147 | .select({ |
| 148 | body: schema.pullRequestReviewComment |
| 149 | path: schema.pullRequestReviewComment |
| 150 | }) |
| 151 | .from(schema.pullRequestReviewComment |
| 152 | .where( |
| 153 | eq(schema.pullRequestReviewComment |
| 154 | ); |
| 155 | if (!comment) |
| 156 | return { |
| 157 | text: comment.body |
| 158 | assigneeIds: [], |
| 159 | participates: true, |
| 160 | template: 'thread-comment', |
| 161 | context: { body: excerpt |
| 162 | }; |
| 163 | } |
| 164 | case 'pull_request.reviewed': { |
| 165 | const [review] |
| 166 | .select({ |
| 167 | state: schema.pullRequestReview |
| 168 | body: schema.pullRequestReview |
| 169 | }) |
| 170 | .from(schema.pullRequestReview |
| 171 | .where(eq(schema |
| 172 | if (!review) |
| 173 | const comments = |
| 174 | .select({ body: |
| 175 | .from(schema.pullRequestReviewComment |
| 176 | .where( |
| 177 | eq( |
| 178 | schema.pullRequestReviewComment.reviewId |
| 179 | event.payload.reviewId |
| 180 | ), |
| 181 | ); |
| 182 | return { |
| 183 | text: [review.body |
| 184 | '\n\n', |
| 185 | ), |
| 186 | assigneeIds: [], |
| 187 | participates: true, |
| 188 | template: 'thread-review', |
| 189 | context: { |
| 190 | state: review.state |
| 191 | body: review.body |
| 192 | commentCount: comments.length, |
| 193 | }, |
| 194 | }; |
| 195 | } |
| 196 | case 'issue.assigned': { |
| 197 | const [assignee] |
| 198 | .select({ username: |
| 199 | .from(schema.user |
| 200 | .where(eq(schema |
| 201 | if (!assignee) |
| 202 | return { |
| 203 | text: null, |
| 204 | assigneeIds: [event.payload |
| 205 | participates: false, |
| 206 | template: 'thread-assigned', |
| 207 | context: { assignee: assignee |
| 208 | }; |
| 209 | } |
| 210 | case 'issue.closed': |
| 211 | case 'issue.reopened': |
| 212 | case 'pull_request.merged': |
| 213 | return { |
| 214 | text: null, |
| 215 | assigneeIds: [], |
| 216 | participates: false, |
| 217 | template: 'thread-state', |
| 218 | context: { state: STATES |
| 219 | }; |
| 220 | } |
| 221 | } |
| 222 | |
| 223 | /** Everyone to notify, each with the most specific reason that applies. Nobody hears about their own activity, or about a repository they ignore or can no longer read. */ |
| 224 | private async recipientsOf |
| 225 | event: RepositoryEvent |
| 226 | thread: Thread |
| 227 | activity: Activity |
| 228 | ) { |
| 229 | const direct = |
| 230 | for (const userId |
| 231 | const mentions = |
| 232 | activity.text, |
| 233 | thread, |
| 234 | event.actorId, |
| 235 | ); |
| 236 | for (const userId |
| 237 | if (!direct.has |
| 238 | } |
| 239 | for (const userId |
| 240 | if (!direct.has |
| 241 | } |
| 242 | // mentioning someone who cannot read the thread must neither notify nor subscribe them |
| 243 | for (const userId |
| 244 | if (!(await |
| 245 | direct.delete(userId |
| 246 | } |
| 247 | } |
| 248 | |
| 249 | const joining = |
| 250 | if (activity.participates |
| 251 | if (joining.length |
| 252 | await this.db |
| 253 | .insert(schema.issueSubscription |
| 254 | .values( |
| 255 | joining.map((userId |
| 256 | userId, |
| 257 | issueId: thread.id |
| 258 | subscribed: true, |
| 259 | })), |
| 260 | ) |
| 261 | .onConflictDoNothing(); |
| 262 | } |
| 263 | |
| 264 | const [subscriptions, |
| 265 | this.db |
| 266 | .select({ |
| 267 | userId: schema.issueSubscription |
| 268 | subscribed: schema.issueSubscription |
| 269 | }) |
| 270 | .from(schema.issueSubscription |
| 271 | .where(eq(schema |
| 272 | this.db |
| 273 | .select({ |
| 274 | userId: schema.repositoryWatch |
| 275 | level: schema.repositoryWatch |
| 276 | }) |
| 277 | .from(schema.repositoryWatch |
| 278 | .where(eq(schema |
| 279 | ]); |
| 280 | |
| 281 | const subscribed = |
| 282 | subscriptions.map((row |
| 283 | ); |
| 284 | const ignoring = |
| 285 | watches.filter((row |
| 286 | ); |
| 287 | const indirect = |
| 288 | for (const [userId |
| 289 | if (isSubscribed) { |
| 290 | indirect.set( |
| 291 | userId, |
| 292 | userId === thread. |
| 293 | ); |
| 294 | } |
| 295 | } |
| 296 | for (const { |
| 297 | // an explicit unsubscribe silences watching too |
| 298 | if (level === |
| 299 | indirect.set(userId |
| 300 | } |
| 301 | |
| 302 | const recipients = |
| 303 | // ponytail: one access query per indirect recipient, batch them if threads with hundreds of subscribers show up |
| 304 | for (const [userId |
| 305 | if ( |
| 306 | !recipients.has(userId |
| 307 | (await this.access |
| 308 | ) { |
| 309 | recipients.set(userId |
| 310 | } |
| 311 | } |
| 312 | for (const userId |
| 313 | if (event.actorId |
| 314 | return recipients; |
| 315 | } |
| 316 | |
| 317 | /** `@org/team` counts only for the repository's own organization, and only from one of its members, so nobody can page a whole team from outside. */ |
| 318 | private async mentionsIn |
| 319 | text: string |
| 320 | thread: Thread |
| 321 | actorId: string |
| 322 | ) { |
| 323 | const references = |
| 324 | const usernames = |
| 325 | .flatMap((reference) |
| 326 | reference.kind === |
| 327 | ) |
| 328 | .slice(0, MAX_MENTIONS |
| 329 | const teamNames = |
| 330 | .flatMap((reference) |
| 331 | .slice(0, MAX_MENTIONS |
| 332 | |
| 333 | const users = |
| 334 | ? await this. |
| 335 | .select({ id: |
| 336 | .from(schema.user |
| 337 | .where(inArray(schema |
| 338 | : []; |
| 339 | |
| 340 | let teams: |
| 341 | if (teamNames.length |
| 342 | const [organization] |
| 343 | .select({ slug: |
| 344 | .from(schema.organization |
| 345 | .innerJoin( |
| 346 | schema.member, |
| 347 | and( |
| 348 | eq(schema.member |
| 349 | eq(schema.member |
| 350 | ), |
| 351 | ) |
| 352 | .where(eq(schema |
| 353 | const wanted = |
| 354 | teamNames |
| 355 | .filter((team) |
| 356 | .map((team) |
| 357 | ); |
| 358 | if (wanted.size |
| 359 | const members = |
| 360 | .select({ userId: |
| 361 | .from(schema.team |
| 362 | .innerJoin( |
| 363 | schema.teamMember, |
| 364 | eq(schema.teamMember |
| 365 | ) |
| 366 | .where(eq(schema |
| 367 | teams = members |
| 368 | .filter((member) |
| 369 | .map((member) |
| 370 | } |
| 371 | } |
| 372 | |
| 373 | return { users: |
| 374 | } |
| 375 | |
| 376 | /** Only to verified addresses, so nobody can sign up with someone else's address and have Ghost mail them. Best effort: a failed send is logged and skipped. */ |
| 377 | private async email |
| 378 | event: RepositoryEvent |
| 379 | thread: Thread |
| 380 | activity: Activity |
| 381 | recipients: Map |
| 382 | ) { |
| 383 | const [people, |
| 384 | this.db |
| 385 | .select({ id: |
| 386 | .from(schema.user |
| 387 | .where( |
| 388 | and( |
| 389 | inArray(schema.user |
| 390 | eq(schema.user |
| 391 | ), |
| 392 | ), |
| 393 | event.actorId |
| 394 | ? this.db |
| 395 | .select({ username: |
| 396 | .from(schema.user |
| 397 | .where(eq(schema |
| 398 | .then(([row |
| 399 | : undefined, |
| 400 | ]); |
| 401 | |
| 402 | const kind = |
| 403 | for (const person |
| 404 | try { |
| 405 | await this.mail |
| 406 | template: activity.template |
| 407 | threadId: thread.id |
| 408 | // a title is user input, and a line break in a header would start a new one |
| 409 | subject: `[${thread |
| 410 | context: { |
| 411 | ...activity.context |
| 412 | repository: thread.repository |
| 413 | number: thread.number |
| 414 | title: thread.title |
| 415 | isPullRequest: thread.isPullRequest |
| 416 | path: `/${thread |
| 417 | reason: recipients.get |
| 418 | actor: actor ?? |
| 419 | }, |
| 420 | }); |
| 421 | } catch (error) |
| 422 | this.logger.warn |
| 423 | `Emailing ${person.id |
| 424 | ); |
| 425 | } |
| 426 | } |
| 427 | } |
| 428 | } |
| 429 | |
| 430 | function excerpt(text: |
| 431 | const trimmed = |
| 432 | return trimmed.length |
| 433 | ? `${trimmed.slice |
| 434 | : trimmed; |
| 435 | } |