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