1 import * as Sequelize from 'sequelize'
14 } from 'sequelize-typescript'
15 import { throwIfNotValid } from '../utils'
16 import { VideoModel } from './video'
17 import { isVideoCaptionLanguageValid } from '../../helpers/custom-validators/video-captions'
18 import { VideoCaption } from '../../../shared/models/videos/video-caption.model'
19 import { CONFIG, STATIC_PATHS, VIDEO_LANGUAGES } from '../../initializers'
20 import { join } from 'path'
21 import { logger } from '../../helpers/logger'
22 import { unlinkPromise } from '../../helpers/core-utils'
24 export enum ScopeNames {
25 WITH_VIDEO_UUID_AND_REMOTE = 'WITH_VIDEO_UUID_AND_REMOTE'
29 [ScopeNames.WITH_VIDEO_UUID_AND_REMOTE]: {
32 attributes: [ 'uuid', 'remote' ],
33 model: () => VideoModel.unscoped(),
41 tableName: 'videoCaption',
47 fields: [ 'videoId', 'language' ],
52 export class VideoCaptionModel extends Model<VideoCaptionModel> {
60 @Is('VideoCaptionLanguage', value => throwIfNotValid(value, isVideoCaptionLanguageValid, 'language'))
64 @ForeignKey(() => VideoModel)
68 @BelongsTo(() => VideoModel, {
77 static async removeFiles (instance: VideoCaptionModel) {
78 if (!instance.Video) {
79 instance.Video = await instance.$get('Video') as VideoModel
82 if (instance.isOwned()) {
83 logger.info('Removing captions %s of video %s.', instance.Video.uuid, instance.language)
86 await instance.removeCaptionFile()
88 logger.error('Cannot remove caption file of video %s.', instance.Video.uuid)
95 static loadByVideoIdAndLanguage (videoId: string | number, language: string) {
96 const videoInclude = {
97 model: VideoModel.unscoped(),
98 attributes: [ 'id', 'remote', 'uuid' ],
102 if (typeof videoId === 'string') videoInclude.where['uuid'] = videoId
103 else videoInclude.where['id'] = videoId
114 return VideoCaptionModel.findOne(query)
117 static insertOrReplaceLanguage (videoId: number, language: string, transaction: Sequelize.Transaction) {
123 return VideoCaptionModel.upsert(values, { transaction })
126 static listVideoCaptions (videoId: number) {
128 order: [ [ 'language', 'ASC' ] ],
134 return VideoCaptionModel.scope(ScopeNames.WITH_VIDEO_UUID_AND_REMOTE).findAll(query)
137 static getLanguageLabel (language: string) {
138 return VIDEO_LANGUAGES[language] || 'Unknown'
141 static deleteAllCaptionsOfRemoteVideo (videoId: number, transaction: Sequelize.Transaction) {
149 return VideoCaptionModel.destroy(query)
153 return this.Video.remote === false
156 toFormattedJSON (): VideoCaption {
160 label: VideoCaptionModel.getLanguageLabel(this.language)
162 captionPath: this.getCaptionStaticPath()
166 getCaptionStaticPath () {
167 return join(STATIC_PATHS.VIDEO_CAPTIONS, this.getCaptionName())
171 return `${this.Video.uuid}-${this.language}.vtt`
174 removeCaptionFile () {
175 return unlinkPromise(CONFIG.STORAGE.CAPTIONS_DIR + this.getCaptionName())