Merge branch 'release/1.4.0' into develop
[oweals/peertube.git] / server / models / redundancy / video-redundancy.ts
1 import {
2   AllowNull,
3   BeforeDestroy,
4   BelongsTo,
5   Column,
6   CreatedAt,
7   DataType,
8   ForeignKey,
9   Is,
10   Model,
11   Scopes,
12   Table,
13   UpdatedAt
14 } from 'sequelize-typescript'
15 import { ActorModel } from '../activitypub/actor'
16 import { getVideoSort, parseAggregateResult, throwIfNotValid } from '../utils'
17 import { isActivityPubUrlValid, isUrlValid } from '../../helpers/custom-validators/activitypub/misc'
18 import { CONSTRAINTS_FIELDS, MIMETYPES } from '../../initializers/constants'
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 { col, FindOptions, fn, literal, Op, Transaction } from 'sequelize'
31 import { VideoStreamingPlaylistModel } from '../video/video-streaming-playlist'
32 import { CONFIG } from '../../initializers/config'
33 import { MVideoRedundancy, MVideoRedundancyAP, MVideoRedundancyVideo } from '@server/typings/models'
34
35 export enum ScopeNames {
36   WITH_VIDEO = 'WITH_VIDEO'
37 }
38
39 @Scopes(() => ({
40   [ ScopeNames.WITH_VIDEO ]: {
41     include: [
42       {
43         model: VideoFileModel,
44         required: false,
45         include: [
46           {
47             model: VideoModel,
48             required: true
49           }
50         ]
51       },
52       {
53         model: VideoStreamingPlaylistModel,
54         required: false,
55         include: [
56           {
57             model: VideoModel,
58             required: true
59           }
60         ]
61       }
62     ]
63   }
64 }))
65
66 @Table({
67   tableName: 'videoRedundancy',
68   indexes: [
69     {
70       fields: [ 'videoFileId' ]
71     },
72     {
73       fields: [ 'actorId' ]
74     },
75     {
76       fields: [ 'url' ],
77       unique: true
78     }
79   ]
80 })
81 export class VideoRedundancyModel extends Model<VideoRedundancyModel> {
82
83   @CreatedAt
84   createdAt: Date
85
86   @UpdatedAt
87   updatedAt: Date
88
89   @AllowNull(false)
90   @Column
91   expiresOn: Date
92
93   @AllowNull(false)
94   @Is('VideoRedundancyFileUrl', value => throwIfNotValid(value, isUrlValid, 'fileUrl'))
95   @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS_REDUNDANCY.URL.max))
96   fileUrl: string
97
98   @AllowNull(false)
99   @Is('VideoRedundancyUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
100   @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS_REDUNDANCY.URL.max))
101   url: string
102
103   @AllowNull(true)
104   @Column
105   strategy: string // Only used by us
106
107   @ForeignKey(() => VideoFileModel)
108   @Column
109   videoFileId: number
110
111   @BelongsTo(() => VideoFileModel, {
112     foreignKey: {
113       allowNull: true
114     },
115     onDelete: 'cascade'
116   })
117   VideoFile: VideoFileModel
118
119   @ForeignKey(() => VideoStreamingPlaylistModel)
120   @Column
121   videoStreamingPlaylistId: number
122
123   @BelongsTo(() => VideoStreamingPlaylistModel, {
124     foreignKey: {
125       allowNull: true
126     },
127     onDelete: 'cascade'
128   })
129   VideoStreamingPlaylist: VideoStreamingPlaylistModel
130
131   @ForeignKey(() => ActorModel)
132   @Column
133   actorId: number
134
135   @BelongsTo(() => ActorModel, {
136     foreignKey: {
137       allowNull: false
138     },
139     onDelete: 'cascade'
140   })
141   Actor: ActorModel
142
143   @BeforeDestroy
144   static async removeFile (instance: VideoRedundancyModel) {
145     if (!instance.isOwned()) return
146
147     if (instance.videoFileId) {
148       const videoFile = await VideoFileModel.loadWithVideo(instance.videoFileId)
149
150       const logIdentifier = `${videoFile.Video.uuid}-${videoFile.resolution}`
151       logger.info('Removing duplicated video file %s.', logIdentifier)
152
153       videoFile.Video.removeFile(videoFile, true)
154                .catch(err => logger.error('Cannot delete %s files.', logIdentifier, { err }))
155     }
156
157     if (instance.videoStreamingPlaylistId) {
158       const videoStreamingPlaylist = await VideoStreamingPlaylistModel.loadWithVideo(instance.videoStreamingPlaylistId)
159
160       const videoUUID = videoStreamingPlaylist.Video.uuid
161       logger.info('Removing duplicated video streaming playlist %s.', videoUUID)
162
163       videoStreamingPlaylist.Video.removeStreamingPlaylist(true)
164                .catch(err => logger.error('Cannot delete video streaming playlist files of %s.', videoUUID, { err }))
165     }
166
167     return undefined
168   }
169
170   static async loadLocalByFileId (videoFileId: number): Promise<MVideoRedundancyVideo> {
171     const actor = await getServerActor()
172
173     const query = {
174       where: {
175         actorId: actor.id,
176         videoFileId
177       }
178     }
179
180     return VideoRedundancyModel.scope(ScopeNames.WITH_VIDEO).findOne(query)
181   }
182
183   static async loadLocalByStreamingPlaylistId (videoStreamingPlaylistId: number): Promise<MVideoRedundancyVideo> {
184     const actor = await getServerActor()
185
186     const query = {
187       where: {
188         actorId: actor.id,
189         videoStreamingPlaylistId
190       }
191     }
192
193     return VideoRedundancyModel.scope(ScopeNames.WITH_VIDEO).findOne(query)
194   }
195
196   static loadByUrl (url: string, transaction?: Transaction): Bluebird<MVideoRedundancy> {
197     const query = {
198       where: {
199         url
200       },
201       transaction
202     }
203
204     return VideoRedundancyModel.findOne(query)
205   }
206
207   static async isLocalByVideoUUIDExists (uuid: string) {
208     const actor = await getServerActor()
209
210     const query = {
211       raw: true,
212       attributes: [ 'id' ],
213       where: {
214         actorId: actor.id
215       },
216       include: [
217         {
218           attributes: [ ],
219           model: VideoFileModel,
220           required: true,
221           include: [
222             {
223               attributes: [ ],
224               model: VideoModel,
225               required: true,
226               where: {
227                 uuid
228               }
229             }
230           ]
231         }
232       ]
233     }
234
235     return VideoRedundancyModel.findOne(query)
236       .then(r => !!r)
237   }
238
239   static async getVideoSample (p: Bluebird<VideoModel[]>) {
240     const rows = await p
241     if (rows.length === 0) return undefined
242
243     const ids = rows.map(r => r.id)
244     const id = sample(ids)
245
246     return VideoModel.loadWithFiles(id, undefined, !isTestInstance())
247   }
248
249   static async findMostViewToDuplicate (randomizedFactor: number) {
250     // On VideoModel!
251     const query = {
252       attributes: [ 'id', 'views' ],
253       limit: randomizedFactor,
254       order: getVideoSort('-views'),
255       where: {
256         privacy: VideoPrivacy.PUBLIC
257       },
258       include: [
259         await VideoRedundancyModel.buildVideoFileForDuplication(),
260         VideoRedundancyModel.buildServerRedundancyInclude()
261       ]
262     }
263
264     return VideoRedundancyModel.getVideoSample(VideoModel.unscoped().findAll(query))
265   }
266
267   static async findTrendingToDuplicate (randomizedFactor: number) {
268     // On VideoModel!
269     const query = {
270       attributes: [ 'id', 'views' ],
271       subQuery: false,
272       group: 'VideoModel.id',
273       limit: randomizedFactor,
274       order: getVideoSort('-trending'),
275       where: {
276         privacy: VideoPrivacy.PUBLIC
277       },
278       include: [
279         await VideoRedundancyModel.buildVideoFileForDuplication(),
280         VideoRedundancyModel.buildServerRedundancyInclude(),
281
282         VideoModel.buildTrendingQuery(CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS)
283       ]
284     }
285
286     return VideoRedundancyModel.getVideoSample(VideoModel.unscoped().findAll(query))
287   }
288
289   static async findRecentlyAddedToDuplicate (randomizedFactor: number, minViews: number) {
290     // On VideoModel!
291     const query = {
292       attributes: [ 'id', 'publishedAt' ],
293       limit: randomizedFactor,
294       order: getVideoSort('-publishedAt'),
295       where: {
296         privacy: VideoPrivacy.PUBLIC,
297         views: {
298           [ Op.gte ]: minViews
299         }
300       },
301       include: [
302         await VideoRedundancyModel.buildVideoFileForDuplication(),
303         VideoRedundancyModel.buildServerRedundancyInclude()
304       ]
305     }
306
307     return VideoRedundancyModel.getVideoSample(VideoModel.unscoped().findAll(query))
308   }
309
310   static async loadOldestLocalExpired (strategy: VideoRedundancyStrategy, expiresAfterMs: number): Promise<MVideoRedundancyVideo> {
311     const expiredDate = new Date()
312     expiredDate.setMilliseconds(expiredDate.getMilliseconds() - expiresAfterMs)
313
314     const actor = await getServerActor()
315
316     const query = {
317       where: {
318         actorId: actor.id,
319         strategy,
320         createdAt: {
321           [ Op.lt ]: expiredDate
322         }
323       }
324     }
325
326     return VideoRedundancyModel.scope([ ScopeNames.WITH_VIDEO ]).findOne(query)
327   }
328
329   static async getTotalDuplicated (strategy: VideoRedundancyStrategy) {
330     const actor = await getServerActor()
331     const redundancyInclude = {
332       attributes: [],
333       model: VideoRedundancyModel,
334       required: true,
335       where: {
336         actorId: actor.id,
337         strategy
338       }
339     }
340
341     const queryFiles: FindOptions = {
342       include: [ redundancyInclude ]
343     }
344
345     const queryStreamingPlaylists: FindOptions = {
346       include: [
347         {
348           attributes: [],
349           model: VideoModel.unscoped(),
350           required: true,
351           include: [
352             {
353               required: true,
354               attributes: [],
355               model: VideoStreamingPlaylistModel.unscoped(),
356               include: [
357                 redundancyInclude
358               ]
359             }
360           ]
361         }
362       ]
363     }
364
365     return Promise.all([
366       VideoFileModel.aggregate('size', 'SUM', queryFiles),
367       VideoFileModel.aggregate('size', 'SUM', queryStreamingPlaylists)
368     ]).then(([ r1, r2 ]) => {
369       return parseAggregateResult(r1) + parseAggregateResult(r2)
370     })
371   }
372
373   static async listLocalExpired () {
374     const actor = await getServerActor()
375
376     const query = {
377       where: {
378         actorId: actor.id,
379         expiresOn: {
380           [ Op.lt ]: new Date()
381         }
382       }
383     }
384
385     return VideoRedundancyModel.scope([ ScopeNames.WITH_VIDEO ]).findAll(query)
386   }
387
388   static async listRemoteExpired () {
389     const actor = await getServerActor()
390
391     const query = {
392       where: {
393         actorId: {
394           [Op.ne]: actor.id
395         },
396         expiresOn: {
397           [ Op.lt ]: new Date()
398         }
399       }
400     }
401
402     return VideoRedundancyModel.scope([ ScopeNames.WITH_VIDEO ]).findAll(query)
403   }
404
405   static async listLocalOfServer (serverId: number) {
406     const actor = await getServerActor()
407     const buildVideoInclude = () => ({
408       model: VideoModel,
409       required: true,
410       include: [
411         {
412           attributes: [],
413           model: VideoChannelModel.unscoped(),
414           required: true,
415           include: [
416             {
417               attributes: [],
418               model: ActorModel.unscoped(),
419               required: true,
420               where: {
421                 serverId
422               }
423             }
424           ]
425         }
426       ]
427     })
428
429     const query = {
430       where: {
431         actorId: actor.id
432       },
433       include: [
434         {
435           model: VideoFileModel,
436           required: false,
437           include: [ buildVideoInclude() ]
438         },
439         {
440           model: VideoStreamingPlaylistModel,
441           required: false,
442           include: [ buildVideoInclude() ]
443         }
444       ]
445     }
446
447     return VideoRedundancyModel.findAll(query)
448   }
449
450   static async getStats (strategy: VideoRedundancyStrategy) {
451     const actor = await getServerActor()
452
453     const query: FindOptions = {
454       raw: true,
455       attributes: [
456         [ fn('COALESCE', fn('SUM', col('VideoFile.size')), '0'), 'totalUsed' ],
457         [ fn('COUNT', fn('DISTINCT', col('videoId'))), 'totalVideos' ],
458         [ fn('COUNT', col('videoFileId')), 'totalVideoFiles' ]
459       ],
460       where: {
461         strategy,
462         actorId: actor.id
463       },
464       include: [
465         {
466           attributes: [],
467           model: VideoFileModel,
468           required: true
469         }
470       ]
471     }
472
473     return VideoRedundancyModel.findOne(query)
474       .then((r: any) => ({
475         totalUsed: parseAggregateResult(r.totalUsed),
476         totalVideos: r.totalVideos,
477         totalVideoFiles: r.totalVideoFiles
478       }))
479   }
480
481   getVideo () {
482     if (this.VideoFile) return this.VideoFile.Video
483
484     return this.VideoStreamingPlaylist.Video
485   }
486
487   isOwned () {
488     return !!this.strategy
489   }
490
491   toActivityPubObject (this: MVideoRedundancyAP): CacheFileObject {
492     if (this.VideoStreamingPlaylist) {
493       return {
494         id: this.url,
495         type: 'CacheFile' as 'CacheFile',
496         object: this.VideoStreamingPlaylist.Video.url,
497         expires: this.expiresOn.toISOString(),
498         url: {
499           type: 'Link',
500           mimeType: 'application/x-mpegURL',
501           mediaType: 'application/x-mpegURL',
502           href: this.fileUrl
503         }
504       }
505     }
506
507     return {
508       id: this.url,
509       type: 'CacheFile' as 'CacheFile',
510       object: this.VideoFile.Video.url,
511       expires: this.expiresOn.toISOString(),
512       url: {
513         type: 'Link',
514         mimeType: MIMETYPES.VIDEO.EXT_MIMETYPE[ this.VideoFile.extname ] as any,
515         mediaType: MIMETYPES.VIDEO.EXT_MIMETYPE[ this.VideoFile.extname ] as any,
516         href: this.fileUrl,
517         height: this.VideoFile.resolution,
518         size: this.VideoFile.size,
519         fps: this.VideoFile.fps
520       }
521     }
522   }
523
524   // Don't include video files we already duplicated
525   private static async buildVideoFileForDuplication () {
526     const actor = await getServerActor()
527
528     const notIn = literal(
529       '(' +
530         `SELECT "videoFileId" FROM "videoRedundancy" WHERE "actorId" = ${actor.id} AND "videoFileId" IS NOT NULL` +
531       ')'
532     )
533
534     return {
535       attributes: [],
536       model: VideoFileModel.unscoped(),
537       required: true,
538       where: {
539         id: {
540           [ Op.notIn ]: notIn
541         }
542       }
543     }
544   }
545
546   private static buildServerRedundancyInclude () {
547     return {
548       attributes: [],
549       model: VideoChannelModel.unscoped(),
550       required: true,
551       include: [
552         {
553           attributes: [],
554           model: ActorModel.unscoped(),
555           required: true,
556           include: [
557             {
558               attributes: [],
559               model: ServerModel.unscoped(),
560               required: true,
561               where: {
562                 redundancyAllowed: true
563               }
564             }
565           ]
566         }
567       ]
568     }
569   }
570 }