14 } from 'sequelize-typescript'
15 import { ActorModel } from '../activitypub/actor'
16 import { getVideoSort, throwIfNotValid } from '../utils'
17 import { isActivityPubUrlValid, isUrlValid } from '../../helpers/custom-validators/activitypub/misc'
18 import { CONSTRAINTS_FIELDS, MIMETYPES } from '../../initializers/constants'
19 import { VideoFileModel } from '../video/video-file'
20 import { getServerActor } from '../../helpers/utils'
21 import { VideoModel } from '../video/video'
22 import { VideoRedundancyStrategy } from '../../../shared/models/redundancy'
23 import { logger } from '../../helpers/logger'
24 import { CacheFileObject, VideoPrivacy } from '../../../shared'
25 import { VideoChannelModel } from '../video/video-channel'
26 import { ServerModel } from '../server/server'
27 import { sample } from 'lodash'
28 import { isTestInstance } from '../../helpers/core-utils'
29 import * as Bluebird from 'bluebird'
30 import * as Sequelize from 'sequelize'
31 import { VideoStreamingPlaylistModel } from '../video/video-streaming-playlist'
32 import { CONFIG } from '../../initializers/config'
34 export enum ScopeNames {
35 WITH_VIDEO = 'WITH_VIDEO'
39 [ ScopeNames.WITH_VIDEO ]: {
42 model: () => VideoFileModel,
46 model: () => VideoModel,
52 model: () => VideoStreamingPlaylistModel,
56 model: () => VideoModel,
61 ] as any // FIXME: sequelize typings
66 tableName: 'videoRedundancy',
69 fields: [ 'videoFileId' ]
80 export class VideoRedundancyModel extends Model<VideoRedundancyModel> {
93 @Is('VideoRedundancyFileUrl', value => throwIfNotValid(value, isUrlValid, 'fileUrl'))
94 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS_REDUNDANCY.URL.max))
98 @Is('VideoRedundancyUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
99 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS_REDUNDANCY.URL.max))
104 strategy: string // Only used by us
106 @ForeignKey(() => VideoFileModel)
110 @BelongsTo(() => VideoFileModel, {
116 VideoFile: VideoFileModel
118 @ForeignKey(() => VideoStreamingPlaylistModel)
120 videoStreamingPlaylistId: number
122 @BelongsTo(() => VideoStreamingPlaylistModel, {
128 VideoStreamingPlaylist: VideoStreamingPlaylistModel
130 @ForeignKey(() => ActorModel)
134 @BelongsTo(() => ActorModel, {
143 static async removeFile (instance: VideoRedundancyModel) {
144 if (!instance.isOwned()) return
146 if (instance.videoFileId) {
147 const videoFile = await VideoFileModel.loadWithVideo(instance.videoFileId)
149 const logIdentifier = `${videoFile.Video.uuid}-${videoFile.resolution}`
150 logger.info('Removing duplicated video file %s.', logIdentifier)
152 videoFile.Video.removeFile(videoFile, true)
153 .catch(err => logger.error('Cannot delete %s files.', logIdentifier, { err }))
156 if (instance.videoStreamingPlaylistId) {
157 const videoStreamingPlaylist = await VideoStreamingPlaylistModel.loadWithVideo(instance.videoStreamingPlaylistId)
159 const videoUUID = videoStreamingPlaylist.Video.uuid
160 logger.info('Removing duplicated video streaming playlist %s.', videoUUID)
162 videoStreamingPlaylist.Video.removeStreamingPlaylist(true)
163 .catch(err => logger.error('Cannot delete video streaming playlist files of %s.', videoUUID, { err }))
169 static async loadLocalByFileId (videoFileId: number) {
170 const actor = await getServerActor()
179 return VideoRedundancyModel.scope(ScopeNames.WITH_VIDEO).findOne(query)
182 static async loadLocalByStreamingPlaylistId (videoStreamingPlaylistId: number) {
183 const actor = await getServerActor()
188 videoStreamingPlaylistId
192 return VideoRedundancyModel.scope(ScopeNames.WITH_VIDEO).findOne(query)
195 static loadByUrl (url: string, transaction?: Sequelize.Transaction) {
203 return VideoRedundancyModel.findOne(query)
206 static async isLocalByVideoUUIDExists (uuid: string) {
207 const actor = await getServerActor()
211 attributes: [ 'id' ],
218 model: VideoFileModel,
234 return VideoRedundancyModel.findOne(query)
238 static async getVideoSample (p: Bluebird<VideoModel[]>) {
240 const ids = rows.map(r => r.id)
241 const id = sample(ids)
243 return VideoModel.loadWithFiles(id, undefined, !isTestInstance())
246 static async findMostViewToDuplicate (randomizedFactor: number) {
249 attributes: [ 'id', 'views' ],
250 limit: randomizedFactor,
251 order: getVideoSort('-views'),
253 privacy: VideoPrivacy.PUBLIC
256 await VideoRedundancyModel.buildVideoFileForDuplication(),
257 VideoRedundancyModel.buildServerRedundancyInclude()
261 return VideoRedundancyModel.getVideoSample(VideoModel.unscoped().findAll(query))
264 static async findTrendingToDuplicate (randomizedFactor: number) {
267 attributes: [ 'id', 'views' ],
269 group: 'VideoModel.id',
270 limit: randomizedFactor,
271 order: getVideoSort('-trending'),
273 privacy: VideoPrivacy.PUBLIC
276 await VideoRedundancyModel.buildVideoFileForDuplication(),
277 VideoRedundancyModel.buildServerRedundancyInclude(),
279 VideoModel.buildTrendingQuery(CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS)
283 return VideoRedundancyModel.getVideoSample(VideoModel.unscoped().findAll(query))
286 static async findRecentlyAddedToDuplicate (randomizedFactor: number, minViews: number) {
289 attributes: [ 'id', 'publishedAt' ],
290 limit: randomizedFactor,
291 order: getVideoSort('-publishedAt'),
293 privacy: VideoPrivacy.PUBLIC,
295 [ Sequelize.Op.gte ]: minViews
299 await VideoRedundancyModel.buildVideoFileForDuplication(),
300 VideoRedundancyModel.buildServerRedundancyInclude()
304 return VideoRedundancyModel.getVideoSample(VideoModel.unscoped().findAll(query))
307 static async loadOldestLocalThatAlreadyExpired (strategy: VideoRedundancyStrategy, expiresAfterMs: number) {
308 const expiredDate = new Date()
309 expiredDate.setMilliseconds(expiredDate.getMilliseconds() - expiresAfterMs)
311 const actor = await getServerActor()
318 [ Sequelize.Op.lt ]: expiredDate
323 return VideoRedundancyModel.scope([ ScopeNames.WITH_VIDEO ]).findOne(query)
326 static async getTotalDuplicated (strategy: VideoRedundancyStrategy) {
327 const actor = await getServerActor()
333 model: VideoRedundancyModel,
343 return VideoFileModel.sum('size', options as any) // FIXME: typings
345 if (!v || isNaN(v)) return 0
351 static async listLocalExpired () {
352 const actor = await getServerActor()
358 [ Sequelize.Op.lt ]: new Date()
363 return VideoRedundancyModel.scope([ ScopeNames.WITH_VIDEO ]).findAll(query)
366 static async listRemoteExpired () {
367 const actor = await getServerActor()
372 [Sequelize.Op.ne]: actor.id
375 [ Sequelize.Op.lt ]: new Date()
380 return VideoRedundancyModel.scope([ ScopeNames.WITH_VIDEO ]).findAll(query)
383 static async listLocalOfServer (serverId: number) {
384 const actor = await getServerActor()
385 const buildVideoInclude = () => ({
391 model: VideoChannelModel.unscoped(),
396 model: ActorModel.unscoped(),
413 model: VideoFileModel,
415 include: [ buildVideoInclude() ]
418 model: VideoStreamingPlaylistModel,
420 include: [ buildVideoInclude() ]
425 return VideoRedundancyModel.findAll(query)
428 static async getStats (strategy: VideoRedundancyStrategy) {
429 const actor = await getServerActor()
434 [ Sequelize.fn('COALESCE', Sequelize.fn('SUM', Sequelize.col('VideoFile.size')), '0'), 'totalUsed' ],
435 [ Sequelize.fn('COUNT', Sequelize.fn('DISTINCT', Sequelize.col('videoId'))), 'totalVideos' ],
436 [ Sequelize.fn('COUNT', Sequelize.col('videoFileId')), 'totalVideoFiles' ]
445 model: VideoFileModel,
451 return VideoRedundancyModel.findOne(query as any) // FIXME: typings
453 totalUsed: parseInt(r.totalUsed.toString(), 10),
454 totalVideos: r.totalVideos,
455 totalVideoFiles: r.totalVideoFiles
460 if (this.VideoFile) return this.VideoFile.Video
462 return this.VideoStreamingPlaylist.Video
466 return !!this.strategy
469 toActivityPubObject (): CacheFileObject {
470 if (this.VideoStreamingPlaylist) {
473 type: 'CacheFile' as 'CacheFile',
474 object: this.VideoStreamingPlaylist.Video.url,
475 expires: this.expiresOn.toISOString(),
478 mimeType: 'application/x-mpegURL',
479 mediaType: 'application/x-mpegURL',
487 type: 'CacheFile' as 'CacheFile',
488 object: this.VideoFile.Video.url,
489 expires: this.expiresOn.toISOString(),
492 mimeType: MIMETYPES.VIDEO.EXT_MIMETYPE[ this.VideoFile.extname ] as any,
493 mediaType: MIMETYPES.VIDEO.EXT_MIMETYPE[ this.VideoFile.extname ] as any,
495 height: this.VideoFile.resolution,
496 size: this.VideoFile.size,
497 fps: this.VideoFile.fps
502 // Don't include video files we already duplicated
503 private static async buildVideoFileForDuplication () {
504 const actor = await getServerActor()
506 const notIn = Sequelize.literal(
508 `SELECT "videoFileId" FROM "videoRedundancy" WHERE "actorId" = ${actor.id} AND "videoFileId" IS NOT NULL` +
514 model: VideoFileModel.unscoped(),
518 [ Sequelize.Op.notIn ]: notIn
524 private static buildServerRedundancyInclude () {
527 model: VideoChannelModel.unscoped(),
532 model: ActorModel.unscoped(),
537 model: ServerModel.unscoped(),
540 redundancyAllowed: true