@meith/avatars 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE.md ADDED
@@ -0,0 +1,165 @@
1
+ GNU LESSER GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+
9
+ This version of the GNU Lesser General Public License incorporates
10
+ the terms and conditions of version 3 of the GNU General Public
11
+ License, supplemented by the additional permissions listed below.
12
+
13
+ 0. Additional Definitions.
14
+
15
+ As used herein, "this License" refers to version 3 of the GNU Lesser
16
+ General Public License, and the "GNU GPL" refers to version 3 of the GNU
17
+ General Public License.
18
+
19
+ "The Library" refers to a covered work governed by this License,
20
+ other than an Application or a Combined Work as defined below.
21
+
22
+ An "Application" is any work that makes use of an interface provided
23
+ by the Library, but which is not otherwise based on the Library.
24
+ Defining a subclass of a class defined by the Library is deemed a mode
25
+ of using an interface provided by the Library.
26
+
27
+ A "Combined Work" is a work produced by combining or linking an
28
+ Application with the Library. The particular version of the Library
29
+ with which the Combined Work was made is also called the "Linked
30
+ Version".
31
+
32
+ The "Minimal Corresponding Source" for a Combined Work means the
33
+ Corresponding Source for the Combined Work, excluding any source code
34
+ for portions of the Combined Work that, considered in isolation, are
35
+ based on the Application, and not on the Linked Version.
36
+
37
+ The "Corresponding Application Code" for a Combined Work means the
38
+ object code and/or source code for the Application, including any data
39
+ and utility programs needed for reproducing the Combined Work from the
40
+ Application, but excluding the System Libraries of the Combined Work.
41
+
42
+ 1. Exception to Section 3 of the GNU GPL.
43
+
44
+ You may convey a covered work under sections 3 and 4 of this License
45
+ without being bound by section 3 of the GNU GPL.
46
+
47
+ 2. Conveying Modified Versions.
48
+
49
+ If you modify a copy of the Library, and, in your modifications, a
50
+ facility refers to a function or data to be supplied by an Application
51
+ that uses the facility (other than as an argument passed when the
52
+ facility is invoked), then you may convey a copy of the modified
53
+ version:
54
+
55
+ a) under this License, provided that you make a good faith effort to
56
+ ensure that, in the event an Application does not supply the
57
+ function or data, the facility still operates, and performs
58
+ whatever part of its purpose remains meaningful, or
59
+
60
+ b) under the GNU GPL, with none of the additional permissions of
61
+ this License applicable to that copy.
62
+
63
+ 3. Object Code Incorporating Material from Library Header Files.
64
+
65
+ The object code form of an Application may incorporate material from
66
+ a header file that is part of the Library. You may convey such object
67
+ code under terms of your choice, provided that, if the incorporated
68
+ material is not limited to numerical parameters, data structure
69
+ layouts and accessors, or small macros, inline functions and templates
70
+ (ten or fewer lines in length), you do both of the following:
71
+
72
+ a) Give prominent notice with each copy of the object code that the
73
+ Library is used in it and that the Library and its use are
74
+ covered by this License.
75
+
76
+ b) Accompany the object code with a copy of the GNU GPL and this license
77
+ document.
78
+
79
+ 4. Combined Works.
80
+
81
+ You may convey a Combined Work under terms of your choice that,
82
+ taken together, effectively do not restrict modification of the
83
+ portions of the Library contained in the Combined Work and reverse
84
+ engineering for debugging such modifications, if you also do each of
85
+ the following:
86
+
87
+ a) Give prominent notice with each copy of the Combined Work that
88
+ the Library is used in it and that the Library and its use are
89
+ covered by this License.
90
+
91
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
92
+ document.
93
+
94
+ c) For a Combined Work that displays copyright notices during
95
+ execution, include the copyright notice for the Library among
96
+ these notices, as well as a reference directing the user to the
97
+ copies of the GNU GPL and this license document.
98
+
99
+ d) Do one of the following:
100
+
101
+ 0) Convey the Minimal Corresponding Source under the terms of this
102
+ License, and the Corresponding Application Code in a form
103
+ suitable for, and under terms that permit, the user to
104
+ recombine or relink the Application with a modified version of
105
+ the Linked Version to produce a modified Combined Work, in the
106
+ manner specified by section 6 of the GNU GPL for conveying
107
+ Corresponding Source.
108
+
109
+ 1) Use a suitable shared library mechanism for linking with the
110
+ Library. A suitable mechanism is one that (a) uses at run time
111
+ a copy of the Library already present on the user's computer
112
+ system, and (b) will operate properly with a modified version
113
+ of the Library that is interface-compatible with the Linked
114
+ Version.
115
+
116
+ e) Provide Installation Information, but only if you would otherwise
117
+ be required to provide such information under section 6 of the
118
+ GNU GPL, and only to the extent that such information is
119
+ necessary to install and execute a modified version of the
120
+ Combined Work produced by recombining or relinking the
121
+ Application with a modified version of the Linked Version. (If
122
+ you use option 4d0, the Installation Information must accompany
123
+ the Minimal Corresponding Source and Corresponding Application
124
+ Code. If you use option 4d1, you must provide the Installation
125
+ Information in the manner specified by section 6 of the GNU GPL
126
+ for conveying Corresponding Source.)
127
+
128
+ 5. Combined Libraries.
129
+
130
+ You may place library facilities that are a work based on the
131
+ Library side by side in a single library together with other library
132
+ facilities that are not Applications and are not covered by this
133
+ License, and convey such a combined library under terms of your
134
+ choice, if you do both of the following:
135
+
136
+ a) Accompany the combined library with a copy of the same work based
137
+ on the Library, uncombined with any other library facilities,
138
+ conveyed under the terms of this License.
139
+
140
+ b) Give prominent notice with the combined library that part of it
141
+ is a work based on the Library, and explaining where to find the
142
+ accompanying uncombined form of the same work.
143
+
144
+ 6. Revised Versions of the GNU Lesser General Public License.
145
+
146
+ The Free Software Foundation may publish revised and/or new versions
147
+ of the GNU Lesser General Public License from time to time. Such new
148
+ versions will be similar in spirit to the present version, but may
149
+ differ in detail to address new problems or concerns.
150
+
151
+ Each version is given a distinguishing version number. If the
152
+ Library as you received it specifies that a certain numbered version
153
+ of the GNU Lesser General Public License "or any later version"
154
+ applies to it, you have the option of following the terms and
155
+ conditions either of that published version or of any later version
156
+ published by the Free Software Foundation. If the Library as you
157
+ received it does not specify a version number of the GNU Lesser
158
+ General Public License, you may choose any version of the GNU Lesser
159
+ General Public License ever published by the Free Software Foundation.
160
+
161
+ If the Library as you received it specifies that a proxy can decide
162
+ whether future versions of the GNU Lesser General Public License shall
163
+ apply, that proxy's public statement of acceptance of any version is
164
+ permanent authorization for you to choose that version for the
165
+ Library.
package/package.json ADDED
@@ -0,0 +1,30 @@
1
+ {
2
+ "name": "@meith/avatars",
3
+ "version": "0.16.0",
4
+ "license": "LGPL-3.0-or-later",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/meith-dev/meith.git",
8
+ "directory": "packages/avatars"
9
+ },
10
+ "type": "module",
11
+ "main": "./src/index.ts",
12
+ "types": "./src/index.ts",
13
+ "exports": {
14
+ ".": "./src/index.ts",
15
+ "./limits": "./src/limits.ts"
16
+ },
17
+ "files": [
18
+ "src",
19
+ "!src/**/*.test.*",
20
+ "!src/**/*.type-test.*"
21
+ ],
22
+ "publishConfig": {
23
+ "access": "public"
24
+ },
25
+ "dependencies": {
26
+ "@meith/core": "0.16.0",
27
+ "@meith/attachments": "0.16.0",
28
+ "@meith/i18n": "0.16.0"
29
+ }
30
+ }
package/src/index.ts ADDED
@@ -0,0 +1,253 @@
1
+ import {
2
+ type AcceptedUpload,
3
+ acceptFile,
4
+ type ImageProcessor,
5
+ type IncomingFile,
6
+ storageKeyFor,
7
+ } from '@meith/attachments'
8
+ import type { FileStore } from '@meith/core'
9
+ import { ForbiddenError, ValidationError } from '@meith/core'
10
+ import { msg } from '@meith/i18n'
11
+
12
+ import { AVATAR_BOX, AVATAR_MAX_BYTES } from './limits'
13
+
14
+ export { AVATAR_BOX, AVATAR_MAX_BYTES } from './limits'
15
+
16
+ export type AvatarStatus = 'none' | 'pending' | 'ready' | 'failed'
17
+
18
+ export interface StoredAvatar {
19
+ readonly status: AvatarStatus
20
+ readonly key: string | null
21
+ readonly sourceKey: string | null
22
+ readonly width: number | null
23
+ readonly height: number | null
24
+ readonly failureReason: string | null
25
+ readonly updatedAt: Date | null
26
+ readonly locked: boolean
27
+ readonly lockedReason: string | null
28
+ }
29
+
30
+ export const NO_AVATAR: StoredAvatar = {
31
+ status: 'none',
32
+ key: null,
33
+ sourceKey: null,
34
+ width: null,
35
+ height: null,
36
+ failureReason: null,
37
+ updatedAt: null,
38
+ locked: false,
39
+ lockedReason: null,
40
+ }
41
+
42
+ export function avatarVisible(avatar: StoredAvatar): boolean {
43
+ return avatar.status === 'ready' && avatar.key !== null && !avatar.locked
44
+ }
45
+
46
+ export function avatarUrl(userId: number, avatar: StoredAvatar): string | null {
47
+ if (!avatarVisible(avatar)) return null
48
+ const version = avatar.updatedAt === null ? 0 : avatar.updatedAt.getTime()
49
+ return `/avatar/${userId}?v=${version}`
50
+ }
51
+
52
+ export interface AvatarRepository {
53
+ find(userId: number): Promise<StoredAvatar | null>
54
+ readMany(userIds: readonly number[]): Promise<ReadonlyMap<number, StoredAvatar>>
55
+ beginUpload(input: {
56
+ readonly userId: number
57
+ readonly sourceKey: string
58
+ readonly at: Date
59
+ }): Promise<{ readonly replaced: readonly string[] }>
60
+ markReady(input: {
61
+ readonly userId: number
62
+ readonly key: string
63
+ readonly width: number
64
+ readonly height: number
65
+ }): Promise<void>
66
+ markFailed(userId: number, reason: string): Promise<void>
67
+ clear(userId: number): Promise<{ readonly replaced: readonly string[] }>
68
+ lock(input: {
69
+ readonly userId: number
70
+ readonly locked: boolean
71
+ readonly reason: string | null
72
+ }): Promise<void>
73
+ stalled(before: Date, limit: number): Promise<readonly number[]>
74
+
75
+ rememberKey(key: string): Promise<void>
76
+ forgetKeys(keys: readonly string[]): Promise<void>
77
+ }
78
+
79
+ export interface AvatarServiceDeps {
80
+ readonly avatars: AvatarRepository
81
+ readonly files: FileStore
82
+ readonly images: ImageProcessor
83
+ readonly random?: () => string
84
+ readonly now?: () => Date
85
+ }
86
+
87
+ export const AVATAR_PROCESSING_GRACE_MINUTES = 30
88
+
89
+ export class AvatarService {
90
+ private readonly deps: AvatarServiceDeps
91
+ private readonly random: () => string
92
+ private readonly now: () => Date
93
+
94
+ constructor(deps: AvatarServiceDeps) {
95
+ this.deps = deps
96
+ this.random = deps.random ?? (() => crypto.randomUUID())
97
+ this.now = deps.now ?? (() => new Date())
98
+ }
99
+
100
+ async upload(input: {
101
+ readonly userId: number
102
+ readonly file: IncomingFile
103
+ readonly mayUpload: boolean
104
+ }): Promise<void> {
105
+ if (!input.mayUpload) {
106
+ throw new ForbiddenError(msg('error.avatars.upload-avatar'))
107
+ }
108
+
109
+ const current = await this.deps.avatars.find(input.userId)
110
+ if (current?.locked === true) {
111
+ throw new ForbiddenError(msg('error.avatars.moderator-locked-avatar-so-changed'))
112
+ }
113
+
114
+ const accepted = this.accept(input.file)
115
+
116
+ const key = storageKeyFor('source', this.random)
117
+ await this.deps.avatars.rememberKey(key)
118
+ await this.deps.files.put(key, accepted.bytes, {
119
+ contentType: accepted.type.contentType,
120
+ visibility: 'private',
121
+ })
122
+
123
+ const { replaced } = await this.deps.avatars.beginUpload({
124
+ userId: input.userId,
125
+ sourceKey: key,
126
+ at: this.now(),
127
+ })
128
+ await this.deps.avatars.forgetKeys([key])
129
+ await this.sweepKeys(replaced)
130
+ }
131
+
132
+ private accept(file: IncomingFile): AcceptedUpload {
133
+ const accepted = acceptFile(file, {
134
+ maxPerPost: 1,
135
+ maxSizeKb: AVATAR_MAX_BYTES / 1024,
136
+ })
137
+
138
+ if (accepted.type.codec === null) {
139
+ throw new ValidationError(msg('error.avatars.avatar-must-png-jpeg'))
140
+ }
141
+ return accepted
142
+ }
143
+
144
+ async process(userId: number): Promise<'done' | 'skipped' | 'failed'> {
145
+ const current = await this.deps.avatars.find(userId)
146
+ if (current === null || current.status !== 'pending' || current.sourceKey === null) {
147
+ return 'skipped'
148
+ }
149
+
150
+ const source = await this.deps.files.get(current.sourceKey)
151
+ if (source === undefined) {
152
+ await this.fail(userId, 'The uploaded file is no longer available.', current.sourceKey)
153
+ return 'failed'
154
+ }
155
+
156
+ const accepted = (() => {
157
+ try {
158
+ return this.accept({ filename: 'avatar', bytes: source })
159
+ } catch {
160
+ return null
161
+ }
162
+ })()
163
+
164
+ if (accepted === null) {
165
+ await this.fail(userId, 'That image could not be read.', current.sourceKey)
166
+ return 'failed'
167
+ }
168
+
169
+ let processed: Awaited<ReturnType<ImageProcessor['process']>>
170
+ try {
171
+ processed = await this.deps.images.process({
172
+ bytes: source,
173
+ codec: accepted.type.codec as 'png' | 'jpeg',
174
+ fit: AVATAR_BOX,
175
+ thumbnail: false,
176
+ })
177
+ } catch {
178
+ await this.fail(userId, 'That image could not be read.', current.sourceKey)
179
+ return 'failed'
180
+ }
181
+
182
+ const key = storageKeyFor('file', this.random)
183
+ await this.deps.avatars.rememberKey(key)
184
+ await this.deps.files.put(key, processed.bytes, {
185
+ contentType: processed.contentType,
186
+ visibility: 'private',
187
+ })
188
+
189
+ await this.deps.avatars.markReady({
190
+ userId,
191
+ key,
192
+ width: processed.width,
193
+ height: processed.height,
194
+ })
195
+ await this.deps.avatars.forgetKeys([key])
196
+ await this.discard(current.sourceKey)
197
+ return 'done'
198
+ }
199
+
200
+ async remove(userId: number): Promise<void> {
201
+ const current = await this.deps.avatars.find(userId)
202
+ if (current?.locked === true) {
203
+ throw new ForbiddenError(msg('error.avatars.moderator-locked-avatar-so-changed'))
204
+ }
205
+ const { replaced } = await this.deps.avatars.clear(userId)
206
+ await this.sweepKeys(replaced)
207
+ }
208
+
209
+ async setLock(input: {
210
+ readonly userId: number
211
+ readonly locked: boolean
212
+ readonly reason: string
213
+ }): Promise<void> {
214
+ const reason = input.reason.trim()
215
+ if (input.locked && reason === '') {
216
+ throw new ValidationError(msg('error.avatars.give-reason-member-shown'))
217
+ }
218
+ await this.deps.avatars.lock({
219
+ userId: input.userId,
220
+ locked: input.locked,
221
+ reason: input.locked ? reason : null,
222
+ })
223
+ }
224
+
225
+ async sweep(limit = 200): Promise<number> {
226
+ const cutoff = new Date(this.now().getTime() - AVATAR_PROCESSING_GRACE_MINUTES * 60_000)
227
+ const stalled = await this.deps.avatars.stalled(cutoff, limit)
228
+
229
+ for (const userId of stalled) {
230
+ const current = await this.deps.avatars.find(userId)
231
+ await this.deps.avatars.markFailed(
232
+ userId,
233
+ 'Processing did not finish. Please upload it again.',
234
+ )
235
+ if (current?.sourceKey != null) await this.discard(current.sourceKey)
236
+ }
237
+ return stalled.length
238
+ }
239
+
240
+ private async fail(userId: number, reason: string, sourceKey: string): Promise<void> {
241
+ await this.deps.avatars.markFailed(userId, reason)
242
+ await this.discard(sourceKey)
243
+ }
244
+
245
+ private async sweepKeys(keys: readonly string[]): Promise<void> {
246
+ for (const key of keys) await this.discard(key)
247
+ }
248
+
249
+ private async discard(key: string): Promise<void> {
250
+ await this.deps.files.delete(key)
251
+ await this.deps.avatars.forgetKeys([key])
252
+ }
253
+ }
package/src/limits.ts ADDED
@@ -0,0 +1,3 @@
1
+ export const AVATAR_BOX = { width: 200, height: 200 } as const
2
+
3
+ export const AVATAR_MAX_BYTES = 2 * 1024 * 1024