15 } from 'sequelize-typescript'
16 import { ActorModel } from '../activitypub/actor'
17 import { getVideoSort, throwIfNotValid } from '../utils'
18 import { isActivityPubUrlValid, isUrlValid } from '../../helpers/custom-validators/activitypub/misc'
19 import { CONFIG, CONSTRAINTS_FIELDS, VIDEO_EXT_MIMETYPE } from '../../initializers'
20 import { VideoFileModel } from '../video/video-file'
21 import { getServerActor } from '../../helpers/utils'
22 import { VideoModel } from '../video/video'
23 import { VideoRedundancyStrategy } from '../../../shared/models/redundancy'
24 import { logger } from '../../helpers/logger'
25 import { CacheFileObject } from '../../../shared'
26 import { VideoChannelModel } from '../video/video-channel'
27 import { ServerModel } from '../server/server'
28 import { sample } from 'lodash'
29 import { isTestInstance } from '../../helpers/core-utils'
30 import * as Bluebird from 'bluebird'
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 removeFilesAndSendDelete (instance: VideoRedundancyModel) {
121 if (!instance.strategy) return
123 logger.info('Removing video file %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) {
145 return VideoRedundancyModel.findOne(query)
148 static async getVideoSample (p: Bluebird<VideoModel[]>) {
150 const ids = rows.map(r => r.id)
151 const id = sample(ids)
153 return VideoModel.loadWithFile(id, undefined, !isTestInstance())
156 static async findMostViewToDuplicate (randomizedFactor: number) {
159 attributes: [ 'id', 'views' ],
160 logging: !isTestInstance(),
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 logging: !isTestInstance(),
178 group: 'VideoModel.id',
179 limit: randomizedFactor,
180 order: getVideoSort('-trending'),
182 await VideoRedundancyModel.buildVideoFileForDuplication(),
183 VideoRedundancyModel.buildServerRedundancyInclude(),
185 VideoModel.buildTrendingQuery(CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS)
189 return VideoRedundancyModel.getVideoSample(VideoModel.unscoped().findAll(query))
192 static async findRecentlyAddedToDuplicate (randomizedFactor: number, minViews: number) {
195 attributes: [ 'id', 'publishedAt' ],
196 logging: !isTestInstance(),
197 limit: randomizedFactor,
198 order: getVideoSort('-publishedAt'),
201 [ Sequelize.Op.gte ]: minViews
205 await VideoRedundancyModel.buildVideoFileForDuplication(),
206 VideoRedundancyModel.buildServerRedundancyInclude()
210 return VideoRedundancyModel.getVideoSample(VideoModel.unscoped().findAll(query))
213 static async getTotalDuplicated (strategy: VideoRedundancyStrategy) {
214 const actor = await getServerActor()
217 logging: !isTestInstance(),
221 model: VideoRedundancyModel,
231 return VideoFileModel.sum('size', options)
234 static listAllExpired () {
236 logging: !isTestInstance(),
239 [ Sequelize.Op.lt ]: new Date()
244 return VideoRedundancyModel.scope(ScopeNames.WITH_VIDEO)
248 static async getStats (strategy: VideoRedundancyStrategy) {
249 const actor = await getServerActor()
254 [ Sequelize.fn('COALESCE', Sequelize.fn('SUM', Sequelize.col('VideoFile.size')), '0'), 'totalUsed' ],
255 [ Sequelize.fn('COUNT', Sequelize.fn('DISTINCT', 'videoId')), 'totalVideos' ],
256 [ Sequelize.fn('COUNT', 'videoFileId'), 'totalVideoFiles' ]
265 model: VideoFileModel,
271 return VideoRedundancyModel.find(query as any) // FIXME: typings
273 totalUsed: parseInt(r.totalUsed.toString(), 10),
274 totalVideos: r.totalVideos,
275 totalVideoFiles: r.totalVideoFiles
279 toActivityPubObject (): CacheFileObject {
282 type: 'CacheFile' as 'CacheFile',
283 object: this.VideoFile.Video.url,
284 expires: this.expiresOn.toISOString(),
287 mimeType: VIDEO_EXT_MIMETYPE[ this.VideoFile.extname ] as any,
289 height: this.VideoFile.resolution,
290 size: this.VideoFile.size,
291 fps: this.VideoFile.fps
296 // Don't include video files we already duplicated
297 private static async buildVideoFileForDuplication () {
298 const actor = await getServerActor()
300 const notIn = Sequelize.literal(
302 `SELECT "videoFileId" FROM "videoRedundancy" WHERE "actorId" = ${actor.id} AND "expiresOn" >= NOW()` +
308 model: VideoFileModel.unscoped(),
312 [ Sequelize.Op.notIn ]: notIn
318 private static buildServerRedundancyInclude () {
321 model: VideoChannelModel.unscoped(),
326 model: ActorModel.unscoped(),
331 model: ServerModel.unscoped(),
334 redundancyAllowed: true