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 } 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 await VideoRedundancyModel.buildVideoFileForDuplication(),
165 VideoRedundancyModel.buildServerRedundancyInclude()
169 return VideoRedundancyModel.getVideoSample(VideoModel.unscoped().findAll(query))
172 static async findTrendingToDuplicate (randomizedFactor: number) {
175 attributes: [ 'id', 'views' ],
177 group: 'VideoModel.id',
178 limit: randomizedFactor,
179 order: getVideoSort('-trending'),
181 await VideoRedundancyModel.buildVideoFileForDuplication(),
182 VideoRedundancyModel.buildServerRedundancyInclude(),
184 VideoModel.buildTrendingQuery(CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS)
188 return VideoRedundancyModel.getVideoSample(VideoModel.unscoped().findAll(query))
191 static async findRecentlyAddedToDuplicate (randomizedFactor: number, minViews: number) {
194 attributes: [ 'id', 'publishedAt' ],
195 limit: randomizedFactor,
196 order: getVideoSort('-publishedAt'),
199 [ Sequelize.Op.gte ]: minViews
203 await VideoRedundancyModel.buildVideoFileForDuplication(),
204 VideoRedundancyModel.buildServerRedundancyInclude()
208 return VideoRedundancyModel.getVideoSample(VideoModel.unscoped().findAll(query))
211 static async loadOldestLocalThatAlreadyExpired (strategy: VideoRedundancyStrategy, expiresAfterMs: number) {
212 const expiredDate = new Date()
213 expiredDate.setMilliseconds(expiredDate.getMilliseconds() - expiresAfterMs)
215 const actor = await getServerActor()
222 [ Sequelize.Op.lt ]: expiredDate
227 return VideoRedundancyModel.scope([ ScopeNames.WITH_VIDEO ]).findOne(query)
230 static async getTotalDuplicated (strategy: VideoRedundancyStrategy) {
231 const actor = await getServerActor()
237 model: VideoRedundancyModel,
247 return VideoFileModel.sum('size', options as any) // FIXME: typings
250 static async listLocalExpired () {
251 const actor = await getServerActor()
257 [ Sequelize.Op.lt ]: new Date()
262 return VideoRedundancyModel.scope([ ScopeNames.WITH_VIDEO ]).findAll(query)
265 static async listRemoteExpired () {
266 const actor = await getServerActor()
271 [Sequelize.Op.ne]: actor.id
274 [ Sequelize.Op.lt ]: new Date()
279 return VideoRedundancyModel.scope([ ScopeNames.WITH_VIDEO ]).findAll(query)
282 static async getStats (strategy: VideoRedundancyStrategy) {
283 const actor = await getServerActor()
288 [ Sequelize.fn('COALESCE', Sequelize.fn('SUM', Sequelize.col('VideoFile.size')), '0'), 'totalUsed' ],
289 [ Sequelize.fn('COUNT', Sequelize.fn('DISTINCT', Sequelize.col('videoId'))), 'totalVideos' ],
290 [ Sequelize.fn('COUNT', Sequelize.col('videoFileId')), 'totalVideoFiles' ]
299 model: VideoFileModel,
305 return VideoRedundancyModel.find(query as any) // FIXME: typings
307 totalUsed: parseInt(r.totalUsed.toString(), 10),
308 totalVideos: r.totalVideos,
309 totalVideoFiles: r.totalVideoFiles
313 toActivityPubObject (): CacheFileObject {
316 type: 'CacheFile' as 'CacheFile',
317 object: this.VideoFile.Video.url,
318 expires: this.expiresOn.toISOString(),
321 mimeType: VIDEO_EXT_MIMETYPE[ this.VideoFile.extname ] as any,
323 height: this.VideoFile.resolution,
324 size: this.VideoFile.size,
325 fps: this.VideoFile.fps
330 // Don't include video files we already duplicated
331 private static async buildVideoFileForDuplication () {
332 const actor = await getServerActor()
334 const notIn = Sequelize.literal(
336 `SELECT "videoFileId" FROM "videoRedundancy" WHERE "actorId" = ${actor.id}` +
342 model: VideoFileModel.unscoped(),
346 [ Sequelize.Op.notIn ]: notIn
352 private static buildServerRedundancyInclude () {
355 model: VideoChannelModel.unscoped(),
360 model: ActorModel.unscoped(),
365 model: ServerModel.unscoped(),
368 redundancyAllowed: true