]>
Commit | Line | Data |
---|---|---|
1 | import { remove } from 'fs-extra' | |
2 | import memoizee from 'memoizee' | |
3 | import { join } from 'path' | |
4 | import { FindOptions, Op, Transaction } from 'sequelize' | |
5 | import { | |
6 | AllowNull, | |
7 | BelongsTo, | |
8 | Column, | |
9 | CreatedAt, | |
10 | DataType, | |
11 | Default, | |
12 | DefaultScope, | |
13 | ForeignKey, | |
14 | HasMany, | |
15 | Is, | |
16 | Model, | |
17 | Scopes, | |
18 | Table, | |
19 | UpdatedAt | |
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 { 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 { AttributesOnly } from '@shared/core-utils' | |
30 | import { VideoStorage } from '@shared/models' | |
31 | import { | |
32 | isVideoFileExtnameValid, | |
33 | isVideoFileInfoHashValid, | |
34 | isVideoFileResolutionValid, | |
35 | isVideoFileSizeValid, | |
36 | isVideoFPSResolutionValid | |
37 | } from '../../helpers/custom-validators/videos' | |
38 | import { | |
39 | LAZY_STATIC_PATHS, | |
40 | MEMOIZE_LENGTH, | |
41 | MEMOIZE_TTL, | |
42 | MIMETYPES, | |
43 | STATIC_DOWNLOAD_PATHS, | |
44 | STATIC_PATHS, | |
45 | WEBSERVER | |
46 | } from '../../initializers/constants' | |
47 | import { MVideoFile, MVideoFileStreamingPlaylistVideo, MVideoFileVideo } from '../../types/models/video/video-file' | |
48 | import { VideoRedundancyModel } from '../redundancy/video-redundancy' | |
49 | import { doesExist } from '../shared' | |
50 | import { parseAggregateResult, throwIfNotValid } from '../utils' | |
51 | import { VideoModel } from './video' | |
52 | import { VideoStreamingPlaylistModel } from './video-streaming-playlist' | |
53 | ||
54 | export enum ScopeNames { | |
55 | WITH_VIDEO = 'WITH_VIDEO', | |
56 | WITH_METADATA = 'WITH_METADATA', | |
57 | WITH_VIDEO_OR_PLAYLIST = 'WITH_VIDEO_OR_PLAYLIST' | |
58 | } | |
59 | ||
60 | @DefaultScope(() => ({ | |
61 | attributes: { | |
62 | exclude: [ 'metadata' ] | |
63 | } | |
64 | })) | |
65 | @Scopes(() => ({ | |
66 | [ScopeNames.WITH_VIDEO]: { | |
67 | include: [ | |
68 | { | |
69 | model: VideoModel.unscoped(), | |
70 | required: true | |
71 | } | |
72 | ] | |
73 | }, | |
74 | [ScopeNames.WITH_VIDEO_OR_PLAYLIST]: (options: { whereVideo?: Where } = {}) => { | |
75 | return { | |
76 | include: [ | |
77 | { | |
78 | model: VideoModel.unscoped(), | |
79 | required: false, | |
80 | where: options.whereVideo | |
81 | }, | |
82 | { | |
83 | model: VideoStreamingPlaylistModel.unscoped(), | |
84 | required: false, | |
85 | include: [ | |
86 | { | |
87 | model: VideoModel.unscoped(), | |
88 | required: true, | |
89 | where: options.whereVideo | |
90 | } | |
91 | ] | |
92 | } | |
93 | ] | |
94 | } | |
95 | }, | |
96 | [ScopeNames.WITH_METADATA]: { | |
97 | attributes: { | |
98 | include: [ 'metadata' ] | |
99 | } | |
100 | } | |
101 | })) | |
102 | @Table({ | |
103 | tableName: 'videoFile', | |
104 | indexes: [ | |
105 | { | |
106 | fields: [ 'videoId' ], | |
107 | where: { | |
108 | videoId: { | |
109 | [Op.ne]: null | |
110 | } | |
111 | } | |
112 | }, | |
113 | { | |
114 | fields: [ 'videoStreamingPlaylistId' ], | |
115 | where: { | |
116 | videoStreamingPlaylistId: { | |
117 | [Op.ne]: null | |
118 | } | |
119 | } | |
120 | }, | |
121 | ||
122 | { | |
123 | fields: [ 'infoHash' ] | |
124 | }, | |
125 | ||
126 | { | |
127 | fields: [ 'torrentFilename' ], | |
128 | unique: true | |
129 | }, | |
130 | ||
131 | { | |
132 | fields: [ 'filename' ], | |
133 | unique: true | |
134 | }, | |
135 | ||
136 | { | |
137 | fields: [ 'videoId', 'resolution', 'fps' ], | |
138 | unique: true, | |
139 | where: { | |
140 | videoId: { | |
141 | [Op.ne]: null | |
142 | } | |
143 | } | |
144 | }, | |
145 | { | |
146 | fields: [ 'videoStreamingPlaylistId', 'resolution', 'fps' ], | |
147 | unique: true, | |
148 | where: { | |
149 | videoStreamingPlaylistId: { | |
150 | [Op.ne]: null | |
151 | } | |
152 | } | |
153 | } | |
154 | ] | |
155 | }) | |
156 | export class VideoFileModel extends Model<Partial<AttributesOnly<VideoFileModel>>> { | |
157 | @CreatedAt | |
158 | createdAt: Date | |
159 | ||
160 | @UpdatedAt | |
161 | updatedAt: Date | |
162 | ||
163 | @AllowNull(false) | |
164 | @Is('VideoFileResolution', value => throwIfNotValid(value, isVideoFileResolutionValid, 'resolution')) | |
165 | @Column | |
166 | resolution: number | |
167 | ||
168 | @AllowNull(false) | |
169 | @Is('VideoFileSize', value => throwIfNotValid(value, isVideoFileSizeValid, 'size')) | |
170 | @Column(DataType.BIGINT) | |
171 | size: number | |
172 | ||
173 | @AllowNull(false) | |
174 | @Is('VideoFileExtname', value => throwIfNotValid(value, isVideoFileExtnameValid, 'extname')) | |
175 | @Column | |
176 | extname: string | |
177 | ||
178 | @AllowNull(true) | |
179 | @Is('VideoFileInfohash', value => throwIfNotValid(value, isVideoFileInfoHashValid, 'info hash', true)) | |
180 | @Column | |
181 | infoHash: string | |
182 | ||
183 | @AllowNull(false) | |
184 | @Default(-1) | |
185 | @Is('VideoFileFPS', value => throwIfNotValid(value, isVideoFPSResolutionValid, 'fps')) | |
186 | @Column | |
187 | fps: number | |
188 | ||
189 | @AllowNull(true) | |
190 | @Column(DataType.JSONB) | |
191 | metadata: any | |
192 | ||
193 | @AllowNull(true) | |
194 | @Column | |
195 | metadataUrl: string | |
196 | ||
197 | // Could be null for remote files | |
198 | @AllowNull(true) | |
199 | @Column | |
200 | fileUrl: string | |
201 | ||
202 | // Could be null for live files | |
203 | @AllowNull(true) | |
204 | @Column | |
205 | filename: string | |
206 | ||
207 | // Could be null for remote files | |
208 | @AllowNull(true) | |
209 | @Column | |
210 | torrentUrl: string | |
211 | ||
212 | // Could be null for live files | |
213 | @AllowNull(true) | |
214 | @Column | |
215 | torrentFilename: string | |
216 | ||
217 | @ForeignKey(() => VideoModel) | |
218 | @Column | |
219 | videoId: number | |
220 | ||
221 | @AllowNull(false) | |
222 | @Default(VideoStorage.FILE_SYSTEM) | |
223 | @Column | |
224 | storage: VideoStorage | |
225 | ||
226 | @BelongsTo(() => VideoModel, { | |
227 | foreignKey: { | |
228 | allowNull: true | |
229 | }, | |
230 | onDelete: 'CASCADE' | |
231 | }) | |
232 | Video: VideoModel | |
233 | ||
234 | @ForeignKey(() => VideoStreamingPlaylistModel) | |
235 | @Column | |
236 | videoStreamingPlaylistId: number | |
237 | ||
238 | @BelongsTo(() => VideoStreamingPlaylistModel, { | |
239 | foreignKey: { | |
240 | allowNull: true | |
241 | }, | |
242 | onDelete: 'CASCADE' | |
243 | }) | |
244 | VideoStreamingPlaylist: VideoStreamingPlaylistModel | |
245 | ||
246 | @HasMany(() => VideoRedundancyModel, { | |
247 | foreignKey: { | |
248 | allowNull: true | |
249 | }, | |
250 | onDelete: 'CASCADE', | |
251 | hooks: true | |
252 | }) | |
253 | RedundancyVideos: VideoRedundancyModel[] | |
254 | ||
255 | static doesInfohashExistCached = memoizee(VideoFileModel.doesInfohashExist, { | |
256 | promise: true, | |
257 | max: MEMOIZE_LENGTH.INFO_HASH_EXISTS, | |
258 | maxAge: MEMOIZE_TTL.INFO_HASH_EXISTS | |
259 | }) | |
260 | ||
261 | static doesInfohashExist (infoHash: string) { | |
262 | const query = 'SELECT 1 FROM "videoFile" WHERE "infoHash" = $infoHash LIMIT 1' | |
263 | ||
264 | return doesExist(query, { infoHash }) | |
265 | } | |
266 | ||
267 | static async doesVideoExistForVideoFile (id: number, videoIdOrUUID: number | string) { | |
268 | const videoFile = await VideoFileModel.loadWithVideoOrPlaylist(id, videoIdOrUUID) | |
269 | ||
270 | return !!videoFile | |
271 | } | |
272 | ||
273 | static async doesOwnedTorrentFileExist (filename: string) { | |
274 | const query = 'SELECT 1 FROM "videoFile" ' + | |
275 | 'LEFT JOIN "video" "webtorrent" ON "webtorrent"."id" = "videoFile"."videoId" AND "webtorrent"."remote" IS FALSE ' + | |
276 | 'LEFT JOIN "videoStreamingPlaylist" ON "videoStreamingPlaylist"."id" = "videoFile"."videoStreamingPlaylistId" ' + | |
277 | 'LEFT JOIN "video" "hlsVideo" ON "hlsVideo"."id" = "videoStreamingPlaylist"."videoId" AND "hlsVideo"."remote" IS FALSE ' + | |
278 | 'WHERE "torrentFilename" = $filename AND ("hlsVideo"."id" IS NOT NULL OR "webtorrent"."id" IS NOT NULL) LIMIT 1' | |
279 | ||
280 | return doesExist(query, { filename }) | |
281 | } | |
282 | ||
283 | static async doesOwnedWebTorrentVideoFileExist (filename: string) { | |
284 | const query = 'SELECT 1 FROM "videoFile" INNER JOIN "video" ON "video"."id" = "videoFile"."videoId" AND "video"."remote" IS FALSE ' + | |
285 | `WHERE "filename" = $filename AND "storage" = ${VideoStorage.FILE_SYSTEM} LIMIT 1` | |
286 | ||
287 | return doesExist(query, { filename }) | |
288 | } | |
289 | ||
290 | static loadByFilename (filename: string) { | |
291 | const query = { | |
292 | where: { | |
293 | filename | |
294 | } | |
295 | } | |
296 | ||
297 | return VideoFileModel.findOne(query) | |
298 | } | |
299 | ||
300 | static loadWithVideoOrPlaylistByTorrentFilename (filename: string) { | |
301 | const query = { | |
302 | where: { | |
303 | torrentFilename: filename | |
304 | } | |
305 | } | |
306 | ||
307 | return VideoFileModel.scope(ScopeNames.WITH_VIDEO_OR_PLAYLIST).findOne(query) | |
308 | } | |
309 | ||
310 | static loadWithMetadata (id: number) { | |
311 | return VideoFileModel.scope(ScopeNames.WITH_METADATA).findByPk(id) | |
312 | } | |
313 | ||
314 | static loadWithVideo (id: number) { | |
315 | return VideoFileModel.scope(ScopeNames.WITH_VIDEO).findByPk(id) | |
316 | } | |
317 | ||
318 | static loadWithVideoOrPlaylist (id: number, videoIdOrUUID: number | string) { | |
319 | const whereVideo = validator.isUUID(videoIdOrUUID + '') | |
320 | ? { uuid: videoIdOrUUID } | |
321 | : { id: videoIdOrUUID } | |
322 | ||
323 | const options = { | |
324 | where: { | |
325 | id | |
326 | } | |
327 | } | |
328 | ||
329 | return VideoFileModel.scope({ method: [ ScopeNames.WITH_VIDEO_OR_PLAYLIST, whereVideo ] }) | |
330 | .findOne(options) | |
331 | .then(file => { | |
332 | // We used `required: false` so check we have at least a video or a streaming playlist | |
333 | if (!file.Video && !file.VideoStreamingPlaylist) return null | |
334 | ||
335 | return file | |
336 | }) | |
337 | } | |
338 | ||
339 | static listByStreamingPlaylist (streamingPlaylistId: number, transaction: Transaction) { | |
340 | const query = { | |
341 | include: [ | |
342 | { | |
343 | model: VideoModel.unscoped(), | |
344 | required: true, | |
345 | include: [ | |
346 | { | |
347 | model: VideoStreamingPlaylistModel.unscoped(), | |
348 | required: true, | |
349 | where: { | |
350 | id: streamingPlaylistId | |
351 | } | |
352 | } | |
353 | ] | |
354 | } | |
355 | ], | |
356 | transaction | |
357 | } | |
358 | ||
359 | return VideoFileModel.findAll(query) | |
360 | } | |
361 | ||
362 | static getStats () { | |
363 | const webtorrentFilesQuery: FindOptions = { | |
364 | include: [ | |
365 | { | |
366 | attributes: [], | |
367 | required: true, | |
368 | model: VideoModel.unscoped(), | |
369 | where: { | |
370 | remote: false | |
371 | } | |
372 | } | |
373 | ] | |
374 | } | |
375 | ||
376 | const hlsFilesQuery: FindOptions = { | |
377 | include: [ | |
378 | { | |
379 | attributes: [], | |
380 | required: true, | |
381 | model: VideoStreamingPlaylistModel.unscoped(), | |
382 | include: [ | |
383 | { | |
384 | attributes: [], | |
385 | model: VideoModel.unscoped(), | |
386 | required: true, | |
387 | where: { | |
388 | remote: false | |
389 | } | |
390 | } | |
391 | ] | |
392 | } | |
393 | ] | |
394 | } | |
395 | ||
396 | return Promise.all([ | |
397 | VideoFileModel.aggregate('size', 'SUM', webtorrentFilesQuery), | |
398 | VideoFileModel.aggregate('size', 'SUM', hlsFilesQuery) | |
399 | ]).then(([ webtorrentResult, hlsResult ]) => ({ | |
400 | totalLocalVideoFilesSize: parseAggregateResult(webtorrentResult) + parseAggregateResult(hlsResult) | |
401 | })) | |
402 | } | |
403 | ||
404 | // Redefine upsert because sequelize does not use an appropriate where clause in the update query with 2 unique indexes | |
405 | static async customUpsert ( | |
406 | videoFile: MVideoFile, | |
407 | mode: 'streaming-playlist' | 'video', | |
408 | transaction: Transaction | |
409 | ) { | |
410 | const baseWhere = { | |
411 | fps: videoFile.fps, | |
412 | resolution: videoFile.resolution | |
413 | } | |
414 | ||
415 | if (mode === 'streaming-playlist') Object.assign(baseWhere, { videoStreamingPlaylistId: videoFile.videoStreamingPlaylistId }) | |
416 | else Object.assign(baseWhere, { videoId: videoFile.videoId }) | |
417 | ||
418 | const element = await VideoFileModel.findOne({ where: baseWhere, transaction }) | |
419 | if (!element) return videoFile.save({ transaction }) | |
420 | ||
421 | for (const k of Object.keys(videoFile.toJSON())) { | |
422 | element[k] = videoFile[k] | |
423 | } | |
424 | ||
425 | return element.save({ transaction }) | |
426 | } | |
427 | ||
428 | static removeHLSFilesOfVideoId (videoStreamingPlaylistId: number) { | |
429 | const options = { | |
430 | where: { videoStreamingPlaylistId } | |
431 | } | |
432 | ||
433 | return VideoFileModel.destroy(options) | |
434 | } | |
435 | ||
436 | hasTorrent () { | |
437 | return this.infoHash && this.torrentFilename | |
438 | } | |
439 | ||
440 | getVideoOrStreamingPlaylist (this: MVideoFileVideo | MVideoFileStreamingPlaylistVideo): MVideo | MStreamingPlaylistVideo { | |
441 | if (this.videoId) return (this as MVideoFileVideo).Video | |
442 | ||
443 | return (this as MVideoFileStreamingPlaylistVideo).VideoStreamingPlaylist | |
444 | } | |
445 | ||
446 | getVideo (this: MVideoFileVideo | MVideoFileStreamingPlaylistVideo): MVideo { | |
447 | return extractVideo(this.getVideoOrStreamingPlaylist()) | |
448 | } | |
449 | ||
450 | isAudio () { | |
451 | return !!MIMETYPES.AUDIO.EXT_MIMETYPE[this.extname] | |
452 | } | |
453 | ||
454 | isLive () { | |
455 | return this.size === -1 | |
456 | } | |
457 | ||
458 | isHLS () { | |
459 | return !!this.videoStreamingPlaylistId | |
460 | } | |
461 | ||
462 | getObjectStorageUrl () { | |
463 | if (this.isHLS()) { | |
464 | return getHLSPublicFileUrl(this.fileUrl) | |
465 | } | |
466 | ||
467 | return getWebTorrentPublicFileUrl(this.fileUrl) | |
468 | } | |
469 | ||
470 | getFileUrl (video: MVideo) { | |
471 | if (this.storage === VideoStorage.OBJECT_STORAGE) { | |
472 | return this.getObjectStorageUrl() | |
473 | } | |
474 | ||
475 | if (!this.Video) this.Video = video as VideoModel | |
476 | if (video.isOwned()) return WEBSERVER.URL + this.getFileStaticPath(video) | |
477 | ||
478 | return this.fileUrl | |
479 | } | |
480 | ||
481 | getFileStaticPath (video: MVideo) { | |
482 | if (this.isHLS()) return join(STATIC_PATHS.STREAMING_PLAYLISTS.HLS, video.uuid, this.filename) | |
483 | ||
484 | return join(STATIC_PATHS.WEBSEED, this.filename) | |
485 | } | |
486 | ||
487 | getFileDownloadUrl (video: MVideoWithHost) { | |
488 | const path = this.isHLS() | |
489 | ? join(STATIC_DOWNLOAD_PATHS.HLS_VIDEOS, `${video.uuid}-${this.resolution}-fragmented${this.extname}`) | |
490 | : join(STATIC_DOWNLOAD_PATHS.VIDEOS, `${video.uuid}-${this.resolution}${this.extname}`) | |
491 | ||
492 | if (video.isOwned()) return WEBSERVER.URL + path | |
493 | ||
494 | // FIXME: don't guess remote URL | |
495 | return buildRemoteVideoBaseUrl(video, path) | |
496 | } | |
497 | ||
498 | getRemoteTorrentUrl (video: MVideo) { | |
499 | if (video.isOwned()) throw new Error(`Video ${video.url} is not a remote video`) | |
500 | ||
501 | return this.torrentUrl | |
502 | } | |
503 | ||
504 | // We proxify torrent requests so use a local URL | |
505 | getTorrentUrl () { | |
506 | if (!this.torrentFilename) return null | |
507 | ||
508 | return WEBSERVER.URL + this.getTorrentStaticPath() | |
509 | } | |
510 | ||
511 | getTorrentStaticPath () { | |
512 | if (!this.torrentFilename) return null | |
513 | ||
514 | return join(LAZY_STATIC_PATHS.TORRENTS, this.torrentFilename) | |
515 | } | |
516 | ||
517 | getTorrentDownloadUrl () { | |
518 | if (!this.torrentFilename) return null | |
519 | ||
520 | return WEBSERVER.URL + join(STATIC_DOWNLOAD_PATHS.TORRENTS, this.torrentFilename) | |
521 | } | |
522 | ||
523 | removeTorrent () { | |
524 | if (!this.torrentFilename) return null | |
525 | ||
526 | const torrentPath = getFSTorrentFilePath(this) | |
527 | return remove(torrentPath) | |
528 | .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err })) | |
529 | } | |
530 | ||
531 | hasSameUniqueKeysThan (other: MVideoFile) { | |
532 | return this.fps === other.fps && | |
533 | this.resolution === other.resolution && | |
534 | ( | |
535 | (this.videoId !== null && this.videoId === other.videoId) || | |
536 | (this.videoStreamingPlaylistId !== null && this.videoStreamingPlaylistId === other.videoStreamingPlaylistId) | |
537 | ) | |
538 | } | |
539 | ||
540 | withVideoOrPlaylist (videoOrPlaylist: MVideo | MStreamingPlaylistVideo) { | |
541 | if (isStreamingPlaylist(videoOrPlaylist)) return Object.assign(this, { VideoStreamingPlaylist: videoOrPlaylist }) | |
542 | ||
543 | return Object.assign(this, { Video: videoOrPlaylist }) | |
544 | } | |
545 | } |