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 async loadLocalByFileId (videoFileId: number) {
129 const actor = await getServerActor()
138 return VideoRedundancyModel.scope(ScopeNames.WITH_VIDEO).findOne(query)
141 static loadByUrl (url: string, transaction?: Sequelize.Transaction) {
149 return VideoRedundancyModel.findOne(query)
152 static async isLocalByVideoUUIDExists (uuid: string) {
153 const actor = await getServerActor()
157 attributes: [ 'id' ],
164 model: VideoFileModel,
180 return VideoRedundancyModel.findOne(query)
184 static async getVideoSample (p: Bluebird<VideoModel[]>) {
186 const ids = rows.map(r => r.id)
187 const id = sample(ids)
189 return VideoModel.loadWithFile(id, undefined, !isTestInstance())
192 static async findMostViewToDuplicate (randomizedFactor: number) {
195 attributes: [ 'id', 'views' ],
196 limit: randomizedFactor,
197 order: getVideoSort('-views'),
199 privacy: VideoPrivacy.PUBLIC
202 await VideoRedundancyModel.buildVideoFileForDuplication(),
203 VideoRedundancyModel.buildServerRedundancyInclude()
207 return VideoRedundancyModel.getVideoSample(VideoModel.unscoped().findAll(query))
210 static async findTrendingToDuplicate (randomizedFactor: number) {
213 attributes: [ 'id', 'views' ],
215 group: 'VideoModel.id',
216 limit: randomizedFactor,
217 order: getVideoSort('-trending'),
219 privacy: VideoPrivacy.PUBLIC
222 await VideoRedundancyModel.buildVideoFileForDuplication(),
223 VideoRedundancyModel.buildServerRedundancyInclude(),
225 VideoModel.buildTrendingQuery(CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS)
229 return VideoRedundancyModel.getVideoSample(VideoModel.unscoped().findAll(query))
232 static async findRecentlyAddedToDuplicate (randomizedFactor: number, minViews: number) {
235 attributes: [ 'id', 'publishedAt' ],
236 limit: randomizedFactor,
237 order: getVideoSort('-publishedAt'),
239 privacy: VideoPrivacy.PUBLIC,
241 [ Sequelize.Op.gte ]: minViews
245 await VideoRedundancyModel.buildVideoFileForDuplication(),
246 VideoRedundancyModel.buildServerRedundancyInclude()
250 return VideoRedundancyModel.getVideoSample(VideoModel.unscoped().findAll(query))
253 static async loadOldestLocalThatAlreadyExpired (strategy: VideoRedundancyStrategy, expiresAfterMs: number) {
254 const expiredDate = new Date()
255 expiredDate.setMilliseconds(expiredDate.getMilliseconds() - expiresAfterMs)
257 const actor = await getServerActor()
264 [ Sequelize.Op.lt ]: expiredDate
269 return VideoRedundancyModel.scope([ ScopeNames.WITH_VIDEO ]).findOne(query)
272 static async getTotalDuplicated (strategy: VideoRedundancyStrategy) {
273 const actor = await getServerActor()
279 model: VideoRedundancyModel,
289 return VideoFileModel.sum('size', options as any) // FIXME: typings
292 static async listLocalExpired () {
293 const actor = await getServerActor()
299 [ Sequelize.Op.lt ]: new Date()
304 return VideoRedundancyModel.scope([ ScopeNames.WITH_VIDEO ]).findAll(query)
307 static async listRemoteExpired () {
308 const actor = await getServerActor()
313 [Sequelize.Op.ne]: actor.id
316 [ Sequelize.Op.lt ]: new Date()
321 return VideoRedundancyModel.scope([ ScopeNames.WITH_VIDEO ]).findAll(query)
324 static async listLocalOfServer (serverId: number) {
325 const actor = await getServerActor()
333 model: VideoFileModel,
342 model: VideoChannelModel.unscoped(),
347 model: ActorModel.unscoped(),
362 return VideoRedundancyModel.findAll(query)
365 static async getStats (strategy: VideoRedundancyStrategy) {
366 const actor = await getServerActor()
371 [ Sequelize.fn('COALESCE', Sequelize.fn('SUM', Sequelize.col('VideoFile.size')), '0'), 'totalUsed' ],
372 [ Sequelize.fn('COUNT', Sequelize.fn('DISTINCT', Sequelize.col('videoId'))), 'totalVideos' ],
373 [ Sequelize.fn('COUNT', Sequelize.col('videoFileId')), 'totalVideoFiles' ]
382 model: VideoFileModel,
388 return VideoRedundancyModel.find(query as any) // FIXME: typings
390 totalUsed: parseInt(r.totalUsed.toString(), 10),
391 totalVideos: r.totalVideos,
392 totalVideoFiles: r.totalVideoFiles
396 toActivityPubObject (): CacheFileObject {
399 type: 'CacheFile' as 'CacheFile',
400 object: this.VideoFile.Video.url,
401 expires: this.expiresOn.toISOString(),
404 mimeType: VIDEO_EXT_MIMETYPE[ this.VideoFile.extname ] as any,
406 height: this.VideoFile.resolution,
407 size: this.VideoFile.size,
408 fps: this.VideoFile.fps
413 // Don't include video files we already duplicated
414 private static async buildVideoFileForDuplication () {
415 const actor = await getServerActor()
417 const notIn = Sequelize.literal(
419 `SELECT "videoFileId" FROM "videoRedundancy" WHERE "actorId" = ${actor.id}` +
425 model: VideoFileModel.unscoped(),
429 [ Sequelize.Op.notIn ]: notIn
435 private static buildServerRedundancyInclude () {
438 model: VideoChannelModel.unscoped(),
443 model: ActorModel.unscoped(),
448 model: ServerModel.unscoped(),
451 redundancyAllowed: true