]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/models/redundancy/video-redundancy.ts
Reducing tag input excessive padding; fixes #3915 (#3927)
[github/Chocobozzz/PeerTube.git] / server / models / redundancy / video-redundancy.ts
CommitLineData
b49f22d8 1import { sample } from 'lodash'
6949a1a1 2import { FindOptions, literal, Op, QueryTypes, Transaction, WhereOptions } from 'sequelize'
c48e82b5 3import {
c48e82b5 4 AllowNull,
25378bc8 5 BeforeDestroy,
c48e82b5
C
6 BelongsTo,
7 Column,
8 CreatedAt,
9 DataType,
10 ForeignKey,
11 Is,
12 Model,
13 Scopes,
c48e82b5
C
14 Table,
15 UpdatedAt
16} from 'sequelize-typescript'
b49f22d8 17import { getServerActor } from '@server/models/application/application'
7448551f 18import { MActor, MVideoForRedundancyAPI, MVideoRedundancy, MVideoRedundancyAP, MVideoRedundancyVideo } from '@server/types/models'
b764380a
C
19import { VideoRedundanciesTarget } from '@shared/models/redundancy/video-redundancies-filters.model'
20import {
21 FileRedundancyInformation,
22 StreamingPlaylistRedundancyInformation,
23 VideoRedundancy
24} from '@shared/models/redundancy/video-redundancy.model'
b49f22d8
C
25import { CacheFileObject, VideoPrivacy } from '../../../shared'
26import { VideoRedundancyStrategy, VideoRedundancyStrategyWithManual } from '../../../shared/models/redundancy'
27import { isTestInstance } from '../../helpers/core-utils'
28import { isActivityPubUrlValid, isUrlValid } from '../../helpers/custom-validators/activitypub/misc'
29import { logger } from '../../helpers/logger'
30import { CONFIG } from '../../initializers/config'
31import { CONSTRAINTS_FIELDS, MIMETYPES } from '../../initializers/constants'
32import { ActorModel } from '../activitypub/actor'
33import { ServerModel } from '../server/server'
34import { getSort, getVideoSort, parseAggregateResult, throwIfNotValid } from '../utils'
35import { VideoModel } from '../video/video'
36import { VideoChannelModel } from '../video/video-channel'
37import { VideoFileModel } from '../video/video-file'
38import { VideoStreamingPlaylistModel } from '../video/video-streaming-playlist'
c48e82b5
C
39
40export enum ScopeNames {
41 WITH_VIDEO = 'WITH_VIDEO'
42}
43
3acc5084 44@Scopes(() => ({
a1587156 45 [ScopeNames.WITH_VIDEO]: {
c48e82b5
C
46 include: [
47 {
3acc5084 48 model: VideoFileModel,
09209296
C
49 required: false,
50 include: [
51 {
3acc5084 52 model: VideoModel,
09209296
C
53 required: true
54 }
55 ]
56 },
57 {
3acc5084 58 model: VideoStreamingPlaylistModel,
09209296 59 required: false,
c48e82b5
C
60 include: [
61 {
3acc5084 62 model: VideoModel,
c48e82b5
C
63 required: true
64 }
65 ]
66 }
3acc5084 67 ]
c48e82b5 68 }
3acc5084 69}))
c48e82b5
C
70
71@Table({
72 tableName: 'videoRedundancy',
73 indexes: [
74 {
75 fields: [ 'videoFileId' ]
76 },
77 {
78 fields: [ 'actorId' ]
79 },
80 {
81 fields: [ 'url' ],
82 unique: true
83 }
84 ]
85})
b49f22d8 86export class VideoRedundancyModel extends Model {
c48e82b5
C
87
88 @CreatedAt
89 createdAt: Date
90
91 @UpdatedAt
92 updatedAt: Date
93
b764380a 94 @AllowNull(true)
c48e82b5
C
95 @Column
96 expiresOn: Date
97
98 @AllowNull(false)
99 @Is('VideoRedundancyFileUrl', value => throwIfNotValid(value, isUrlValid, 'fileUrl'))
100 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS_REDUNDANCY.URL.max))
101 fileUrl: string
102
103 @AllowNull(false)
104 @Is('VideoRedundancyUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
105 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS_REDUNDANCY.URL.max))
106 url: string
107
108 @AllowNull(true)
109 @Column
110 strategy: string // Only used by us
111
112 @ForeignKey(() => VideoFileModel)
113 @Column
114 videoFileId: number
115
116 @BelongsTo(() => VideoFileModel, {
117 foreignKey: {
09209296 118 allowNull: true
c48e82b5
C
119 },
120 onDelete: 'cascade'
121 })
122 VideoFile: VideoFileModel
123
09209296
C
124 @ForeignKey(() => VideoStreamingPlaylistModel)
125 @Column
126 videoStreamingPlaylistId: number
127
128 @BelongsTo(() => VideoStreamingPlaylistModel, {
129 foreignKey: {
130 allowNull: true
131 },
132 onDelete: 'cascade'
133 })
134 VideoStreamingPlaylist: VideoStreamingPlaylistModel
135
c48e82b5
C
136 @ForeignKey(() => ActorModel)
137 @Column
138 actorId: number
139
140 @BelongsTo(() => ActorModel, {
141 foreignKey: {
142 allowNull: false
143 },
144 onDelete: 'cascade'
145 })
146 Actor: ActorModel
147
25378bc8
C
148 @BeforeDestroy
149 static async removeFile (instance: VideoRedundancyModel) {
8d1fa36a 150 if (!instance.isOwned()) return
c48e82b5 151
09209296
C
152 if (instance.videoFileId) {
153 const videoFile = await VideoFileModel.loadWithVideo(instance.videoFileId)
c48e82b5 154
09209296
C
155 const logIdentifier = `${videoFile.Video.uuid}-${videoFile.resolution}`
156 logger.info('Removing duplicated video file %s.', logIdentifier)
25378bc8 157
09209296
C
158 videoFile.Video.removeFile(videoFile, true)
159 .catch(err => logger.error('Cannot delete %s files.', logIdentifier, { err }))
160 }
161
162 if (instance.videoStreamingPlaylistId) {
163 const videoStreamingPlaylist = await VideoStreamingPlaylistModel.loadWithVideo(instance.videoStreamingPlaylistId)
164
165 const videoUUID = videoStreamingPlaylist.Video.uuid
166 logger.info('Removing duplicated video streaming playlist %s.', videoUUID)
167
ffc65cbd 168 videoStreamingPlaylist.Video.removeStreamingPlaylistFiles(videoStreamingPlaylist, true)
a1587156 169 .catch(err => logger.error('Cannot delete video streaming playlist files of %s.', videoUUID, { err }))
09209296 170 }
d0ae9490
C
171
172 return undefined
c48e82b5
C
173 }
174
453e83ea 175 static async loadLocalByFileId (videoFileId: number): Promise<MVideoRedundancyVideo> {
46f8d69b
C
176 const actor = await getServerActor()
177
c48e82b5
C
178 const query = {
179 where: {
46f8d69b 180 actorId: actor.id,
c48e82b5
C
181 videoFileId
182 }
183 }
184
185 return VideoRedundancyModel.scope(ScopeNames.WITH_VIDEO).findOne(query)
186 }
187
89613cb4
C
188 static async listLocalByVideoId (videoId: number): Promise<MVideoRedundancyVideo[]> {
189 const actor = await getServerActor()
190
191 const queryStreamingPlaylist = {
192 where: {
193 actorId: actor.id
194 },
195 include: [
196 {
197 model: VideoStreamingPlaylistModel.unscoped(),
198 required: true,
199 include: [
200 {
201 model: VideoModel.unscoped(),
202 required: true,
203 where: {
204 id: videoId
205 }
206 }
207 ]
208 }
209 ]
210 }
211
212 const queryFiles = {
213 where: {
214 actorId: actor.id
215 },
216 include: [
217 {
218 model: VideoFileModel,
219 required: true,
220 include: [
221 {
222 model: VideoModel,
223 required: true,
224 where: {
225 id: videoId
226 }
227 }
228 ]
229 }
230 ]
231 }
232
233 return Promise.all([
234 VideoRedundancyModel.findAll(queryStreamingPlaylist),
235 VideoRedundancyModel.findAll(queryFiles)
236 ]).then(([ r1, r2 ]) => r1.concat(r2))
237 }
238
453e83ea 239 static async loadLocalByStreamingPlaylistId (videoStreamingPlaylistId: number): Promise<MVideoRedundancyVideo> {
09209296
C
240 const actor = await getServerActor()
241
242 const query = {
243 where: {
244 actorId: actor.id,
245 videoStreamingPlaylistId
246 }
247 }
248
249 return VideoRedundancyModel.scope(ScopeNames.WITH_VIDEO).findOne(query)
250 }
251
b49f22d8 252 static loadByIdWithVideo (id: number, transaction?: Transaction): Promise<MVideoRedundancyVideo> {
b764380a
C
253 const query = {
254 where: { id },
255 transaction
256 }
257
258 return VideoRedundancyModel.scope(ScopeNames.WITH_VIDEO).findOne(query)
259 }
260
b49f22d8 261 static loadByUrl (url: string, transaction?: Transaction): Promise<MVideoRedundancy> {
c48e82b5
C
262 const query = {
263 where: {
264 url
e5565833
C
265 },
266 transaction
c48e82b5
C
267 }
268
269 return VideoRedundancyModel.findOne(query)
270 }
271
5ce1208a
C
272 static async isLocalByVideoUUIDExists (uuid: string) {
273 const actor = await getServerActor()
274
275 const query = {
276 raw: true,
277 attributes: [ 'id' ],
278 where: {
279 actorId: actor.id
280 },
281 include: [
282 {
a1587156 283 attributes: [],
5ce1208a
C
284 model: VideoFileModel,
285 required: true,
286 include: [
287 {
a1587156 288 attributes: [],
5ce1208a
C
289 model: VideoModel,
290 required: true,
291 where: {
292 uuid
293 }
294 }
295 ]
296 }
297 ]
298 }
299
300 return VideoRedundancyModel.findOne(query)
a1587156 301 .then(r => !!r)
5ce1208a
C
302 }
303
b49f22d8 304 static async getVideoSample (p: Promise<VideoModel[]>) {
3f6b6a56 305 const rows = await p
9e3e3617
C
306 if (rows.length === 0) return undefined
307
b36f41ca
C
308 const ids = rows.map(r => r.id)
309 const id = sample(ids)
310
09209296 311 return VideoModel.loadWithFiles(id, undefined, !isTestInstance())
b36f41ca
C
312 }
313
c48e82b5 314 static async findMostViewToDuplicate (randomizedFactor: number) {
7448551f
C
315 const peertubeActor = await getServerActor()
316
c48e82b5
C
317 // On VideoModel!
318 const query = {
b36f41ca 319 attributes: [ 'id', 'views' ],
c48e82b5 320 limit: randomizedFactor,
b36f41ca 321 order: getVideoSort('-views'),
4a08f669 322 where: {
9e2b2e76 323 privacy: VideoPrivacy.PUBLIC,
7448551f
C
324 isLive: false,
325 ...this.buildVideoIdsForDuplication(peertubeActor)
4a08f669 326 },
c48e82b5 327 include: [
b36f41ca
C
328 VideoRedundancyModel.buildServerRedundancyInclude()
329 ]
330 }
331
3f6b6a56 332 return VideoRedundancyModel.getVideoSample(VideoModel.unscoped().findAll(query))
b36f41ca
C
333 }
334
335 static async findTrendingToDuplicate (randomizedFactor: number) {
7448551f
C
336 const peertubeActor = await getServerActor()
337
b36f41ca
C
338 // On VideoModel!
339 const query = {
340 attributes: [ 'id', 'views' ],
341 subQuery: false,
b36f41ca
C
342 group: 'VideoModel.id',
343 limit: randomizedFactor,
344 order: getVideoSort('-trending'),
4a08f669 345 where: {
9e2b2e76 346 privacy: VideoPrivacy.PUBLIC,
7448551f
C
347 isLive: false,
348 ...this.buildVideoIdsForDuplication(peertubeActor)
4a08f669 349 },
b36f41ca 350 include: [
b36f41ca
C
351 VideoRedundancyModel.buildServerRedundancyInclude(),
352
353 VideoModel.buildTrendingQuery(CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS)
c48e82b5
C
354 ]
355 }
356
3f6b6a56
C
357 return VideoRedundancyModel.getVideoSample(VideoModel.unscoped().findAll(query))
358 }
359
360 static async findRecentlyAddedToDuplicate (randomizedFactor: number, minViews: number) {
7448551f
C
361 const peertubeActor = await getServerActor()
362
3f6b6a56
C
363 // On VideoModel!
364 const query = {
365 attributes: [ 'id', 'publishedAt' ],
3f6b6a56
C
366 limit: randomizedFactor,
367 order: getVideoSort('-publishedAt'),
368 where: {
4a08f669 369 privacy: VideoPrivacy.PUBLIC,
9e2b2e76 370 isLive: false,
3f6b6a56 371 views: {
a1587156 372 [Op.gte]: minViews
7448551f
C
373 },
374 ...this.buildVideoIdsForDuplication(peertubeActor)
3f6b6a56
C
375 },
376 include: [
3f6b6a56
C
377 VideoRedundancyModel.buildServerRedundancyInclude()
378 ]
379 }
c48e82b5 380
3f6b6a56 381 return VideoRedundancyModel.getVideoSample(VideoModel.unscoped().findAll(query))
c48e82b5
C
382 }
383
453e83ea 384 static async loadOldestLocalExpired (strategy: VideoRedundancyStrategy, expiresAfterMs: number): Promise<MVideoRedundancyVideo> {
e5565833
C
385 const expiredDate = new Date()
386 expiredDate.setMilliseconds(expiredDate.getMilliseconds() - expiresAfterMs)
387
388 const actor = await getServerActor()
389
390 const query = {
391 where: {
392 actorId: actor.id,
393 strategy,
394 createdAt: {
a1587156 395 [Op.lt]: expiredDate
e5565833
C
396 }
397 }
398 }
399
400 return VideoRedundancyModel.scope([ ScopeNames.WITH_VIDEO ]).findOne(query)
401 }
402
3f6b6a56 403 static async getTotalDuplicated (strategy: VideoRedundancyStrategy) {
c48e82b5 404 const actor = await getServerActor()
0b353d1d
C
405 const redundancyInclude = {
406 attributes: [],
407 model: VideoRedundancyModel,
408 required: true,
409 where: {
410 actorId: actor.id,
411 strategy
412 }
413 }
414
415 const queryFiles: FindOptions = {
416 include: [ redundancyInclude ]
417 }
c48e82b5 418
0b353d1d 419 const queryStreamingPlaylists: FindOptions = {
3f6b6a56
C
420 include: [
421 {
422 attributes: [],
0b353d1d 423 model: VideoModel.unscoped(),
3f6b6a56 424 required: true,
0b353d1d
C
425 include: [
426 {
9e3e3617 427 required: true,
0b353d1d
C
428 attributes: [],
429 model: VideoStreamingPlaylistModel.unscoped(),
430 include: [
431 redundancyInclude
432 ]
433 }
434 ]
3f6b6a56
C
435 }
436 ]
c48e82b5
C
437 }
438
0b353d1d
C
439 return Promise.all([
440 VideoFileModel.aggregate('size', 'SUM', queryFiles),
441 VideoFileModel.aggregate('size', 'SUM', queryStreamingPlaylists)
442 ]).then(([ r1, r2 ]) => {
443 return parseAggregateResult(r1) + parseAggregateResult(r2)
444 })
c48e82b5
C
445 }
446
e5565833
C
447 static async listLocalExpired () {
448 const actor = await getServerActor()
449
450 const query = {
451 where: {
452 actorId: actor.id,
453 expiresOn: {
a1587156 454 [Op.lt]: new Date()
e5565833
C
455 }
456 }
457 }
458
459 return VideoRedundancyModel.scope([ ScopeNames.WITH_VIDEO ]).findAll(query)
460 }
461
462 static async listRemoteExpired () {
463 const actor = await getServerActor()
464
c48e82b5 465 const query = {
c48e82b5 466 where: {
e5565833 467 actorId: {
3acc5084 468 [Op.ne]: actor.id
e5565833 469 },
c48e82b5 470 expiresOn: {
a1587156
C
471 [Op.lt]: new Date(),
472 [Op.ne]: null
c48e82b5
C
473 }
474 }
475 }
476
e5565833 477 return VideoRedundancyModel.scope([ ScopeNames.WITH_VIDEO ]).findAll(query)
c48e82b5
C
478 }
479
161b061d
C
480 static async listLocalOfServer (serverId: number) {
481 const actor = await getServerActor()
09209296
C
482 const buildVideoInclude = () => ({
483 model: VideoModel,
484 required: true,
161b061d
C
485 include: [
486 {
09209296
C
487 attributes: [],
488 model: VideoChannelModel.unscoped(),
161b061d
C
489 required: true,
490 include: [
491 {
09209296
C
492 attributes: [],
493 model: ActorModel.unscoped(),
161b061d 494 required: true,
09209296
C
495 where: {
496 serverId
497 }
161b061d
C
498 }
499 ]
500 }
501 ]
09209296
C
502 })
503
504 const query = {
505 where: {
506 actorId: actor.id
507 },
508 include: [
509 {
510 model: VideoFileModel,
511 required: false,
512 include: [ buildVideoInclude() ]
513 },
514 {
515 model: VideoStreamingPlaylistModel,
516 required: false,
517 include: [ buildVideoInclude() ]
518 }
519 ]
161b061d
C
520 }
521
522 return VideoRedundancyModel.findAll(query)
523 }
524
b764380a 525 static listForApi (options: {
a1587156
C
526 start: number
527 count: number
528 sort: string
529 target: VideoRedundanciesTarget
b764380a
C
530 strategy?: string
531 }) {
532 const { start, count, sort, target, strategy } = options
a1587156
C
533 const redundancyWhere: WhereOptions = {}
534 const videosWhere: WhereOptions = {}
b764380a
C
535 let redundancySqlSuffix = ''
536
537 if (target === 'my-videos') {
538 Object.assign(videosWhere, { remote: false })
539 } else if (target === 'remote-videos') {
540 Object.assign(videosWhere, { remote: true })
541 Object.assign(redundancyWhere, { strategy: { [Op.ne]: null } })
542 redundancySqlSuffix = ' AND "videoRedundancy"."strategy" IS NOT NULL'
543 }
544
545 if (strategy) {
546 Object.assign(redundancyWhere, { strategy: strategy })
547 }
548
549 const videoFilterWhere = {
550 [Op.and]: [
551 {
a1587156 552 [Op.or]: [
b764380a
C
553 {
554 id: {
a1587156 555 [Op.in]: literal(
b764380a
C
556 '(' +
557 'SELECT "videoId" FROM "videoFile" ' +
558 'INNER JOIN "videoRedundancy" ON "videoRedundancy"."videoFileId" = "videoFile".id' +
559 redundancySqlSuffix +
560 ')'
561 )
562 }
563 },
564 {
565 id: {
a1587156 566 [Op.in]: literal(
b764380a
C
567 '(' +
568 'select "videoId" FROM "videoStreamingPlaylist" ' +
569 'INNER JOIN "videoRedundancy" ON "videoRedundancy"."videoStreamingPlaylistId" = "videoStreamingPlaylist".id' +
570 redundancySqlSuffix +
571 ')'
572 )
573 }
574 }
575 ]
576 },
577
578 videosWhere
579 ]
580 }
581
582 // /!\ On video model /!\
583 const findOptions = {
584 offset: start,
585 limit: count,
586 order: getSort(sort),
587 include: [
588 {
589 required: false,
8319d6ae 590 model: VideoFileModel,
b764380a
C
591 include: [
592 {
593 model: VideoRedundancyModel.unscoped(),
594 required: false,
595 where: redundancyWhere
596 }
597 ]
598 },
599 {
600 required: false,
601 model: VideoStreamingPlaylistModel.unscoped(),
602 include: [
603 {
604 model: VideoRedundancyModel.unscoped(),
605 required: false,
606 where: redundancyWhere
607 },
608 {
8319d6ae 609 model: VideoFileModel,
b764380a
C
610 required: false
611 }
612 ]
613 }
614 ],
615 where: videoFilterWhere
616 }
617
618 // /!\ On video model /!\
619 const countOptions = {
620 where: videoFilterWhere
621 }
622
623 return Promise.all([
624 VideoModel.findAll(findOptions),
625
626 VideoModel.count(countOptions)
627 ]).then(([ data, total ]) => ({ total, data }))
628 }
629
630 static async getStats (strategy: VideoRedundancyStrategyWithManual) {
4b5384f6
C
631 const actor = await getServerActor()
632
7448551f
C
633 const sql = `WITH "tmp" AS ` +
634 `(` +
635 `SELECT "videoFile"."size" AS "videoFileSize", "videoStreamingFile"."size" AS "videoStreamingFileSize", ` +
636 `"videoFile"."videoId" AS "videoFileVideoId", "videoStreamingPlaylist"."videoId" AS "videoStreamingVideoId"` +
637 `FROM "videoRedundancy" AS "videoRedundancy" ` +
638 `LEFT JOIN "videoFile" AS "videoFile" ON "videoRedundancy"."videoFileId" = "videoFile"."id" ` +
639 `LEFT JOIN "videoStreamingPlaylist" ON "videoRedundancy"."videoStreamingPlaylistId" = "videoStreamingPlaylist"."id" ` +
640 `LEFT JOIN "videoFile" AS "videoStreamingFile" ` +
641 `ON "videoStreamingPlaylist"."id" = "videoStreamingFile"."videoStreamingPlaylistId" ` +
642 `WHERE "videoRedundancy"."strategy" = :strategy AND "videoRedundancy"."actorId" = :actorId` +
643 `), ` +
644 `"videoIds" AS (` +
645 `SELECT "videoFileVideoId" AS "videoId" FROM "tmp" ` +
646 `UNION SELECT "videoStreamingVideoId" AS "videoId" FROM "tmp" ` +
647 `) ` +
648 `SELECT ` +
649 `COALESCE(SUM("videoFileSize"), '0') + COALESCE(SUM("videoStreamingFileSize"), '0') AS "totalUsed", ` +
650 `(SELECT COUNT("videoIds"."videoId") FROM "videoIds") AS "totalVideos", ` +
651 `COUNT(*) AS "totalVideoFiles" ` +
652 `FROM "tmp"`
653
654 return VideoRedundancyModel.sequelize.query<any>(sql, {
655 replacements: { strategy, actorId: actor.id },
656 type: QueryTypes.SELECT
657 }).then(([ row ]) => ({
658 totalUsed: parseAggregateResult(row.totalUsed),
659 totalVideos: row.totalVideos,
660 totalVideoFiles: row.totalVideoFiles
661 }))
4b5384f6
C
662 }
663
b764380a 664 static toFormattedJSONStatic (video: MVideoForRedundancyAPI): VideoRedundancy {
a1587156
C
665 const filesRedundancies: FileRedundancyInformation[] = []
666 const streamingPlaylistsRedundancies: StreamingPlaylistRedundancyInformation[] = []
b764380a
C
667
668 for (const file of video.VideoFiles) {
669 for (const redundancy of file.RedundancyVideos) {
670 filesRedundancies.push({
671 id: redundancy.id,
672 fileUrl: redundancy.fileUrl,
673 strategy: redundancy.strategy,
674 createdAt: redundancy.createdAt,
675 updatedAt: redundancy.updatedAt,
676 expiresOn: redundancy.expiresOn,
677 size: file.size
678 })
679 }
680 }
681
682 for (const playlist of video.VideoStreamingPlaylists) {
683 const size = playlist.VideoFiles.reduce((a, b) => a + b.size, 0)
684
685 for (const redundancy of playlist.RedundancyVideos) {
686 streamingPlaylistsRedundancies.push({
687 id: redundancy.id,
688 fileUrl: redundancy.fileUrl,
689 strategy: redundancy.strategy,
690 createdAt: redundancy.createdAt,
691 updatedAt: redundancy.updatedAt,
692 expiresOn: redundancy.expiresOn,
693 size
694 })
695 }
696 }
697
698 return {
699 id: video.id,
700 name: video.name,
701 url: video.url,
702 uuid: video.uuid,
703
704 redundancies: {
705 files: filesRedundancies,
706 streamingPlaylists: streamingPlaylistsRedundancies
707 }
708 }
709 }
710
09209296 711 getVideo () {
2e1e4af0 712 if (this.VideoFile?.Video) return this.VideoFile.Video
09209296 713
2e1e4af0 714 if (this.VideoStreamingPlaylist?.Video) return this.VideoStreamingPlaylist.Video
9cfeb3cf
C
715
716 return undefined
09209296
C
717 }
718
8d1fa36a
C
719 isOwned () {
720 return !!this.strategy
721 }
722
b5fecbf4 723 toActivityPubObject (this: MVideoRedundancyAP): CacheFileObject {
09209296
C
724 if (this.VideoStreamingPlaylist) {
725 return {
726 id: this.url,
727 type: 'CacheFile' as 'CacheFile',
728 object: this.VideoStreamingPlaylist.Video.url,
b764380a 729 expires: this.expiresOn ? this.expiresOn.toISOString() : null,
09209296
C
730 url: {
731 type: 'Link',
09209296
C
732 mediaType: 'application/x-mpegURL',
733 href: this.fileUrl
734 }
735 }
736 }
737
c48e82b5
C
738 return {
739 id: this.url,
740 type: 'CacheFile' as 'CacheFile',
741 object: this.VideoFile.Video.url,
b764380a 742 expires: this.expiresOn ? this.expiresOn.toISOString() : null,
c48e82b5
C
743 url: {
744 type: 'Link',
a1587156 745 mediaType: MIMETYPES.VIDEO.EXT_MIMETYPE[this.VideoFile.extname] as any,
c48e82b5
C
746 href: this.fileUrl,
747 height: this.VideoFile.resolution,
748 size: this.VideoFile.size,
749 fps: this.VideoFile.fps
750 }
751 }
752 }
753
b36f41ca 754 // Don't include video files we already duplicated
7448551f 755 private static buildVideoIdsForDuplication (peertubeActor: MActor) {
3acc5084 756 const notIn = literal(
c48e82b5 757 '(' +
7448551f
C
758 `SELECT "videoFile"."videoId" AS "videoId" FROM "videoRedundancy" ` +
759 `INNER JOIN "videoFile" ON "videoFile"."id" = "videoRedundancy"."videoFileId" ` +
760 `WHERE "videoRedundancy"."actorId" = ${peertubeActor.id} ` +
761 `UNION ` +
762 `SELECT "videoStreamingPlaylist"."videoId" AS "videoId" FROM "videoRedundancy" ` +
763 `INNER JOIN "videoStreamingPlaylist" ON "videoStreamingPlaylist"."id" = "videoRedundancy"."videoStreamingPlaylistId" ` +
764 `WHERE "videoRedundancy"."actorId" = ${peertubeActor.id} ` +
c48e82b5
C
765 ')'
766 )
b36f41ca
C
767
768 return {
7448551f
C
769 id: {
770 [Op.notIn]: notIn
b36f41ca
C
771 }
772 }
773 }
774
775 private static buildServerRedundancyInclude () {
776 return {
777 attributes: [],
778 model: VideoChannelModel.unscoped(),
779 required: true,
780 include: [
781 {
782 attributes: [],
783 model: ActorModel.unscoped(),
784 required: true,
785 include: [
786 {
787 attributes: [],
788 model: ServerModel.unscoped(),
789 required: true,
790 where: {
791 redundancyAllowed: true
792 }
793 }
794 ]
795 }
796 ]
797 }
c48e82b5
C
798 }
799}