]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/models/redundancy/video-redundancy.ts
Merge branch 'release/1.4.0' into develop
[github/Chocobozzz/PeerTube.git] / server / models / redundancy / video-redundancy.ts
CommitLineData
c48e82b5 1import {
c48e82b5 2 AllowNull,
25378bc8 3 BeforeDestroy,
c48e82b5
C
4 BelongsTo,
5 Column,
6 CreatedAt,
7 DataType,
8 ForeignKey,
9 Is,
10 Model,
11 Scopes,
c48e82b5
C
12 Table,
13 UpdatedAt
14} from 'sequelize-typescript'
15import { ActorModel } from '../activitypub/actor'
3acc5084 16import { getVideoSort, parseAggregateResult, throwIfNotValid } from '../utils'
c48e82b5 17import { isActivityPubUrlValid, isUrlValid } from '../../helpers/custom-validators/activitypub/misc'
74dc3bca 18import { CONSTRAINTS_FIELDS, MIMETYPES } from '../../initializers/constants'
c48e82b5 19import { VideoFileModel } from '../video/video-file'
c48e82b5
C
20import { getServerActor } from '../../helpers/utils'
21import { VideoModel } from '../video/video'
22import { VideoRedundancyStrategy } from '../../../shared/models/redundancy'
23import { logger } from '../../helpers/logger'
4a08f669 24import { CacheFileObject, VideoPrivacy } from '../../../shared'
c48e82b5
C
25import { VideoChannelModel } from '../video/video-channel'
26import { ServerModel } from '../server/server'
27import { sample } from 'lodash'
28import { isTestInstance } from '../../helpers/core-utils'
3f6b6a56 29import * as Bluebird from 'bluebird'
3acc5084 30import { col, FindOptions, fn, literal, Op, Transaction } from 'sequelize'
09209296 31import { VideoStreamingPlaylistModel } from '../video/video-streaming-playlist'
6dd9de95 32import { CONFIG } from '../../initializers/config'
b5fecbf4 33import { MVideoRedundancy, MVideoRedundancyAP, MVideoRedundancyVideo } from '@server/typings/models'
c48e82b5
C
34
35export enum ScopeNames {
36 WITH_VIDEO = 'WITH_VIDEO'
37}
38
3acc5084 39@Scopes(() => ({
c48e82b5
C
40 [ ScopeNames.WITH_VIDEO ]: {
41 include: [
42 {
3acc5084 43 model: VideoFileModel,
09209296
C
44 required: false,
45 include: [
46 {
3acc5084 47 model: VideoModel,
09209296
C
48 required: true
49 }
50 ]
51 },
52 {
3acc5084 53 model: VideoStreamingPlaylistModel,
09209296 54 required: false,
c48e82b5
C
55 include: [
56 {
3acc5084 57 model: VideoModel,
c48e82b5
C
58 required: true
59 }
60 ]
61 }
3acc5084 62 ]
c48e82b5 63 }
3acc5084 64}))
c48e82b5
C
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})
81export 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: {
09209296 113 allowNull: true
c48e82b5
C
114 },
115 onDelete: 'cascade'
116 })
117 VideoFile: VideoFileModel
118
09209296
C
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
c48e82b5
C
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
25378bc8
C
143 @BeforeDestroy
144 static async removeFile (instance: VideoRedundancyModel) {
8d1fa36a 145 if (!instance.isOwned()) return
c48e82b5 146
09209296
C
147 if (instance.videoFileId) {
148 const videoFile = await VideoFileModel.loadWithVideo(instance.videoFileId)
c48e82b5 149
09209296
C
150 const logIdentifier = `${videoFile.Video.uuid}-${videoFile.resolution}`
151 logger.info('Removing duplicated video file %s.', logIdentifier)
25378bc8 152
09209296
C
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 }
d0ae9490
C
166
167 return undefined
c48e82b5
C
168 }
169
453e83ea 170 static async loadLocalByFileId (videoFileId: number): Promise<MVideoRedundancyVideo> {
46f8d69b
C
171 const actor = await getServerActor()
172
c48e82b5
C
173 const query = {
174 where: {
46f8d69b 175 actorId: actor.id,
c48e82b5
C
176 videoFileId
177 }
178 }
179
180 return VideoRedundancyModel.scope(ScopeNames.WITH_VIDEO).findOne(query)
181 }
182
453e83ea 183 static async loadLocalByStreamingPlaylistId (videoStreamingPlaylistId: number): Promise<MVideoRedundancyVideo> {
09209296
C
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
453e83ea 196 static loadByUrl (url: string, transaction?: Transaction): Bluebird<MVideoRedundancy> {
c48e82b5
C
197 const query = {
198 where: {
199 url
e5565833
C
200 },
201 transaction
c48e82b5
C
202 }
203
204 return VideoRedundancyModel.findOne(query)
205 }
206
5ce1208a
C
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
3f6b6a56
C
239 static async getVideoSample (p: Bluebird<VideoModel[]>) {
240 const rows = await p
9e3e3617
C
241 if (rows.length === 0) return undefined
242
b36f41ca
C
243 const ids = rows.map(r => r.id)
244 const id = sample(ids)
245
09209296 246 return VideoModel.loadWithFiles(id, undefined, !isTestInstance())
b36f41ca
C
247 }
248
c48e82b5
C
249 static async findMostViewToDuplicate (randomizedFactor: number) {
250 // On VideoModel!
251 const query = {
b36f41ca 252 attributes: [ 'id', 'views' ],
c48e82b5 253 limit: randomizedFactor,
b36f41ca 254 order: getVideoSort('-views'),
4a08f669
C
255 where: {
256 privacy: VideoPrivacy.PUBLIC
257 },
c48e82b5 258 include: [
b36f41ca
C
259 await VideoRedundancyModel.buildVideoFileForDuplication(),
260 VideoRedundancyModel.buildServerRedundancyInclude()
261 ]
262 }
263
3f6b6a56 264 return VideoRedundancyModel.getVideoSample(VideoModel.unscoped().findAll(query))
b36f41ca
C
265 }
266
267 static async findTrendingToDuplicate (randomizedFactor: number) {
268 // On VideoModel!
269 const query = {
270 attributes: [ 'id', 'views' ],
271 subQuery: false,
b36f41ca
C
272 group: 'VideoModel.id',
273 limit: randomizedFactor,
274 order: getVideoSort('-trending'),
4a08f669
C
275 where: {
276 privacy: VideoPrivacy.PUBLIC
277 },
b36f41ca
C
278 include: [
279 await VideoRedundancyModel.buildVideoFileForDuplication(),
280 VideoRedundancyModel.buildServerRedundancyInclude(),
281
282 VideoModel.buildTrendingQuery(CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS)
c48e82b5
C
283 ]
284 }
285
3f6b6a56
C
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' ],
3f6b6a56
C
293 limit: randomizedFactor,
294 order: getVideoSort('-publishedAt'),
295 where: {
4a08f669 296 privacy: VideoPrivacy.PUBLIC,
3f6b6a56 297 views: {
3acc5084 298 [ Op.gte ]: minViews
3f6b6a56
C
299 }
300 },
301 include: [
302 await VideoRedundancyModel.buildVideoFileForDuplication(),
303 VideoRedundancyModel.buildServerRedundancyInclude()
304 ]
305 }
c48e82b5 306
3f6b6a56 307 return VideoRedundancyModel.getVideoSample(VideoModel.unscoped().findAll(query))
c48e82b5
C
308 }
309
453e83ea 310 static async loadOldestLocalExpired (strategy: VideoRedundancyStrategy, expiresAfterMs: number): Promise<MVideoRedundancyVideo> {
e5565833
C
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: {
3acc5084 321 [ Op.lt ]: expiredDate
e5565833
C
322 }
323 }
324 }
325
326 return VideoRedundancyModel.scope([ ScopeNames.WITH_VIDEO ]).findOne(query)
327 }
328
3f6b6a56 329 static async getTotalDuplicated (strategy: VideoRedundancyStrategy) {
c48e82b5 330 const actor = await getServerActor()
0b353d1d
C
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 }
c48e82b5 344
0b353d1d 345 const queryStreamingPlaylists: FindOptions = {
3f6b6a56
C
346 include: [
347 {
348 attributes: [],
0b353d1d 349 model: VideoModel.unscoped(),
3f6b6a56 350 required: true,
0b353d1d
C
351 include: [
352 {
9e3e3617 353 required: true,
0b353d1d
C
354 attributes: [],
355 model: VideoStreamingPlaylistModel.unscoped(),
356 include: [
357 redundancyInclude
358 ]
359 }
360 ]
3f6b6a56
C
361 }
362 ]
c48e82b5
C
363 }
364
0b353d1d
C
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 })
c48e82b5
C
371 }
372
e5565833
C
373 static async listLocalExpired () {
374 const actor = await getServerActor()
375
376 const query = {
377 where: {
378 actorId: actor.id,
379 expiresOn: {
3acc5084 380 [ Op.lt ]: new Date()
e5565833
C
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
c48e82b5 391 const query = {
c48e82b5 392 where: {
e5565833 393 actorId: {
3acc5084 394 [Op.ne]: actor.id
e5565833 395 },
c48e82b5 396 expiresOn: {
3acc5084 397 [ Op.lt ]: new Date()
c48e82b5
C
398 }
399 }
400 }
401
e5565833 402 return VideoRedundancyModel.scope([ ScopeNames.WITH_VIDEO ]).findAll(query)
c48e82b5
C
403 }
404
161b061d
C
405 static async listLocalOfServer (serverId: number) {
406 const actor = await getServerActor()
09209296
C
407 const buildVideoInclude = () => ({
408 model: VideoModel,
409 required: true,
161b061d
C
410 include: [
411 {
09209296
C
412 attributes: [],
413 model: VideoChannelModel.unscoped(),
161b061d
C
414 required: true,
415 include: [
416 {
09209296
C
417 attributes: [],
418 model: ActorModel.unscoped(),
161b061d 419 required: true,
09209296
C
420 where: {
421 serverId
422 }
161b061d
C
423 }
424 ]
425 }
426 ]
09209296
C
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 ]
161b061d
C
445 }
446
447 return VideoRedundancyModel.findAll(query)
448 }
449
4b5384f6
C
450 static async getStats (strategy: VideoRedundancyStrategy) {
451 const actor = await getServerActor()
452
3acc5084 453 const query: FindOptions = {
4b5384f6
C
454 raw: true,
455 attributes: [
3acc5084
C
456 [ fn('COALESCE', fn('SUM', col('VideoFile.size')), '0'), 'totalUsed' ],
457 [ fn('COUNT', fn('DISTINCT', col('videoId'))), 'totalVideos' ],
458 [ fn('COUNT', col('videoFileId')), 'totalVideoFiles' ]
4b5384f6
C
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
3acc5084 473 return VideoRedundancyModel.findOne(query)
4b5384f6 474 .then((r: any) => ({
3acc5084 475 totalUsed: parseAggregateResult(r.totalUsed),
4b5384f6
C
476 totalVideos: r.totalVideos,
477 totalVideoFiles: r.totalVideoFiles
478 }))
479 }
480
09209296
C
481 getVideo () {
482 if (this.VideoFile) return this.VideoFile.Video
483
484 return this.VideoStreamingPlaylist.Video
485 }
486
8d1fa36a
C
487 isOwned () {
488 return !!this.strategy
489 }
490
b5fecbf4 491 toActivityPubObject (this: MVideoRedundancyAP): CacheFileObject {
09209296
C
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
c48e82b5
C
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',
14e2014a
C
514 mimeType: MIMETYPES.VIDEO.EXT_MIMETYPE[ this.VideoFile.extname ] as any,
515 mediaType: MIMETYPES.VIDEO.EXT_MIMETYPE[ this.VideoFile.extname ] as any,
c48e82b5
C
516 href: this.fileUrl,
517 height: this.VideoFile.resolution,
518 size: this.VideoFile.size,
519 fps: this.VideoFile.fps
520 }
521 }
522 }
523
b36f41ca
C
524 // Don't include video files we already duplicated
525 private static async buildVideoFileForDuplication () {
c48e82b5
C
526 const actor = await getServerActor()
527
3acc5084 528 const notIn = literal(
c48e82b5 529 '(' +
09209296 530 `SELECT "videoFileId" FROM "videoRedundancy" WHERE "actorId" = ${actor.id} AND "videoFileId" IS NOT NULL` +
c48e82b5
C
531 ')'
532 )
b36f41ca
C
533
534 return {
535 attributes: [],
536 model: VideoFileModel.unscoped(),
537 required: true,
538 where: {
539 id: {
3acc5084 540 [ Op.notIn ]: notIn
b36f41ca
C
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 }
c48e82b5
C
569 }
570}