]>
Commit | Line | Data |
---|---|---|
c5911fd3 | 1 | import { join } from 'path' |
557b13ae | 2 | import { AfterDestroy, AllowNull, Column, CreatedAt, Is, Model, Table, UpdatedAt } from 'sequelize-typescript' |
c5911fd3 | 3 | import { Avatar } from '../../../shared/models/avatars/avatar.model' |
557b13ae | 4 | import { LAZY_STATIC_PATHS } from '../../initializers/constants' |
8e0fd45e | 5 | import { logger } from '../../helpers/logger' |
62689b94 | 6 | import { remove } from 'fs-extra' |
6dd9de95 | 7 | import { CONFIG } from '../../initializers/config' |
557b13ae C |
8 | import { throwIfNotValid } from '../utils' |
9 | import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc' | |
26d6bf65 | 10 | import { MAvatarFormattable } from '@server/types/models' |
2295ce6c | 11 | |
3fd3ab2d | 12 | @Table({ |
557b13ae C |
13 | tableName: 'avatar', |
14 | indexes: [ | |
15 | { | |
16 | fields: [ 'filename' ], | |
17 | unique: true | |
18 | } | |
19 | ] | |
3fd3ab2d | 20 | }) |
b49f22d8 | 21 | export class AvatarModel extends Model { |
2295ce6c | 22 | |
3fd3ab2d C |
23 | @AllowNull(false) |
24 | @Column | |
25 | filename: string | |
2295ce6c | 26 | |
557b13ae | 27 | @AllowNull(true) |
5bb2eb56 | 28 | @Is('AvatarFileUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'fileUrl', true)) |
557b13ae C |
29 | @Column |
30 | fileUrl: string | |
31 | ||
32 | @AllowNull(false) | |
33 | @Column | |
34 | onDisk: boolean | |
35 | ||
3fd3ab2d C |
36 | @CreatedAt |
37 | createdAt: Date | |
2295ce6c | 38 | |
3fd3ab2d C |
39 | @UpdatedAt |
40 | updatedAt: Date | |
c5911fd3 C |
41 | |
42 | @AfterDestroy | |
43 | static removeFilesAndSendDelete (instance: AvatarModel) { | |
8e0fd45e | 44 | logger.info('Removing avatar file %s.', instance.filename) |
ecf3f060 C |
45 | |
46 | // Don't block the transaction | |
47 | instance.removeAvatar() | |
48 | .catch(err => logger.error('Cannot remove avatar file %s.', instance.filename, err)) | |
c5911fd3 C |
49 | } |
50 | ||
557b13ae C |
51 | static loadByName (filename: string) { |
52 | const query = { | |
53 | where: { | |
54 | filename | |
55 | } | |
56 | } | |
57 | ||
58 | return AvatarModel.findOne(query) | |
59 | } | |
60 | ||
1ca9f7c3 | 61 | toFormattedJSON (this: MAvatarFormattable): Avatar { |
c5911fd3 | 62 | return { |
557b13ae | 63 | path: this.getStaticPath(), |
c5911fd3 C |
64 | createdAt: this.createdAt, |
65 | updatedAt: this.updatedAt | |
66 | } | |
67 | } | |
68 | ||
557b13ae C |
69 | getStaticPath () { |
70 | return join(LAZY_STATIC_PATHS.AVATARS, this.filename) | |
71 | } | |
72 | ||
73 | getPath () { | |
74 | return join(CONFIG.STORAGE.AVATARS_DIR, this.filename) | |
c5911fd3 C |
75 | } |
76 | ||
77 | removeAvatar () { | |
78 | const avatarPath = join(CONFIG.STORAGE.AVATARS_DIR, this.filename) | |
62689b94 | 79 | return remove(avatarPath) |
c5911fd3 | 80 | } |
2295ce6c | 81 | } |