1 import { remove } from 'fs-extra'
2 import memoizee from 'memoizee'
3 import { join } from 'path'
4 import { FindOptions, Op, Transaction, WhereOptions } from 'sequelize'
20 } from 'sequelize-typescript'
21 import validator from 'validator'
22 import { logger } from '@server/helpers/logger'
23 import { extractVideo } from '@server/helpers/video'
24 import { buildRemoteVideoBaseUrl } from '@server/lib/activitypub/url'
25 import { getHLSPublicFileUrl, getWebTorrentPublicFileUrl } from '@server/lib/object-storage'
26 import { getFSTorrentFilePath } from '@server/lib/paths'
27 import { isStreamingPlaylist, MStreamingPlaylistVideo, MVideo, MVideoWithHost } from '@server/types/models'
28 import { VideoResolution, VideoStorage } from '@shared/models'
29 import { AttributesOnly } from '@shared/typescript-utils'
31 isVideoFileExtnameValid,
32 isVideoFileInfoHashValid,
33 isVideoFileResolutionValid,
35 isVideoFPSResolutionValid
36 } from '../../helpers/custom-validators/videos'
41 STATIC_DOWNLOAD_PATHS,
44 } from '../../initializers/constants'
45 import { MVideoFile, MVideoFileStreamingPlaylistVideo, MVideoFileVideo } from '../../types/models/video/video-file'
46 import { VideoRedundancyModel } from '../redundancy/video-redundancy'
47 import { doesExist } from '../shared'
48 import { parseAggregateResult, throwIfNotValid } from '../utils'
49 import { VideoModel } from './video'
50 import { VideoStreamingPlaylistModel } from './video-streaming-playlist'
52 export enum ScopeNames {
53 WITH_VIDEO = 'WITH_VIDEO',
54 WITH_METADATA = 'WITH_METADATA',
55 WITH_VIDEO_OR_PLAYLIST = 'WITH_VIDEO_OR_PLAYLIST'
58 @DefaultScope(() => ({
60 exclude: [ 'metadata' ]
64 [ScopeNames.WITH_VIDEO]: {
67 model: VideoModel.unscoped(),
72 [ScopeNames.WITH_VIDEO_OR_PLAYLIST]: (options: { whereVideo?: WhereOptions } = {}) => {
76 model: VideoModel.unscoped(),
78 where: options.whereVideo
81 model: VideoStreamingPlaylistModel.unscoped(),
85 model: VideoModel.unscoped(),
87 where: options.whereVideo
94 [ScopeNames.WITH_METADATA]: {
96 include: [ 'metadata' ]
101 tableName: 'videoFile',
104 fields: [ 'videoId' ],
112 fields: [ 'videoStreamingPlaylistId' ],
114 videoStreamingPlaylistId: {
121 fields: [ 'infoHash' ]
125 fields: [ 'torrentFilename' ],
130 fields: [ 'filename' ],
135 fields: [ 'videoId', 'resolution', 'fps' ],
144 fields: [ 'videoStreamingPlaylistId', 'resolution', 'fps' ],
147 videoStreamingPlaylistId: {
154 export class VideoFileModel extends Model<Partial<AttributesOnly<VideoFileModel>>> {
162 @Is('VideoFileResolution', value => throwIfNotValid(value, isVideoFileResolutionValid, 'resolution'))
167 @Is('VideoFileSize', value => throwIfNotValid(value, isVideoFileSizeValid, 'size'))
168 @Column(DataType.BIGINT)
172 @Is('VideoFileExtname', value => throwIfNotValid(value, isVideoFileExtnameValid, 'extname'))
177 @Is('VideoFileInfohash', value => throwIfNotValid(value, isVideoFileInfoHashValid, 'info hash', true))
183 @Is('VideoFileFPS', value => throwIfNotValid(value, isVideoFPSResolutionValid, 'fps'))
188 @Column(DataType.JSONB)
195 // Could be null for remote files
200 // Could be null for live files
205 // Could be null for remote files
210 // Could be null for live files
213 torrentFilename: string
215 @ForeignKey(() => VideoModel)
220 @Default(VideoStorage.FILE_SYSTEM)
222 storage: VideoStorage
224 @BelongsTo(() => VideoModel, {
232 @ForeignKey(() => VideoStreamingPlaylistModel)
234 videoStreamingPlaylistId: number
236 @BelongsTo(() => VideoStreamingPlaylistModel, {
242 VideoStreamingPlaylist: VideoStreamingPlaylistModel
244 @HasMany(() => VideoRedundancyModel, {
251 RedundancyVideos: VideoRedundancyModel[]
253 static doesInfohashExistCached = memoizee(VideoFileModel.doesInfohashExist, {
255 max: MEMOIZE_LENGTH.INFO_HASH_EXISTS,
256 maxAge: MEMOIZE_TTL.INFO_HASH_EXISTS
259 static doesInfohashExist (infoHash: string) {
260 const query = 'SELECT 1 FROM "videoFile" WHERE "infoHash" = $infoHash LIMIT 1'
262 return doesExist(query, { infoHash })
265 static async doesVideoExistForVideoFile (id: number, videoIdOrUUID: number | string) {
266 const videoFile = await VideoFileModel.loadWithVideoOrPlaylist(id, videoIdOrUUID)
271 static async doesOwnedTorrentFileExist (filename: string) {
272 const query = 'SELECT 1 FROM "videoFile" ' +
273 'LEFT JOIN "video" "webtorrent" ON "webtorrent"."id" = "videoFile"."videoId" AND "webtorrent"."remote" IS FALSE ' +
274 'LEFT JOIN "videoStreamingPlaylist" ON "videoStreamingPlaylist"."id" = "videoFile"."videoStreamingPlaylistId" ' +
275 'LEFT JOIN "video" "hlsVideo" ON "hlsVideo"."id" = "videoStreamingPlaylist"."videoId" AND "hlsVideo"."remote" IS FALSE ' +
276 'WHERE "torrentFilename" = $filename AND ("hlsVideo"."id" IS NOT NULL OR "webtorrent"."id" IS NOT NULL) LIMIT 1'
278 return doesExist(query, { filename })
281 static async doesOwnedWebTorrentVideoFileExist (filename: string) {
282 const query = 'SELECT 1 FROM "videoFile" INNER JOIN "video" ON "video"."id" = "videoFile"."videoId" AND "video"."remote" IS FALSE ' +
283 `WHERE "filename" = $filename AND "storage" = ${VideoStorage.FILE_SYSTEM} LIMIT 1`
285 return doesExist(query, { filename })
288 static loadByFilename (filename: string) {
295 return VideoFileModel.findOne(query)
298 static loadWithVideoOrPlaylistByTorrentFilename (filename: string) {
301 torrentFilename: filename
305 return VideoFileModel.scope(ScopeNames.WITH_VIDEO_OR_PLAYLIST).findOne(query)
308 static loadWithMetadata (id: number) {
309 return VideoFileModel.scope(ScopeNames.WITH_METADATA).findByPk(id)
312 static loadWithVideo (id: number) {
313 return VideoFileModel.scope(ScopeNames.WITH_VIDEO).findByPk(id)
316 static loadWithVideoOrPlaylist (id: number, videoIdOrUUID: number | string) {
317 const whereVideo = validator.isUUID(videoIdOrUUID + '')
318 ? { uuid: videoIdOrUUID }
319 : { id: videoIdOrUUID }
327 return VideoFileModel.scope({ method: [ ScopeNames.WITH_VIDEO_OR_PLAYLIST, whereVideo ] })
330 // We used `required: false` so check we have at least a video or a streaming playlist
331 if (!file.Video && !file.VideoStreamingPlaylist) return null
337 static listByStreamingPlaylist (streamingPlaylistId: number, transaction: Transaction) {
341 model: VideoModel.unscoped(),
345 model: VideoStreamingPlaylistModel.unscoped(),
348 id: streamingPlaylistId
357 return VideoFileModel.findAll(query)
361 const webtorrentFilesQuery: FindOptions = {
366 model: VideoModel.unscoped(),
374 const hlsFilesQuery: FindOptions = {
379 model: VideoStreamingPlaylistModel.unscoped(),
383 model: VideoModel.unscoped(),
395 VideoFileModel.aggregate('size', 'SUM', webtorrentFilesQuery),
396 VideoFileModel.aggregate('size', 'SUM', hlsFilesQuery)
397 ]).then(([ webtorrentResult, hlsResult ]) => ({
398 totalLocalVideoFilesSize: parseAggregateResult(webtorrentResult) + parseAggregateResult(hlsResult)
402 // Redefine upsert because sequelize does not use an appropriate where clause in the update query with 2 unique indexes
403 static async customUpsert (
404 videoFile: MVideoFile,
405 mode: 'streaming-playlist' | 'video',
406 transaction: Transaction
410 resolution: videoFile.resolution,
414 const element = mode === 'streaming-playlist'
415 ? await VideoFileModel.loadHLSFile({ ...baseFind, playlistId: videoFile.videoStreamingPlaylistId })
416 : await VideoFileModel.loadWebTorrentFile({ ...baseFind, videoId: videoFile.videoId })
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 async loadWebTorrentFile (options: {
431 transaction?: Transaction
435 resolution: options.resolution,
436 videoId: options.videoId
439 return VideoFileModel.findOne({ where, transaction: options.transaction })
442 static async loadHLSFile (options: {
446 transaction?: Transaction
450 resolution: options.resolution,
451 videoStreamingPlaylistId: options.playlistId
454 return VideoFileModel.findOne({ where, transaction: options.transaction })
457 static removeHLSFilesOfVideoId (videoStreamingPlaylistId: number) {
459 where: { videoStreamingPlaylistId }
462 return VideoFileModel.destroy(options)
466 return this.infoHash && this.torrentFilename
469 getVideoOrStreamingPlaylist (this: MVideoFileVideo | MVideoFileStreamingPlaylistVideo): MVideo | MStreamingPlaylistVideo {
470 if (this.videoId) return (this as MVideoFileVideo).Video
472 return (this as MVideoFileStreamingPlaylistVideo).VideoStreamingPlaylist
475 getVideo (this: MVideoFileVideo | MVideoFileStreamingPlaylistVideo): MVideo {
476 return extractVideo(this.getVideoOrStreamingPlaylist())
480 return this.resolution === VideoResolution.H_NOVIDEO
484 return this.size === -1
488 return !!this.videoStreamingPlaylistId
491 getObjectStorageUrl () {
493 return getHLSPublicFileUrl(this.fileUrl)
496 return getWebTorrentPublicFileUrl(this.fileUrl)
499 getFileUrl (video: MVideo) {
500 if (this.storage === VideoStorage.OBJECT_STORAGE) {
501 return this.getObjectStorageUrl()
504 if (!this.Video) this.Video = video as VideoModel
505 if (video.isOwned()) return WEBSERVER.URL + this.getFileStaticPath(video)
510 getFileStaticPath (video: MVideo) {
511 if (this.isHLS()) return join(STATIC_PATHS.STREAMING_PLAYLISTS.HLS, video.uuid, this.filename)
513 return join(STATIC_PATHS.WEBSEED, this.filename)
516 getFileDownloadUrl (video: MVideoWithHost) {
517 const path = this.isHLS()
518 ? join(STATIC_DOWNLOAD_PATHS.HLS_VIDEOS, `${video.uuid}-${this.resolution}-fragmented${this.extname}`)
519 : join(STATIC_DOWNLOAD_PATHS.VIDEOS, `${video.uuid}-${this.resolution}${this.extname}`)
521 if (video.isOwned()) return WEBSERVER.URL + path
523 // FIXME: don't guess remote URL
524 return buildRemoteVideoBaseUrl(video, path)
527 getRemoteTorrentUrl (video: MVideo) {
528 if (video.isOwned()) throw new Error(`Video ${video.url} is not a remote video`)
530 return this.torrentUrl
533 // We proxify torrent requests so use a local URL
535 if (!this.torrentFilename) return null
537 return WEBSERVER.URL + this.getTorrentStaticPath()
540 getTorrentStaticPath () {
541 if (!this.torrentFilename) return null
543 return join(LAZY_STATIC_PATHS.TORRENTS, this.torrentFilename)
546 getTorrentDownloadUrl () {
547 if (!this.torrentFilename) return null
549 return WEBSERVER.URL + join(STATIC_DOWNLOAD_PATHS.TORRENTS, this.torrentFilename)
553 if (!this.torrentFilename) return null
555 const torrentPath = getFSTorrentFilePath(this)
556 return remove(torrentPath)
557 .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err }))
560 hasSameUniqueKeysThan (other: MVideoFile) {
561 return this.fps === other.fps &&
562 this.resolution === other.resolution &&
564 (this.videoId !== null && this.videoId === other.videoId) ||
565 (this.videoStreamingPlaylistId !== null && this.videoStreamingPlaylistId === other.videoStreamingPlaylistId)
569 withVideoOrPlaylist (videoOrPlaylist: MVideo | MStreamingPlaylistVideo) {
570 if (isStreamingPlaylist(videoOrPlaylist)) return Object.assign(this, { VideoStreamingPlaylist: videoOrPlaylist })
572 return Object.assign(this, { Video: videoOrPlaylist })