1 import { remove } from 'fs-extra'
2 import memoizee from 'memoizee'
3 import { join } from 'path'
4 import { FindOptions, Op, Transaction } from 'sequelize'
20 } from 'sequelize-typescript'
21 import { Where } from 'sequelize/types/utils'
22 import validator from 'validator'
23 import { buildRemoteVideoBaseUrl } from '@server/helpers/activitypub'
24 import { logger } from '@server/helpers/logger'
25 import { extractVideo } from '@server/helpers/video'
26 import { getHLSPublicFileUrl, getWebTorrentPublicFileUrl } from '@server/lib/object-storage'
27 import { getFSTorrentFilePath } from '@server/lib/paths'
28 import { isStreamingPlaylist, MStreamingPlaylistVideo, MVideo, MVideoWithHost } from '@server/types/models'
29 import { VideoResolution, VideoStorage } from '@shared/models'
30 import { AttributesOnly } from '@shared/typescript-utils'
32 isVideoFileExtnameValid,
33 isVideoFileInfoHashValid,
34 isVideoFileResolutionValid,
36 isVideoFPSResolutionValid
37 } from '../../helpers/custom-validators/videos'
42 STATIC_DOWNLOAD_PATHS,
45 } from '../../initializers/constants'
46 import { MVideoFile, MVideoFileStreamingPlaylistVideo, MVideoFileVideo } from '../../types/models/video/video-file'
47 import { VideoRedundancyModel } from '../redundancy/video-redundancy'
48 import { doesExist } from '../shared'
49 import { parseAggregateResult, throwIfNotValid } from '../utils'
50 import { VideoModel } from './video'
51 import { VideoStreamingPlaylistModel } from './video-streaming-playlist'
53 export enum ScopeNames {
54 WITH_VIDEO = 'WITH_VIDEO',
55 WITH_METADATA = 'WITH_METADATA',
56 WITH_VIDEO_OR_PLAYLIST = 'WITH_VIDEO_OR_PLAYLIST'
59 @DefaultScope(() => ({
61 exclude: [ 'metadata' ]
65 [ScopeNames.WITH_VIDEO]: {
68 model: VideoModel.unscoped(),
73 [ScopeNames.WITH_VIDEO_OR_PLAYLIST]: (options: { whereVideo?: Where } = {}) => {
77 model: VideoModel.unscoped(),
79 where: options.whereVideo
82 model: VideoStreamingPlaylistModel.unscoped(),
86 model: VideoModel.unscoped(),
88 where: options.whereVideo
95 [ScopeNames.WITH_METADATA]: {
97 include: [ 'metadata' ]
102 tableName: 'videoFile',
105 fields: [ 'videoId' ],
113 fields: [ 'videoStreamingPlaylistId' ],
115 videoStreamingPlaylistId: {
122 fields: [ 'infoHash' ]
126 fields: [ 'torrentFilename' ],
131 fields: [ 'filename' ],
136 fields: [ 'videoId', 'resolution', 'fps' ],
145 fields: [ 'videoStreamingPlaylistId', 'resolution', 'fps' ],
148 videoStreamingPlaylistId: {
155 export class VideoFileModel extends Model<Partial<AttributesOnly<VideoFileModel>>> {
163 @Is('VideoFileResolution', value => throwIfNotValid(value, isVideoFileResolutionValid, 'resolution'))
168 @Is('VideoFileSize', value => throwIfNotValid(value, isVideoFileSizeValid, 'size'))
169 @Column(DataType.BIGINT)
173 @Is('VideoFileExtname', value => throwIfNotValid(value, isVideoFileExtnameValid, 'extname'))
178 @Is('VideoFileInfohash', value => throwIfNotValid(value, isVideoFileInfoHashValid, 'info hash', true))
184 @Is('VideoFileFPS', value => throwIfNotValid(value, isVideoFPSResolutionValid, 'fps'))
189 @Column(DataType.JSONB)
196 // Could be null for remote files
201 // Could be null for live files
206 // Could be null for remote files
211 // Could be null for live files
214 torrentFilename: string
216 @ForeignKey(() => VideoModel)
221 @Default(VideoStorage.FILE_SYSTEM)
223 storage: VideoStorage
225 @BelongsTo(() => VideoModel, {
233 @ForeignKey(() => VideoStreamingPlaylistModel)
235 videoStreamingPlaylistId: number
237 @BelongsTo(() => VideoStreamingPlaylistModel, {
243 VideoStreamingPlaylist: VideoStreamingPlaylistModel
245 @HasMany(() => VideoRedundancyModel, {
252 RedundancyVideos: VideoRedundancyModel[]
254 static doesInfohashExistCached = memoizee(VideoFileModel.doesInfohashExist, {
256 max: MEMOIZE_LENGTH.INFO_HASH_EXISTS,
257 maxAge: MEMOIZE_TTL.INFO_HASH_EXISTS
260 static doesInfohashExist (infoHash: string) {
261 const query = 'SELECT 1 FROM "videoFile" WHERE "infoHash" = $infoHash LIMIT 1'
263 return doesExist(query, { infoHash })
266 static async doesVideoExistForVideoFile (id: number, videoIdOrUUID: number | string) {
267 const videoFile = await VideoFileModel.loadWithVideoOrPlaylist(id, videoIdOrUUID)
272 static async doesOwnedTorrentFileExist (filename: string) {
273 const query = 'SELECT 1 FROM "videoFile" ' +
274 'LEFT JOIN "video" "webtorrent" ON "webtorrent"."id" = "videoFile"."videoId" AND "webtorrent"."remote" IS FALSE ' +
275 'LEFT JOIN "videoStreamingPlaylist" ON "videoStreamingPlaylist"."id" = "videoFile"."videoStreamingPlaylistId" ' +
276 'LEFT JOIN "video" "hlsVideo" ON "hlsVideo"."id" = "videoStreamingPlaylist"."videoId" AND "hlsVideo"."remote" IS FALSE ' +
277 'WHERE "torrentFilename" = $filename AND ("hlsVideo"."id" IS NOT NULL OR "webtorrent"."id" IS NOT NULL) LIMIT 1'
279 return doesExist(query, { filename })
282 static async doesOwnedWebTorrentVideoFileExist (filename: string) {
283 const query = 'SELECT 1 FROM "videoFile" INNER JOIN "video" ON "video"."id" = "videoFile"."videoId" AND "video"."remote" IS FALSE ' +
284 `WHERE "filename" = $filename AND "storage" = ${VideoStorage.FILE_SYSTEM} LIMIT 1`
286 return doesExist(query, { filename })
289 static loadByFilename (filename: string) {
296 return VideoFileModel.findOne(query)
299 static loadWithVideoOrPlaylistByTorrentFilename (filename: string) {
302 torrentFilename: filename
306 return VideoFileModel.scope(ScopeNames.WITH_VIDEO_OR_PLAYLIST).findOne(query)
309 static loadWithMetadata (id: number) {
310 return VideoFileModel.scope(ScopeNames.WITH_METADATA).findByPk(id)
313 static loadWithVideo (id: number) {
314 return VideoFileModel.scope(ScopeNames.WITH_VIDEO).findByPk(id)
317 static loadWithVideoOrPlaylist (id: number, videoIdOrUUID: number | string) {
318 const whereVideo = validator.isUUID(videoIdOrUUID + '')
319 ? { uuid: videoIdOrUUID }
320 : { id: videoIdOrUUID }
328 return VideoFileModel.scope({ method: [ ScopeNames.WITH_VIDEO_OR_PLAYLIST, whereVideo ] })
331 // We used `required: false` so check we have at least a video or a streaming playlist
332 if (!file.Video && !file.VideoStreamingPlaylist) return null
338 static listByStreamingPlaylist (streamingPlaylistId: number, transaction: Transaction) {
342 model: VideoModel.unscoped(),
346 model: VideoStreamingPlaylistModel.unscoped(),
349 id: streamingPlaylistId
358 return VideoFileModel.findAll(query)
362 const webtorrentFilesQuery: FindOptions = {
367 model: VideoModel.unscoped(),
375 const hlsFilesQuery: FindOptions = {
380 model: VideoStreamingPlaylistModel.unscoped(),
384 model: VideoModel.unscoped(),
396 VideoFileModel.aggregate('size', 'SUM', webtorrentFilesQuery),
397 VideoFileModel.aggregate('size', 'SUM', hlsFilesQuery)
398 ]).then(([ webtorrentResult, hlsResult ]) => ({
399 totalLocalVideoFilesSize: parseAggregateResult(webtorrentResult) + parseAggregateResult(hlsResult)
403 // Redefine upsert because sequelize does not use an appropriate where clause in the update query with 2 unique indexes
404 static async customUpsert (
405 videoFile: MVideoFile,
406 mode: 'streaming-playlist' | 'video',
407 transaction: Transaction
411 resolution: videoFile.resolution
414 if (mode === 'streaming-playlist') Object.assign(baseWhere, { videoStreamingPlaylistId: videoFile.videoStreamingPlaylistId })
415 else Object.assign(baseWhere, { videoId: videoFile.videoId })
417 const element = await VideoFileModel.findOne({ where: baseWhere, transaction })
418 if (!element) return videoFile.save({ transaction })
420 for (const k of Object.keys(videoFile.toJSON())) {
421 element[k] = videoFile[k]
424 return element.save({ transaction })
427 static removeHLSFilesOfVideoId (videoStreamingPlaylistId: number) {
429 where: { videoStreamingPlaylistId }
432 return VideoFileModel.destroy(options)
436 return this.infoHash && this.torrentFilename
439 getVideoOrStreamingPlaylist (this: MVideoFileVideo | MVideoFileStreamingPlaylistVideo): MVideo | MStreamingPlaylistVideo {
440 if (this.videoId) return (this as MVideoFileVideo).Video
442 return (this as MVideoFileStreamingPlaylistVideo).VideoStreamingPlaylist
445 getVideo (this: MVideoFileVideo | MVideoFileStreamingPlaylistVideo): MVideo {
446 return extractVideo(this.getVideoOrStreamingPlaylist())
450 return this.resolution === VideoResolution.H_NOVIDEO
454 return this.size === -1
458 return !!this.videoStreamingPlaylistId
461 getObjectStorageUrl () {
463 return getHLSPublicFileUrl(this.fileUrl)
466 return getWebTorrentPublicFileUrl(this.fileUrl)
469 getFileUrl (video: MVideo) {
470 if (this.storage === VideoStorage.OBJECT_STORAGE) {
471 return this.getObjectStorageUrl()
474 if (!this.Video) this.Video = video as VideoModel
475 if (video.isOwned()) return WEBSERVER.URL + this.getFileStaticPath(video)
480 getFileStaticPath (video: MVideo) {
481 if (this.isHLS()) return join(STATIC_PATHS.STREAMING_PLAYLISTS.HLS, video.uuid, this.filename)
483 return join(STATIC_PATHS.WEBSEED, this.filename)
486 getFileDownloadUrl (video: MVideoWithHost) {
487 const path = this.isHLS()
488 ? join(STATIC_DOWNLOAD_PATHS.HLS_VIDEOS, `${video.uuid}-${this.resolution}-fragmented${this.extname}`)
489 : join(STATIC_DOWNLOAD_PATHS.VIDEOS, `${video.uuid}-${this.resolution}${this.extname}`)
491 if (video.isOwned()) return WEBSERVER.URL + path
493 // FIXME: don't guess remote URL
494 return buildRemoteVideoBaseUrl(video, path)
497 getRemoteTorrentUrl (video: MVideo) {
498 if (video.isOwned()) throw new Error(`Video ${video.url} is not a remote video`)
500 return this.torrentUrl
503 // We proxify torrent requests so use a local URL
505 if (!this.torrentFilename) return null
507 return WEBSERVER.URL + this.getTorrentStaticPath()
510 getTorrentStaticPath () {
511 if (!this.torrentFilename) return null
513 return join(LAZY_STATIC_PATHS.TORRENTS, this.torrentFilename)
516 getTorrentDownloadUrl () {
517 if (!this.torrentFilename) return null
519 return WEBSERVER.URL + join(STATIC_DOWNLOAD_PATHS.TORRENTS, this.torrentFilename)
523 if (!this.torrentFilename) return null
525 const torrentPath = getFSTorrentFilePath(this)
526 return remove(torrentPath)
527 .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err }))
530 hasSameUniqueKeysThan (other: MVideoFile) {
531 return this.fps === other.fps &&
532 this.resolution === other.resolution &&
534 (this.videoId !== null && this.videoId === other.videoId) ||
535 (this.videoStreamingPlaylistId !== null && this.videoStreamingPlaylistId === other.videoStreamingPlaylistId)
539 withVideoOrPlaylist (videoOrPlaylist: MVideo | MStreamingPlaylistVideo) {
540 if (isStreamingPlaylist(videoOrPlaylist)) return Object.assign(this, { VideoStreamingPlaylist: videoOrPlaylist })
542 return Object.assign(this, { Video: videoOrPlaylist })