aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/models/avatar/avatar.ts
blob: 950e4b181464626a68b8058e8b4f28a9d7db94ee (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import { join } from 'path'
import { AfterDestroy, AllowNull, Column, CreatedAt, Is, Model, Table, UpdatedAt } from 'sequelize-typescript'
import { Avatar } from '../../../shared/models/avatars/avatar.model'
import { LAZY_STATIC_PATHS } from '../../initializers/constants'
import { logger } from '../../helpers/logger'
import { remove } from 'fs-extra'
import { CONFIG } from '../../initializers/config'
import { throwIfNotValid } from '../utils'
import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
import { MAvatarFormattable } from '@server/typings/models'

@Table({
  tableName: 'avatar',
  indexes: [
    {
      fields: [ 'filename' ],
      unique: true
    }
  ]
})
export class AvatarModel extends Model<AvatarModel> {

  @AllowNull(false)
  @Column
  filename: string

  @AllowNull(true)
  @Is('AvatarFileUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'fileUrl', true))
  @Column
  fileUrl: string

  @AllowNull(false)
  @Column
  onDisk: boolean

  @CreatedAt
  createdAt: Date

  @UpdatedAt
  updatedAt: Date

  @AfterDestroy
  static removeFilesAndSendDelete (instance: AvatarModel) {
    logger.info('Removing avatar file %s.', instance.filename)

    // Don't block the transaction
    instance.removeAvatar()
      .catch(err => logger.error('Cannot remove avatar file %s.', instance.filename, err))
  }

  static loadByName (filename: string) {
    const query = {
      where: {
        filename
      }
    }

    return AvatarModel.findOne(query)
  }

  toFormattedJSON (this: MAvatarFormattable): Avatar {
    return {
      path: this.getStaticPath(),
      createdAt: this.createdAt,
      updatedAt: this.updatedAt
    }
  }

  getStaticPath () {
    return join(LAZY_STATIC_PATHS.AVATARS, this.filename)
  }

  getPath () {
    return join(CONFIG.STORAGE.AVATARS_DIR, this.filename)
  }

  removeAvatar () {
    const avatarPath = join(CONFIG.STORAGE.AVATARS_DIR, this.filename)
    return remove(avatarPath)
  }
}