| 1 | import { Inject, Injectable } from '@nestjs/common'; |
| 2 | import { ConfigService } from '@nestjs/config'; |
| 3 | import { type Database, schema } from '@ghost/db'; |
| 4 | import { and, count, eq, gte, inArray, lt, or, sum } from 'drizzle-orm'; |
| 5 | import { nanoid } from 'nanoid'; |
| 6 | import type { Readable } from 'node:stream'; |
| 7 | |
| 8 | import { DATABASE } from '../../database/database.module.js'; |
| 9 | import { S3Service } from '../../services/s3/s3.service.js'; |
| 10 | import { UsersService } from '../../services/users/users.service.js'; |
| 11 | import { |
| 12 | AVATAR_CONTENT_TYPES, |
| 13 | AVATAR_PREFIX, |
| 14 | type AvatarContentType, |
| 15 | } from './avatar.constants.js'; |
| 16 | import type { UploadAvatarResponseDTO } from './dto/avatar.dto.js'; |
| 17 | import type { |
| 18 | GetUserContributionsQueryDTO, |
| 19 | GetUserContributionsResponseDTO, |
| 20 | } from './dto/contributions.dto.js'; |
| 21 | import type { UserProfileResponseDTO } from './dto/profile.dto.js'; |
| 22 | import { |
| 23 | AvatarNotFoundError, |
| 24 | EmptyAvatarError, |
| 25 | UnsupportedAvatarTypeError, |
| 26 | } from './user.errors.js'; |
| 27 | |
| 28 | export type AvatarObject = { |
| 29 | stream: Readable; |
| 30 | contentType: string; |
| 31 | size?: number; |
| 32 | }; |
| 33 | |
| 34 | @Injectable() |
| 35 | export class UserService { |
| 36 | private readonly publicUrl: string; |
| 37 | |
| 38 | constructor( |
| 39 | @Inject(DATABASE) private readonly db: Database, |
| 40 | private readonly users: UsersService, |
| 41 | private readonly s3: S3Service, |
| 42 | configService: ConfigService, |
| 43 | ) { |
| 44 | this.publicUrl = configService |
| 45 | .getOrThrow<string>('BETTER_AUTH_URL') |
| 46 | .replace(/\/+$/, ''); |
| 47 | } |
| 48 | |
| 49 | /** The public profile: anything a signed-out visitor may see. */ |
| 50 | async getProfile(username: string): Promise<UserProfileResponseDTO> { |
| 51 | const user = await this.users.getUserByUsername(username); |
| 52 | |
| 53 | const publicRepositories = and( |
| 54 | eq(schema.repository.ownerId, user.id), |
| 55 | eq(schema.repository.visibility, 'public'), |
| 56 | ); |
| 57 | |
| 58 | const [[repositories], [stars]] = await Promise.all([ |
| 59 | this.db |
| 60 | .select({ value: count() }) |
| 61 | .from(schema.repository) |
| 62 | .where(publicRepositories), |
| 63 | this.db |
| 64 | .select({ value: count() }) |
| 65 | .from(schema.stars) |
| 66 | .innerJoin( |
| 67 | schema.repository, |
| 68 | eq(schema.repository.id, schema.stars.repositoryId), |
| 69 | ) |
| 70 | .where(publicRepositories), |
| 71 | ]); |
| 72 | |
| 73 | return { |
| 74 | username: user.username ?? username, |
| 75 | name: user.name, |
| 76 | image: user.image, |
| 77 | joinedAt: user.createdAt.toISOString(), |
| 78 | repositoryCount: repositories?.value ?? 0, |
| 79 | starCount: stars?.value ?? 0, |
| 80 | }; |
| 81 | } |
| 82 | |
| 83 | async uploadAvatar({ |
| 84 | userId, |
| 85 | contentType, |
| 86 | body, |
| 87 | }: { |
| 88 | userId: string; |
| 89 | contentType: string; |
| 90 | body: Buffer | undefined; |
| 91 | }): Promise<UploadAvatarResponseDTO> { |
| 92 | const extension = |
| 93 | AVATAR_CONTENT_TYPES[ |
| 94 | contentType.split(';')[0]?.trim() as AvatarContentType |
| 95 | ]; |
| 96 | |
| 97 | if (!extension) throw new UnsupportedAvatarTypeError(contentType); |
| 98 | if (!body?.length) throw new EmptyAvatarError(); |
| 99 | |
| 100 | const name = `${nanoid()}.${extension}`; |
| 101 | |
| 102 | await this.s3.putObject({ |
| 103 | Bucket: this.s3.bucket, |
| 104 | Key: this.avatarKey(userId, name), |
| 105 | Body: body, |
| 106 | ContentType: contentType, |
| 107 | }); |
| 108 | |
| 109 | await this.deleteAvatarObjects(userId, name); |
| 110 | |
| 111 | return { url: `${this.publicUrl}/api/users/avatars/${userId}/${name}` }; |
| 112 | } |
| 113 | |
| 114 | async deleteAvatar(userId: string): Promise<void> { |
| 115 | await this.deleteAvatarObjects(userId); |
| 116 | } |
| 117 | |
| 118 | async getAvatar(userId: string, name: string): Promise<AvatarObject> { |
| 119 | try { |
| 120 | const object = await this.s3.getObject({ |
| 121 | Bucket: this.s3.bucket, |
| 122 | Key: this.avatarKey(userId, name), |
| 123 | }); |
| 124 | |
| 125 | if (!object.Body) throw new AvatarNotFoundError(); |
| 126 | |
| 127 | return { |
| 128 | stream: object.Body as Readable, |
| 129 | contentType: object.ContentType ?? 'application/octet-stream', |
| 130 | size: object.ContentLength, |
| 131 | }; |
| 132 | } catch (error) { |
| 133 | if (error instanceof AvatarNotFoundError) throw error; |
| 134 | throw new AvatarNotFoundError(); |
| 135 | } |
| 136 | } |
| 137 | |
| 138 | private avatarKey(userId: string, name: string) { |
| 139 | return `${AVATAR_PREFIX}/${userId}/${name}`; |
| 140 | } |
| 141 | |
| 142 | private async deleteAvatarObjects(userId: string, keep?: string) { |
| 143 | await this.s3.deleteUnder( |
| 144 | `${AVATAR_PREFIX}/${userId}/`, |
| 145 | keep ? [this.avatarKey(userId, keep)] : [], |
| 146 | ); |
| 147 | } |
| 148 | |
| 149 | /** Daily commit counts for the contribution graph, read from the index alone: rendering a profile must not materialize every repository. */ |
| 150 | async getContributions( |
| 151 | username: string, |
| 152 | query: GetUserContributionsQueryDTO = {}, |
| 153 | requesterId?: string, |
| 154 | ): Promise<GetUserContributionsResponseDTO> { |
| 155 | const user = await this.users.getUserByUsername(username); |
| 156 | const now = new Date(); |
| 157 | const year = |
| 158 | Number.isFinite(Number(query.year)) && Number(query.year) >= 2000 |
| 159 | ? Math.trunc(Number(query.year)) |
| 160 | : now.getUTCFullYear(); |
| 161 | |
| 162 | const from = `${year}-01-01`; |
| 163 | const to = `${year + 1}-01-01`; |
| 164 | const counts = new Map<string, number>(); |
| 165 | |
| 166 | // Match on the account link or on a known author email, so adding an email never needs a reindex. Private repositories count only for their owner. |
| 167 | const emails = await this.users.listVerifiedEmails(user); |
| 168 | const rows = await this.db |
| 169 | .select({ |
| 170 | day: schema.repositoryContribution.day, |
| 171 | count: sum(schema.repositoryContribution.commits), |
| 172 | }) |
| 173 | .from(schema.repositoryContribution) |
| 174 | .innerJoin( |
| 175 | schema.repository, |
| 176 | eq(schema.repository.id, schema.repositoryContribution.repositoryId), |
| 177 | ) |
| 178 | .where( |
| 179 | and( |
| 180 | eq(schema.repository.ownerId, user.id), |
| 181 | inArray( |
| 182 | schema.repository.visibility, |
| 183 | user.id === requesterId ? ['private', 'public'] : ['public'], |
| 184 | ), |
| 185 | or( |
| 186 | eq(schema.repositoryContribution.authorId, user.id), |
| 187 | inArray(schema.repositoryContribution.authorEmail, emails), |
| 188 | ), |
| 189 | gte(schema.repositoryContribution.day, from), |
| 190 | lt(schema.repositoryContribution.day, to), |
| 191 | ), |
| 192 | ) |
| 193 | .groupBy(schema.repositoryContribution.day); |
| 194 | |
| 195 | for (const row of rows) { |
| 196 | counts.set(row.day, Number(row.count ?? 0)); |
| 197 | } |
| 198 | |
| 199 | const days: { date: string; count: number }[] = []; |
| 200 | for ( |
| 201 | let day = new Date(Date.UTC(year, 0, 1)); |
| 202 | day < new Date(Date.UTC(year + 1, 0, 1)); |
| 203 | day = new Date(day.getTime() + 86_400_000) |
| 204 | ) { |
| 205 | const date = day.toISOString().slice(0, 10); |
| 206 | days.push({ date, count: counts.get(date) ?? 0 }); |
| 207 | } |
| 208 | |
| 209 | return { |
| 210 | username: user.username ?? username, |
| 211 | year, |
| 212 | totalContributions: days.reduce((total, d) => total + d.count, 0), |
| 213 | days, |
| 214 | }; |
| 215 | } |
| 216 | } |