1 import { remove } from 'fs-extra'
2 import { join } from 'path'
15 } from 'sequelize-typescript'
16 import { buildRemoteVideoBaseUrl } from '@server/helpers/activitypub'
17 import { MThumbnailVideo, MVideoAccountLight } from '@server/types/models'
18 import { ThumbnailType } from '../../../shared/models/videos/thumbnail.type'
19 import { logger } from '../../helpers/logger'
20 import { CONFIG } from '../../initializers/config'
21 import { CONSTRAINTS_FIELDS, LAZY_STATIC_PATHS, STATIC_PATHS, WEBSERVER } from '../../initializers/constants'
22 import { VideoModel } from './video'
23 import { VideoPlaylistModel } from './video-playlist'
26 tableName: 'thumbnail',
32 fields: [ 'videoPlaylistId' ],
36 fields: [ 'filename', 'type' ],
41 export class ThumbnailModel extends Model {
62 @Column(DataType.STRING(CONSTRAINTS_FIELDS.COMMONS.URL.max))
67 automaticallyGenerated: boolean
69 @ForeignKey(() => VideoModel)
73 @BelongsTo(() => VideoModel, {
81 @ForeignKey(() => VideoPlaylistModel)
83 videoPlaylistId: number
85 @BelongsTo(() => VideoPlaylistModel, {
91 VideoPlaylist: VideoPlaylistModel
99 private static readonly types: { [ id in ThumbnailType ]: { label: string, directory: string, staticPath: string } } = {
100 [ThumbnailType.MINIATURE]: {
102 directory: CONFIG.STORAGE.THUMBNAILS_DIR,
103 staticPath: STATIC_PATHS.THUMBNAILS
105 [ThumbnailType.PREVIEW]: {
107 directory: CONFIG.STORAGE.PREVIEWS_DIR,
108 staticPath: LAZY_STATIC_PATHS.PREVIEWS
113 static removeFiles (instance: ThumbnailModel) {
114 logger.info('Removing %s file %s.', ThumbnailModel.types[instance.type].label, instance.filename)
116 // Don't block the transaction
117 instance.removeThumbnail()
118 .catch(err => logger.error('Cannot remove thumbnail file %s.', instance.filename, err))
121 static loadWithVideoByName (filename: string, thumbnailType: ThumbnailType): Promise<MThumbnailVideo> {
129 model: VideoModel.unscoped(),
135 return ThumbnailModel.findOne(query)
138 getFileUrl (video: MVideoAccountLight) {
139 const staticPath = ThumbnailModel.types[this.type].staticPath + this.filename
141 if (video.isOwned()) return WEBSERVER.URL + staticPath
142 if (this.fileUrl) return this.fileUrl
144 // Fallback if we don't have a file URL
145 return buildRemoteVideoBaseUrl(video, staticPath)
149 const directory = ThumbnailModel.types[this.type].directory
150 return join(directory, this.filename)
154 return remove(this.getPath())