]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/models/account/actor-image.ts
Update data in DB when regenerate thumbnails
[github/Chocobozzz/PeerTube.git] / server / models / account / actor-image.ts
1 import { remove } from 'fs-extra'
2 import { join } from 'path'
3 import { AfterDestroy, AllowNull, Column, CreatedAt, Is, Model, Table, UpdatedAt } from 'sequelize-typescript'
4 import { v4 as uuidv4 } from 'uuid'
5 import { MActorImageFormattable } from '@server/types/models'
6 import { ActorImageType } from '@shared/models'
7 import { ActorImage } from '../../../shared/models/actors/actor-image.model'
8 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
9 import { logger } from '../../helpers/logger'
10 import { CONFIG } from '../../initializers/config'
11 import { LAZY_STATIC_PATHS } from '../../initializers/constants'
12 import { throwIfNotValid } from '../utils'
13
14 @Table({
15 tableName: 'actorImage',
16 indexes: [
17 {
18 fields: [ 'filename' ],
19 unique: true
20 }
21 ]
22 })
23 export class ActorImageModel extends Model {
24
25 @AllowNull(false)
26 @Column
27 filename: string
28
29 @AllowNull(true)
30 @Is('ActorImageFileUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'fileUrl', true))
31 @Column
32 fileUrl: string
33
34 @AllowNull(false)
35 @Column
36 onDisk: boolean
37
38 @AllowNull(false)
39 @Column
40 type: ActorImageType
41
42 @CreatedAt
43 createdAt: Date
44
45 @UpdatedAt
46 updatedAt: Date
47
48 @AfterDestroy
49 static removeFilesAndSendDelete (instance: ActorImageModel) {
50 logger.info('Removing actor image file %s.', instance.filename)
51
52 // Don't block the transaction
53 instance.removeImage()
54 .catch(err => logger.error('Cannot remove actor image file %s.', instance.filename, err))
55 }
56
57 static generateFilename () {
58 return uuidv4() + '.jpg'
59 }
60
61 static loadByName (filename: string) {
62 const query = {
63 where: {
64 filename
65 }
66 }
67
68 return ActorImageModel.findOne(query)
69 }
70
71 toFormattedJSON (this: MActorImageFormattable): ActorImage {
72 return {
73 path: this.getStaticPath(),
74 createdAt: this.createdAt,
75 updatedAt: this.updatedAt
76 }
77 }
78
79 getStaticPath () {
80 if (this.type === ActorImageType.AVATAR) {
81 return join(LAZY_STATIC_PATHS.AVATARS, this.filename)
82 }
83
84 return join(LAZY_STATIC_PATHS.BANNERS, this.filename)
85 }
86
87 getPath () {
88 return join(CONFIG.STORAGE.ACTOR_IMAGES, this.filename)
89 }
90
91 removeImage () {
92 const imagePath = join(CONFIG.STORAGE.ACTOR_IMAGES, this.filename)
93 return remove(imagePath)
94 }
95 }