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/caption/video-caption.model'
19 import { STATIC_PATHS, VIDEO_LANGUAGES } from '../../initializers/constants'
20 import { join } from 'path'
21 import { logger } from '../../helpers/logger'
22 import { remove } from 'fs-extra'
23 import { CONFIG } from '../../initializers/config'
25 export enum ScopeNames {
26 WITH_VIDEO_UUID_AND_REMOTE = 'WITH_VIDEO_UUID_AND_REMOTE'
30 [ScopeNames.WITH_VIDEO_UUID_AND_REMOTE]: {
33 attributes: [ 'uuid', 'remote' ],
34 model: () => VideoModel.unscoped(),
42 tableName: 'videoCaption',
48 fields: [ 'videoId', 'language' ],
53 export class VideoCaptionModel extends Model<VideoCaptionModel> {
61 @Is('VideoCaptionLanguage', value => throwIfNotValid(value, isVideoCaptionLanguageValid, 'language'))
65 @ForeignKey(() => VideoModel)
69 @BelongsTo(() => VideoModel, {
78 static async removeFiles (instance: VideoCaptionModel) {
79 if (!instance.Video) {
80 instance.Video = await instance.$get('Video') as VideoModel
83 if (instance.isOwned()) {
84 logger.info('Removing captions %s of video %s.', instance.Video.uuid, instance.language)
87 await instance.removeCaptionFile()
89 logger.error('Cannot remove caption file of video %s.', instance.Video.uuid)
96 static loadByVideoIdAndLanguage (videoId: string | number, language: string) {
97 const videoInclude = {
98 model: VideoModel.unscoped(),
99 attributes: [ 'id', 'remote', 'uuid' ],
103 if (typeof videoId === 'string') videoInclude.where['uuid'] = videoId
104 else videoInclude.where['id'] = videoId
115 return VideoCaptionModel.findOne(query)
118 static insertOrReplaceLanguage (videoId: number, language: string, transaction: Sequelize.Transaction) {
124 return VideoCaptionModel.upsert<VideoCaptionModel>(values, { transaction, returning: true })
125 .then(([ caption ]) => caption)
128 static listVideoCaptions (videoId: number) {
130 order: [ [ 'language', 'ASC' ] ],
136 return VideoCaptionModel.scope(ScopeNames.WITH_VIDEO_UUID_AND_REMOTE).findAll(query)
139 static getLanguageLabel (language: string) {
140 return VIDEO_LANGUAGES[language] || 'Unknown'
143 static deleteAllCaptionsOfRemoteVideo (videoId: number, transaction: Sequelize.Transaction) {
151 return VideoCaptionModel.destroy(query)
155 return this.Video.remote === false
158 toFormattedJSON (): VideoCaption {
162 label: VideoCaptionModel.getLanguageLabel(this.language)
164 captionPath: this.getCaptionStaticPath()
168 getCaptionStaticPath () {
169 return join(STATIC_PATHS.VIDEO_CAPTIONS, this.getCaptionName())
173 return `${this.Video.uuid}-${this.language}.vtt`
176 removeCaptionFile () {
177 return remove(CONFIG.STORAGE.CAPTIONS_DIR + this.getCaptionName())