]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/models/avatar/avatar.ts
Type toFormattedJSON
[github/Chocobozzz/PeerTube.git] / server / models / avatar / avatar.ts
CommitLineData
c5911fd3 1import { join } from 'path'
557b13ae 2import { AfterDestroy, AllowNull, Column, CreatedAt, Is, Model, Table, UpdatedAt } from 'sequelize-typescript'
c5911fd3 3import { Avatar } from '../../../shared/models/avatars/avatar.model'
557b13ae 4import { LAZY_STATIC_PATHS } from '../../initializers/constants'
8e0fd45e 5import { logger } from '../../helpers/logger'
62689b94 6import { remove } from 'fs-extra'
6dd9de95 7import { CONFIG } from '../../initializers/config'
557b13ae
C
8import { throwIfNotValid } from '../utils'
9import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
1ca9f7c3 10import { MAvatarFormattable } from '@server/typings/models'
2295ce6c 11
3fd3ab2d 12@Table({
557b13ae
C
13 tableName: 'avatar',
14 indexes: [
15 {
16 fields: [ 'filename' ],
17 unique: true
18 }
19 ]
3fd3ab2d
C
20})
21export class AvatarModel extends Model<AvatarModel> {
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}