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) {
79 if (instance.isOwned()) {
80 if (!instance.Video) {
81 instance.Video = await instance.$get('Video') as VideoModel
84 logger.debug('Removing captions %s of video %s.', instance.Video.uuid, instance.language)
85 return instance.removeCaptionFile()
91 static loadByVideoIdAndLanguage (videoId: string | number, language: string) {
92 const videoInclude = {
93 model: VideoModel.unscoped(),
94 attributes: [ 'id', 'remote', 'uuid' ],
98 if (typeof videoId === 'string') videoInclude.where['uuid'] = videoId
99 else videoInclude.where['id'] = videoId
110 return VideoCaptionModel.findOne(query)
113 static insertOrReplaceLanguage (videoId: number, language: string, transaction: Sequelize.Transaction) {
119 return VideoCaptionModel.upsert(values, { transaction })
122 static listVideoCaptions (videoId: number) {
124 order: [ [ 'language', 'ASC' ] ],
130 return VideoCaptionModel.scope(ScopeNames.WITH_VIDEO_UUID_AND_REMOTE).findAll(query)
133 static getLanguageLabel (language: string) {
134 return VIDEO_LANGUAGES[language] || 'Unknown'
137 static deleteAllCaptionsOfRemoteVideo (videoId: number, transaction: Sequelize.Transaction) {
145 return VideoCaptionModel.destroy(query)
149 return this.Video.remote === false
152 toFormattedJSON (): VideoCaption {
156 label: VideoCaptionModel.getLanguageLabel(this.language)
158 captionPath: this.getCaptionStaticPath()
162 getCaptionStaticPath () {
163 return join(STATIC_PATHS.VIDEO_CAPTIONS, this.getCaptionName())
167 return `${this.Video.uuid}-${this.language}.vtt`
170 removeCaptionFile () {
171 return unlinkPromise(CONFIG.STORAGE.CAPTIONS_DIR + this.getCaptionName())