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