1 import { join } from 'path'
14 } from 'sequelize-typescript'
15 import { CONSTRAINTS_FIELDS, LAZY_STATIC_PATHS, STATIC_PATHS, WEBSERVER } from '../../initializers/constants'
16 import { logger } from '../../helpers/logger'
17 import { remove } from 'fs-extra'
18 import { CONFIG } from '../../initializers/config'
19 import { VideoModel } from './video'
20 import { VideoPlaylistModel } from './video-playlist'
21 import { ThumbnailType } from '../../../shared/models/videos/thumbnail.type'
22 import { MVideoAccountLight } from '@server/types/models'
23 import { buildRemoteVideoBaseUrl } from '@server/helpers/activitypub'
26 tableName: 'thumbnail',
32 fields: [ 'videoPlaylistId' ],
37 export class ThumbnailModel extends Model<ThumbnailModel> {
58 @Column(DataType.STRING(CONSTRAINTS_FIELDS.COMMONS.URL.max))
63 automaticallyGenerated: boolean
65 @ForeignKey(() => VideoModel)
69 @BelongsTo(() => VideoModel, {
77 @ForeignKey(() => VideoPlaylistModel)
79 videoPlaylistId: number
81 @BelongsTo(() => VideoPlaylistModel, {
87 VideoPlaylist: VideoPlaylistModel
95 private static readonly types: { [ id in ThumbnailType ]: { label: string, directory: string, staticPath: string } } = {
96 [ThumbnailType.MINIATURE]: {
98 directory: CONFIG.STORAGE.THUMBNAILS_DIR,
99 staticPath: STATIC_PATHS.THUMBNAILS
101 [ThumbnailType.PREVIEW]: {
103 directory: CONFIG.STORAGE.PREVIEWS_DIR,
104 staticPath: LAZY_STATIC_PATHS.PREVIEWS
109 static removeFiles (instance: ThumbnailModel) {
110 logger.info('Removing %s file %s.', ThumbnailModel.types[instance.type].label, instance.filename)
112 // Don't block the transaction
113 instance.removeThumbnail()
114 .catch(err => logger.error('Cannot remove thumbnail file %s.', instance.filename, err))
117 static loadByName (filename: string) {
124 return ThumbnailModel.findOne(query)
127 static generateDefaultPreviewName (videoUUID: string) {
128 return videoUUID + '.jpg'
131 getFileUrl (video: MVideoAccountLight) {
132 const staticPath = ThumbnailModel.types[this.type].staticPath + this.filename
134 if (video.isOwned()) return WEBSERVER.URL + staticPath
135 if (this.fileUrl) return this.fileUrl
137 // Fallback if we don't have a file URL
138 return buildRemoteVideoBaseUrl(video, staticPath)
142 const directory = ThumbnailModel.types[this.type].directory
143 return join(directory, this.filename)
147 return remove(this.getPath())