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, VIDEO_EXT_MIMETYPE } 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 removeFile (instance: VideoRedundancyModel) {
121 if (!instance.strategy) return
123 logger.info('Removing duplicated video file %s-%s.', instance.VideoFile.Video.uuid, instance.VideoFile.resolution)
125 return instance.VideoFile.Video.removeFile(instance.VideoFile)
128 static loadByFileId (videoFileId: number) {
135 return VideoRedundancyModel.scope(ScopeNames.WITH_VIDEO).findOne(query)
138 static loadByUrl (url: string, transaction?: Sequelize.Transaction) {
146 return VideoRedundancyModel.findOne(query)
149 static async isLocalByVideoUUIDExists (uuid: string) {
150 const actor = await getServerActor()
154 attributes: [ 'id' ],
161 model: VideoFileModel,
177 return VideoRedundancyModel.findOne(query)
181 static async getVideoSample (p: Bluebird<VideoModel[]>) {
183 const ids = rows.map(r => r.id)
184 const id = sample(ids)
186 return VideoModel.loadWithFile(id, undefined, !isTestInstance())
189 static async findMostViewToDuplicate (randomizedFactor: number) {
192 attributes: [ 'id', 'views' ],
193 limit: randomizedFactor,
194 order: getVideoSort('-views'),
196 privacy: VideoPrivacy.PUBLIC
199 await VideoRedundancyModel.buildVideoFileForDuplication(),
200 VideoRedundancyModel.buildServerRedundancyInclude()
204 return VideoRedundancyModel.getVideoSample(VideoModel.unscoped().findAll(query))
207 static async findTrendingToDuplicate (randomizedFactor: number) {
210 attributes: [ 'id', 'views' ],
212 group: 'VideoModel.id',
213 limit: randomizedFactor,
214 order: getVideoSort('-trending'),
216 privacy: VideoPrivacy.PUBLIC
219 await VideoRedundancyModel.buildVideoFileForDuplication(),
220 VideoRedundancyModel.buildServerRedundancyInclude(),
222 VideoModel.buildTrendingQuery(CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS)
226 return VideoRedundancyModel.getVideoSample(VideoModel.unscoped().findAll(query))
229 static async findRecentlyAddedToDuplicate (randomizedFactor: number, minViews: number) {
232 attributes: [ 'id', 'publishedAt' ],
233 limit: randomizedFactor,
234 order: getVideoSort('-publishedAt'),
236 privacy: VideoPrivacy.PUBLIC,
238 [ Sequelize.Op.gte ]: minViews
242 await VideoRedundancyModel.buildVideoFileForDuplication(),
243 VideoRedundancyModel.buildServerRedundancyInclude()
247 return VideoRedundancyModel.getVideoSample(VideoModel.unscoped().findAll(query))
250 static async loadOldestLocalThatAlreadyExpired (strategy: VideoRedundancyStrategy, expiresAfterMs: number) {
251 const expiredDate = new Date()
252 expiredDate.setMilliseconds(expiredDate.getMilliseconds() - expiresAfterMs)
254 const actor = await getServerActor()
261 [ Sequelize.Op.lt ]: expiredDate
266 return VideoRedundancyModel.scope([ ScopeNames.WITH_VIDEO ]).findOne(query)
269 static async getTotalDuplicated (strategy: VideoRedundancyStrategy) {
270 const actor = await getServerActor()
276 model: VideoRedundancyModel,
286 return VideoFileModel.sum('size', options as any) // FIXME: typings
289 static async listLocalExpired () {
290 const actor = await getServerActor()
296 [ Sequelize.Op.lt ]: new Date()
301 return VideoRedundancyModel.scope([ ScopeNames.WITH_VIDEO ]).findAll(query)
304 static async listRemoteExpired () {
305 const actor = await getServerActor()
310 [Sequelize.Op.ne]: actor.id
313 [ Sequelize.Op.lt ]: new Date()
318 return VideoRedundancyModel.scope([ ScopeNames.WITH_VIDEO ]).findAll(query)
321 static async listLocalOfServer (serverId: number) {
322 const actor = await getServerActor()
330 model: VideoFileModel,
339 model: VideoChannelModel.unscoped(),
344 model: ActorModel.unscoped(),
359 return VideoRedundancyModel.findAll(query)
362 static async getStats (strategy: VideoRedundancyStrategy) {
363 const actor = await getServerActor()
368 [ Sequelize.fn('COALESCE', Sequelize.fn('SUM', Sequelize.col('VideoFile.size')), '0'), 'totalUsed' ],
369 [ Sequelize.fn('COUNT', Sequelize.fn('DISTINCT', Sequelize.col('videoId'))), 'totalVideos' ],
370 [ Sequelize.fn('COUNT', Sequelize.col('videoFileId')), 'totalVideoFiles' ]
379 model: VideoFileModel,
385 return VideoRedundancyModel.find(query as any) // FIXME: typings
387 totalUsed: parseInt(r.totalUsed.toString(), 10),
388 totalVideos: r.totalVideos,
389 totalVideoFiles: r.totalVideoFiles
393 toActivityPubObject (): CacheFileObject {
396 type: 'CacheFile' as 'CacheFile',
397 object: this.VideoFile.Video.url,
398 expires: this.expiresOn.toISOString(),
401 mimeType: VIDEO_EXT_MIMETYPE[ this.VideoFile.extname ] as any,
403 height: this.VideoFile.resolution,
404 size: this.VideoFile.size,
405 fps: this.VideoFile.fps
410 // Don't include video files we already duplicated
411 private static async buildVideoFileForDuplication () {
412 const actor = await getServerActor()
414 const notIn = Sequelize.literal(
416 `SELECT "videoFileId" FROM "videoRedundancy" WHERE "actorId" = ${actor.id}` +
422 model: VideoFileModel.unscoped(),
426 [ Sequelize.Op.notIn ]: notIn
432 private static buildServerRedundancyInclude () {
435 model: VideoChannelModel.unscoped(),
440 model: ActorModel.unscoped(),
445 model: ServerModel.unscoped(),
448 redundancyAllowed: true