PeerTube/server/models/avatar/avatar.ts

82 lines
1.9 KiB
TypeScript
Raw Normal View History

2017-12-29 19:10:13 +01:00
import { join } from 'path'
2019-08-09 11:32:40 +02:00
import { AfterDestroy, AllowNull, Column, CreatedAt, Is, Model, Table, UpdatedAt } from 'sequelize-typescript'
2017-12-29 19:10:13 +01:00
import { Avatar } from '../../../shared/models/avatars/avatar.model'
2019-08-09 11:32:40 +02:00
import { LAZY_STATIC_PATHS } from '../../initializers/constants'
2018-07-30 17:02:40 +02:00
import { logger } from '../../helpers/logger'
2018-08-27 16:23:34 +02:00
import { remove } from 'fs-extra'
2019-04-11 11:33:44 +02:00
import { CONFIG } from '../../initializers/config'
2019-08-09 11:32:40 +02:00
import { throwIfNotValid } from '../utils'
import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
2020-06-18 10:45:25 +02:00
import { MAvatarFormattable } from '@server/types/models'
2017-12-04 10:34:40 +01:00
2017-12-12 17:53:50 +01:00
@Table({
2019-08-09 11:32:40 +02:00
tableName: 'avatar',
indexes: [
{
fields: [ 'filename' ],
unique: true
}
]
2017-12-12 17:53:50 +01:00
})
export class AvatarModel extends Model<AvatarModel> {
2017-12-04 10:34:40 +01:00
2017-12-12 17:53:50 +01:00
@AllowNull(false)
@Column
filename: string
2017-12-04 10:34:40 +01:00
2019-08-09 11:32:40 +02:00
@AllowNull(true)
2019-08-09 11:49:37 +02:00
@Is('AvatarFileUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'fileUrl', true))
2019-08-09 11:32:40 +02:00
@Column
fileUrl: string
@AllowNull(false)
@Column
onDisk: boolean
2017-12-12 17:53:50 +01:00
@CreatedAt
createdAt: Date
2017-12-04 10:34:40 +01:00
2017-12-12 17:53:50 +01:00
@UpdatedAt
updatedAt: Date
2017-12-29 19:10:13 +01:00
@AfterDestroy
static removeFilesAndSendDelete (instance: AvatarModel) {
2018-07-30 17:02:40 +02:00
logger.info('Removing avatar file %s.', instance.filename)
2018-10-08 10:37:08 +02:00
// Don't block the transaction
instance.removeAvatar()
.catch(err => logger.error('Cannot remove avatar file %s.', instance.filename, err))
2017-12-29 19:10:13 +01:00
}
2019-08-09 11:32:40 +02:00
static loadByName (filename: string) {
const query = {
where: {
filename
}
}
return AvatarModel.findOne(query)
}
2019-08-20 19:05:31 +02:00
toFormattedJSON (this: MAvatarFormattable): Avatar {
2017-12-29 19:10:13 +01:00
return {
2019-08-09 11:32:40 +02:00
path: this.getStaticPath(),
2017-12-29 19:10:13 +01:00
createdAt: this.createdAt,
updatedAt: this.updatedAt
}
}
2019-08-09 11:32:40 +02:00
getStaticPath () {
return join(LAZY_STATIC_PATHS.AVATARS, this.filename)
}
getPath () {
return join(CONFIG.STORAGE.AVATARS_DIR, this.filename)
2017-12-29 19:10:13 +01:00
}
removeAvatar () {
const avatarPath = join(CONFIG.STORAGE.AVATARS_DIR, this.filename)
2018-08-27 16:23:34 +02:00
return remove(avatarPath)
2017-12-29 19:10:13 +01:00
}
2017-12-04 10:34:40 +01:00
}