1 import { remove } from 'fs-extra'
2 import * as 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/lib/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 { getTorrentFilePath } from '@server/lib/video-paths'
27 import { MStreamingPlaylistVideo, MVideo, MVideoWithHost } from '@server/types/models'
28 import { AttributesOnly } from '@shared/core-utils'
30 isVideoFileExtnameValid,
31 isVideoFileInfoHashValid,
32 isVideoFileResolutionValid,
34 isVideoFPSResolutionValid
35 } 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?: Where } = {}) => {
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)
199 // Could be null for live files
208 // Could be null for live files
211 torrentFilename: string
213 @ForeignKey(() => VideoModel)
217 @BelongsTo(() => VideoModel, {
225 @ForeignKey(() => VideoStreamingPlaylistModel)
227 videoStreamingPlaylistId: number
229 @BelongsTo(() => VideoStreamingPlaylistModel, {
235 VideoStreamingPlaylist: VideoStreamingPlaylistModel
237 @HasMany(() => VideoRedundancyModel, {
244 RedundancyVideos: VideoRedundancyModel[]
246 static doesInfohashExistCached = memoizee(VideoFileModel.doesInfohashExist, {
248 max: MEMOIZE_LENGTH.INFO_HASH_EXISTS,
249 maxAge: MEMOIZE_TTL.INFO_HASH_EXISTS
252 static doesInfohashExist (infoHash: string) {
253 const query = 'SELECT 1 FROM "videoFile" WHERE "infoHash" = $infoHash LIMIT 1'
255 return doesExist(query, { infoHash })
258 static async doesVideoExistForVideoFile (id: number, videoIdOrUUID: number | string) {
259 const videoFile = await VideoFileModel.loadWithVideoOrPlaylist(id, videoIdOrUUID)
264 static async doesOwnedTorrentFileExist (filename: string) {
265 const query = 'SELECT 1 FROM "videoFile" ' +
266 'LEFT JOIN "video" "webtorrent" ON "webtorrent"."id" = "videoFile"."videoId" AND "webtorrent"."remote" IS FALSE ' +
267 'LEFT JOIN "videoStreamingPlaylist" ON "videoStreamingPlaylist"."id" = "videoFile"."videoStreamingPlaylistId" ' +
268 'LEFT JOIN "video" "hlsVideo" ON "hlsVideo"."id" = "videoStreamingPlaylist"."videoId" AND "hlsVideo"."remote" IS FALSE ' +
269 'WHERE "torrentFilename" = $filename AND ("hlsVideo"."id" IS NOT NULL OR "webtorrent"."id" IS NOT NULL) LIMIT 1'
271 return doesExist(query, { filename })
274 static async doesOwnedWebTorrentVideoFileExist (filename: string) {
275 const query = 'SELECT 1 FROM "videoFile" INNER JOIN "video" ON "video"."id" = "videoFile"."videoId" AND "video"."remote" IS FALSE ' +
276 'WHERE "filename" = $filename LIMIT 1'
278 return doesExist(query, { filename })
281 static loadByFilename (filename: string) {
288 return VideoFileModel.findOne(query)
291 static loadWithVideoOrPlaylistByTorrentFilename (filename: string) {
294 torrentFilename: filename
298 return VideoFileModel.scope(ScopeNames.WITH_VIDEO_OR_PLAYLIST).findOne(query)
301 static loadWithMetadata (id: number) {
302 return VideoFileModel.scope(ScopeNames.WITH_METADATA).findByPk(id)
305 static loadWithVideo (id: number) {
306 return VideoFileModel.scope(ScopeNames.WITH_VIDEO).findByPk(id)
309 static loadWithVideoOrPlaylist (id: number, videoIdOrUUID: number | string) {
310 const whereVideo = validator.isUUID(videoIdOrUUID + '')
311 ? { uuid: videoIdOrUUID }
312 : { id: videoIdOrUUID }
320 return VideoFileModel.scope({ method: [ ScopeNames.WITH_VIDEO_OR_PLAYLIST, whereVideo ] })
323 // We used `required: false` so check we have at least a video or a streaming playlist
324 if (!file.Video && !file.VideoStreamingPlaylist) return null
330 static listByStreamingPlaylist (streamingPlaylistId: number, transaction: Transaction) {
334 model: VideoModel.unscoped(),
338 model: VideoStreamingPlaylistModel.unscoped(),
341 id: streamingPlaylistId
350 return VideoFileModel.findAll(query)
354 const webtorrentFilesQuery: FindOptions = {
359 model: VideoModel.unscoped(),
367 const hlsFilesQuery: FindOptions = {
372 model: VideoStreamingPlaylistModel.unscoped(),
376 model: VideoModel.unscoped(),
388 VideoFileModel.aggregate('size', 'SUM', webtorrentFilesQuery),
389 VideoFileModel.aggregate('size', 'SUM', hlsFilesQuery)
390 ]).then(([ webtorrentResult, hlsResult ]) => ({
391 totalLocalVideoFilesSize: parseAggregateResult(webtorrentResult) + parseAggregateResult(hlsResult)
395 // Redefine upsert because sequelize does not use an appropriate where clause in the update query with 2 unique indexes
396 static async customUpsert (
397 videoFile: MVideoFile,
398 mode: 'streaming-playlist' | 'video',
399 transaction: Transaction
403 resolution: videoFile.resolution
406 if (mode === 'streaming-playlist') Object.assign(baseWhere, { videoStreamingPlaylistId: videoFile.videoStreamingPlaylistId })
407 else Object.assign(baseWhere, { videoId: videoFile.videoId })
409 const element = await VideoFileModel.findOne({ where: baseWhere, transaction })
410 if (!element) return videoFile.save({ transaction })
412 for (const k of Object.keys(videoFile.toJSON())) {
413 element[k] = videoFile[k]
416 return element.save({ transaction })
419 static removeHLSFilesOfVideoId (videoStreamingPlaylistId: number) {
421 where: { videoStreamingPlaylistId }
424 return VideoFileModel.destroy(options)
428 return this.infoHash && this.torrentFilename
431 getVideoOrStreamingPlaylist (this: MVideoFileVideo | MVideoFileStreamingPlaylistVideo): MVideo | MStreamingPlaylistVideo {
432 if (this.videoId) return (this as MVideoFileVideo).Video
434 return (this as MVideoFileStreamingPlaylistVideo).VideoStreamingPlaylist
437 getVideo (this: MVideoFileVideo | MVideoFileStreamingPlaylistVideo): MVideo {
438 return extractVideo(this.getVideoOrStreamingPlaylist())
442 return !!MIMETYPES.AUDIO.EXT_MIMETYPE[this.extname]
446 return this.size === -1
450 return !!this.videoStreamingPlaylistId
453 getFileUrl (video: MVideo) {
454 if (!this.Video) this.Video = video as VideoModel
456 if (video.isOwned()) return WEBSERVER.URL + this.getFileStaticPath(video)
461 getFileStaticPath (video: MVideo) {
462 if (this.isHLS()) return join(STATIC_PATHS.STREAMING_PLAYLISTS.HLS, video.uuid, this.filename)
464 return join(STATIC_PATHS.WEBSEED, this.filename)
467 getFileDownloadUrl (video: MVideoWithHost) {
468 const path = this.isHLS()
469 ? join(STATIC_DOWNLOAD_PATHS.HLS_VIDEOS, `${video.uuid}-${this.resolution}-fragmented${this.extname}`)
470 : join(STATIC_DOWNLOAD_PATHS.VIDEOS, `${video.uuid}-${this.resolution}${this.extname}`)
472 if (video.isOwned()) return WEBSERVER.URL + path
474 // FIXME: don't guess remote URL
475 return buildRemoteVideoBaseUrl(video, path)
478 getRemoteTorrentUrl (video: MVideo) {
479 if (video.isOwned()) throw new Error(`Video ${video.url} is not a remote video`)
481 return this.torrentUrl
484 // We proxify torrent requests so use a local URL
486 if (!this.torrentFilename) return null
488 return WEBSERVER.URL + this.getTorrentStaticPath()
491 getTorrentStaticPath () {
492 if (!this.torrentFilename) return null
494 return join(LAZY_STATIC_PATHS.TORRENTS, this.torrentFilename)
497 getTorrentDownloadUrl () {
498 if (!this.torrentFilename) return null
500 return WEBSERVER.URL + join(STATIC_DOWNLOAD_PATHS.TORRENTS, this.torrentFilename)
504 if (!this.torrentFilename) return null
506 const torrentPath = getTorrentFilePath(this)
507 return remove(torrentPath)
508 .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err }))
511 hasSameUniqueKeysThan (other: MVideoFile) {
512 return this.fps === other.fps &&
513 this.resolution === other.resolution &&
515 (this.videoId !== null && this.videoId === other.videoId) ||
516 (this.videoStreamingPlaylistId !== null && this.videoStreamingPlaylistId === other.videoStreamingPlaylistId)