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 { CONFIG, CONSTRAINTS_FIELDS, MIMETYPES } from '../../initializers'
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'
32 export enum ScopeNames {
33 WITH_VIDEO = 'WITH_VIDEO'
37 [ ScopeNames.WITH_VIDEO ]: {
40 model: () => VideoFileModel,
44 model: () => VideoModel,
54 tableName: 'videoRedundancy',
57 fields: [ 'videoFileId' ]
68 export class VideoRedundancyModel extends Model<VideoRedundancyModel> {
81 @Is('VideoRedundancyFileUrl', value => throwIfNotValid(value, isUrlValid, 'fileUrl'))
82 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS_REDUNDANCY.URL.max))
86 @Is('VideoRedundancyUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
87 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS_REDUNDANCY.URL.max))
92 strategy: string // Only used by us
94 @ForeignKey(() => VideoFileModel)
98 @BelongsTo(() => VideoFileModel, {
104 VideoFile: VideoFileModel
106 @ForeignKey(() => ActorModel)
110 @BelongsTo(() => ActorModel, {
119 static async removeFile (instance: VideoRedundancyModel) {
120 if (!instance.isOwned()) return
122 const videoFile = await VideoFileModel.loadWithVideo(instance.videoFileId)
124 const logIdentifier = `${videoFile.Video.uuid}-${videoFile.resolution}`
125 logger.info('Removing duplicated video file %s.', logIdentifier)
127 videoFile.Video.removeFile(videoFile, true)
128 .catch(err => logger.error('Cannot delete %s files.', logIdentifier, { err }))
133 static async loadLocalByFileId (videoFileId: number) {
134 const actor = await getServerActor()
143 return VideoRedundancyModel.scope(ScopeNames.WITH_VIDEO).findOne(query)
146 static loadByUrl (url: string, transaction?: Sequelize.Transaction) {
154 return VideoRedundancyModel.findOne(query)
157 static async isLocalByVideoUUIDExists (uuid: string) {
158 const actor = await getServerActor()
162 attributes: [ 'id' ],
169 model: VideoFileModel,
185 return VideoRedundancyModel.findOne(query)
189 static async getVideoSample (p: Bluebird<VideoModel[]>) {
191 const ids = rows.map(r => r.id)
192 const id = sample(ids)
194 return VideoModel.loadWithFile(id, undefined, !isTestInstance())
197 static async findMostViewToDuplicate (randomizedFactor: number) {
200 attributes: [ 'id', 'views' ],
201 limit: randomizedFactor,
202 order: getVideoSort('-views'),
204 privacy: VideoPrivacy.PUBLIC
207 await VideoRedundancyModel.buildVideoFileForDuplication(),
208 VideoRedundancyModel.buildServerRedundancyInclude()
212 return VideoRedundancyModel.getVideoSample(VideoModel.unscoped().findAll(query))
215 static async findTrendingToDuplicate (randomizedFactor: number) {
218 attributes: [ 'id', 'views' ],
220 group: 'VideoModel.id',
221 limit: randomizedFactor,
222 order: getVideoSort('-trending'),
224 privacy: VideoPrivacy.PUBLIC
227 await VideoRedundancyModel.buildVideoFileForDuplication(),
228 VideoRedundancyModel.buildServerRedundancyInclude(),
230 VideoModel.buildTrendingQuery(CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS)
234 return VideoRedundancyModel.getVideoSample(VideoModel.unscoped().findAll(query))
237 static async findRecentlyAddedToDuplicate (randomizedFactor: number, minViews: number) {
240 attributes: [ 'id', 'publishedAt' ],
241 limit: randomizedFactor,
242 order: getVideoSort('-publishedAt'),
244 privacy: VideoPrivacy.PUBLIC,
246 [ Sequelize.Op.gte ]: minViews
250 await VideoRedundancyModel.buildVideoFileForDuplication(),
251 VideoRedundancyModel.buildServerRedundancyInclude()
255 return VideoRedundancyModel.getVideoSample(VideoModel.unscoped().findAll(query))
258 static async loadOldestLocalThatAlreadyExpired (strategy: VideoRedundancyStrategy, expiresAfterMs: number) {
259 const expiredDate = new Date()
260 expiredDate.setMilliseconds(expiredDate.getMilliseconds() - expiresAfterMs)
262 const actor = await getServerActor()
269 [ Sequelize.Op.lt ]: expiredDate
274 return VideoRedundancyModel.scope([ ScopeNames.WITH_VIDEO ]).findOne(query)
277 static async getTotalDuplicated (strategy: VideoRedundancyStrategy) {
278 const actor = await getServerActor()
284 model: VideoRedundancyModel,
294 return VideoFileModel.sum('size', options as any) // FIXME: typings
296 if (!v || isNaN(v)) return 0
302 static async listLocalExpired () {
303 const actor = await getServerActor()
309 [ Sequelize.Op.lt ]: new Date()
314 return VideoRedundancyModel.scope([ ScopeNames.WITH_VIDEO ]).findAll(query)
317 static async listRemoteExpired () {
318 const actor = await getServerActor()
323 [Sequelize.Op.ne]: actor.id
326 [ Sequelize.Op.lt ]: new Date()
331 return VideoRedundancyModel.scope([ ScopeNames.WITH_VIDEO ]).findAll(query)
334 static async listLocalOfServer (serverId: number) {
335 const actor = await getServerActor()
343 model: VideoFileModel,
352 model: VideoChannelModel.unscoped(),
357 model: ActorModel.unscoped(),
372 return VideoRedundancyModel.findAll(query)
375 static async getStats (strategy: VideoRedundancyStrategy) {
376 const actor = await getServerActor()
381 [ Sequelize.fn('COALESCE', Sequelize.fn('SUM', Sequelize.col('VideoFile.size')), '0'), 'totalUsed' ],
382 [ Sequelize.fn('COUNT', Sequelize.fn('DISTINCT', Sequelize.col('videoId'))), 'totalVideos' ],
383 [ Sequelize.fn('COUNT', Sequelize.col('videoFileId')), 'totalVideoFiles' ]
392 model: VideoFileModel,
398 return VideoRedundancyModel.find(query as any) // FIXME: typings
400 totalUsed: parseInt(r.totalUsed.toString(), 10),
401 totalVideos: r.totalVideos,
402 totalVideoFiles: r.totalVideoFiles
407 return !!this.strategy
410 toActivityPubObject (): CacheFileObject {
413 type: 'CacheFile' as 'CacheFile',
414 object: this.VideoFile.Video.url,
415 expires: this.expiresOn.toISOString(),
418 mimeType: MIMETYPES.VIDEO.EXT_MIMETYPE[ this.VideoFile.extname ] as any,
419 mediaType: MIMETYPES.VIDEO.EXT_MIMETYPE[ this.VideoFile.extname ] as any,
421 height: this.VideoFile.resolution,
422 size: this.VideoFile.size,
423 fps: this.VideoFile.fps
428 // Don't include video files we already duplicated
429 private static async buildVideoFileForDuplication () {
430 const actor = await getServerActor()
432 const notIn = Sequelize.literal(
434 `SELECT "videoFileId" FROM "videoRedundancy" WHERE "actorId" = ${actor.id}` +
440 model: VideoFileModel.unscoped(),
444 [ Sequelize.Op.notIn ]: notIn
450 private static buildServerRedundancyInclude () {
453 model: VideoChannelModel.unscoped(),
458 model: ActorModel.unscoped(),
463 model: ServerModel.unscoped(),
466 redundancyAllowed: true