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 getVideoSample (p: Bluebird<VideoModel[]>) {
151 const ids = rows.map(r => r.id)
152 const id = sample(ids)
154 return VideoModel.loadWithFile(id, undefined, !isTestInstance())
157 static async findMostViewToDuplicate (randomizedFactor: number) {
160 attributes: [ 'id', 'views' ],
161 limit: randomizedFactor,
162 order: getVideoSort('-views'),
164 privacy: VideoPrivacy.PUBLIC
167 await VideoRedundancyModel.buildVideoFileForDuplication(),
168 VideoRedundancyModel.buildServerRedundancyInclude()
172 return VideoRedundancyModel.getVideoSample(VideoModel.unscoped().findAll(query))
175 static async findTrendingToDuplicate (randomizedFactor: number) {
178 attributes: [ 'id', 'views' ],
180 group: 'VideoModel.id',
181 limit: randomizedFactor,
182 order: getVideoSort('-trending'),
184 privacy: VideoPrivacy.PUBLIC
187 await VideoRedundancyModel.buildVideoFileForDuplication(),
188 VideoRedundancyModel.buildServerRedundancyInclude(),
190 VideoModel.buildTrendingQuery(CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS)
194 return VideoRedundancyModel.getVideoSample(VideoModel.unscoped().findAll(query))
197 static async findRecentlyAddedToDuplicate (randomizedFactor: number, minViews: number) {
200 attributes: [ 'id', 'publishedAt' ],
201 limit: randomizedFactor,
202 order: getVideoSort('-publishedAt'),
204 privacy: VideoPrivacy.PUBLIC,
206 [ Sequelize.Op.gte ]: minViews
210 await VideoRedundancyModel.buildVideoFileForDuplication(),
211 VideoRedundancyModel.buildServerRedundancyInclude()
215 return VideoRedundancyModel.getVideoSample(VideoModel.unscoped().findAll(query))
218 static async loadOldestLocalThatAlreadyExpired (strategy: VideoRedundancyStrategy, expiresAfterMs: number) {
219 const expiredDate = new Date()
220 expiredDate.setMilliseconds(expiredDate.getMilliseconds() - expiresAfterMs)
222 const actor = await getServerActor()
229 [ Sequelize.Op.lt ]: expiredDate
234 return VideoRedundancyModel.scope([ ScopeNames.WITH_VIDEO ]).findOne(query)
237 static async getTotalDuplicated (strategy: VideoRedundancyStrategy) {
238 const actor = await getServerActor()
244 model: VideoRedundancyModel,
254 return VideoFileModel.sum('size', options as any) // FIXME: typings
257 static async listLocalExpired () {
258 const actor = await getServerActor()
264 [ Sequelize.Op.lt ]: new Date()
269 return VideoRedundancyModel.scope([ ScopeNames.WITH_VIDEO ]).findAll(query)
272 static async listRemoteExpired () {
273 const actor = await getServerActor()
278 [Sequelize.Op.ne]: actor.id
281 [ Sequelize.Op.lt ]: new Date()
286 return VideoRedundancyModel.scope([ ScopeNames.WITH_VIDEO ]).findAll(query)
289 static async getStats (strategy: VideoRedundancyStrategy) {
290 const actor = await getServerActor()
295 [ Sequelize.fn('COALESCE', Sequelize.fn('SUM', Sequelize.col('VideoFile.size')), '0'), 'totalUsed' ],
296 [ Sequelize.fn('COUNT', Sequelize.fn('DISTINCT', Sequelize.col('videoId'))), 'totalVideos' ],
297 [ Sequelize.fn('COUNT', Sequelize.col('videoFileId')), 'totalVideoFiles' ]
306 model: VideoFileModel,
312 return VideoRedundancyModel.find(query as any) // FIXME: typings
314 totalUsed: parseInt(r.totalUsed.toString(), 10),
315 totalVideos: r.totalVideos,
316 totalVideoFiles: r.totalVideoFiles
320 toActivityPubObject (): CacheFileObject {
323 type: 'CacheFile' as 'CacheFile',
324 object: this.VideoFile.Video.url,
325 expires: this.expiresOn.toISOString(),
328 mimeType: VIDEO_EXT_MIMETYPE[ this.VideoFile.extname ] as any,
330 height: this.VideoFile.resolution,
331 size: this.VideoFile.size,
332 fps: this.VideoFile.fps
337 // Don't include video files we already duplicated
338 private static async buildVideoFileForDuplication () {
339 const actor = await getServerActor()
341 const notIn = Sequelize.literal(
343 `SELECT "videoFileId" FROM "videoRedundancy" WHERE "actorId" = ${actor.id}` +
349 model: VideoFileModel.unscoped(),
353 [ Sequelize.Op.notIn ]: notIn
359 private static buildServerRedundancyInclude () {
362 model: VideoChannelModel.unscoped(),
367 model: ActorModel.unscoped(),
372 model: ServerModel.unscoped(),
375 redundancyAllowed: true