]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/models/video/video.ts
Use different p2p policy for embeds and webapp
[github/Chocobozzz/PeerTube.git] / server / models / video / video.ts
CommitLineData
41fb13c3 1import Bluebird from 'bluebird'
d95d1559 2import { remove } from 'fs-extra'
e5dbd508 3import { maxBy, minBy } from 'lodash'
098eb377 4import { join } from 'path'
b49f22d8 5import { FindOptions, Includeable, IncludeOptions, Op, QueryTypes, ScopeOptions, Sequelize, Transaction, WhereOptions } from 'sequelize'
3fd3ab2d 6import {
4ba3b8ea
C
7 AllowNull,
8 BeforeDestroy,
9 BelongsTo,
10 BelongsToMany,
11 Column,
12 CreatedAt,
13 DataType,
14 Default,
15 ForeignKey,
16 HasMany,
2baea0c7 17 HasOne,
4ba3b8ea
C
18 Is,
19 IsInt,
20 IsUUID,
21 Min,
22 Model,
23 Scopes,
24 Table,
9a629c6e 25 UpdatedAt
3fd3ab2d 26} from 'sequelize-typescript'
d95d1559 27import { buildNSFWFilter } from '@server/helpers/express-utils'
06aad801 28import { uuidToShort } from '@shared/core-utils/uuid'
68e70a74 29import { getPrivaciesForFederation, isPrivacyForFederation, isStateForFederation } from '@server/helpers/video'
8ebf2a5d 30import { LiveManager } from '@server/lib/live/live-manager'
0305db28
JB
31import { removeHLSObjectStorage, removeWebTorrentObjectStorage } from '@server/lib/object-storage'
32import { getHLSDirectory, getHLSRedundancyDirectory } from '@server/lib/paths'
33import { VideoPathManager } from '@server/lib/video-path-manager'
d95d1559
C
34import { getServerActor } from '@server/models/application/application'
35import { ModelCache } from '@server/models/model-cache'
98846837 36import { AttributesOnly, buildVideoEmbedPath, buildVideoWatchPath, pick } from '@shared/core-utils'
ad5db104 37import { VideoFile, VideoInclude } from '@shared/models'
d95d1559 38import { ResultList, UserRight, VideoPrivacy, VideoState } from '../../../shared'
de6310b2 39import { VideoObject } from '../../../shared/models/activitypub/objects'
0305db28 40import { Video, VideoDetails, VideoRateType, VideoStorage } from '../../../shared/models/videos'
d95d1559 41import { ThumbnailType } from '../../../shared/models/videos/thumbnail.type'
d95d1559 42import { VideoStreamingPlaylistType } from '../../../shared/models/videos/video-streaming-playlist.type'
30ff39e7 43import { peertubeTruncate } from '../../helpers/core-utils'
da854ddd 44import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
c4c0c311 45import { exists, isBooleanValid } from '../../helpers/custom-validators/misc'
3fd3ab2d 46import {
4ba3b8ea
C
47 isVideoDescriptionValid,
48 isVideoDurationValid,
418d092a 49 isVideoNameValid,
2baea0c7
C
50 isVideoPrivacyValid,
51 isVideoStateValid,
b64c950a 52 isVideoSupportValid
3fd3ab2d 53} from '../../helpers/custom-validators/videos'
daf6e480 54import { getVideoFileResolution } from '../../helpers/ffprobe-utils'
da854ddd 55import { logger } from '../../helpers/logger'
d95d1559 56import { CONFIG } from '../../initializers/config'
69322042 57import { ACTIVITY_PUB, API_VERSION, CONSTRAINTS_FIELDS, LAZY_STATIC_PATHS, STATIC_PATHS, WEBSERVER } from '../../initializers/constants'
50d6de9c 58import { sendDeleteVideo } from '../../lib/activitypub/send'
453e83ea
C
59import {
60 MChannel,
0283eaac 61 MChannelAccountDefault,
453e83ea 62 MChannelId,
d7a25329
C
63 MStreamingPlaylist,
64 MStreamingPlaylistFilesVideo,
453e83ea
C
65 MUserAccountId,
66 MUserId,
90a8bd30 67 MVideo,
453e83ea 68 MVideoAccountLight,
0283eaac 69 MVideoAccountLightBlacklistAllFiles,
b5fecbf4 70 MVideoAP,
453e83ea 71 MVideoDetails,
d7a25329 72 MVideoFileVideo,
b5fecbf4
C
73 MVideoFormattable,
74 MVideoFormattableDetails,
0283eaac 75 MVideoForUser,
453e83ea 76 MVideoFullLight,
71d4af1e 77 MVideoId,
5f3e2425 78 MVideoImmutable,
453e83ea 79 MVideoThumbnail,
d636ab58 80 MVideoThumbnailBlacklist,
b5fecbf4 81 MVideoWithAllFiles,
71d4af1e 82 MVideoWithFile
26d6bf65 83} from '../../types/models'
26d6bf65 84import { MThumbnail } from '../../types/models/video/thumbnail'
1896bca0 85import { MVideoFile, MVideoFileStreamingPlaylistVideo } from '../../types/models/video/video-file'
d95d1559
C
86import { VideoAbuseModel } from '../abuse/video-abuse'
87import { AccountModel } from '../account/account'
88import { AccountVideoRateModel } from '../account/account-video-rate'
7d9ba5c0
C
89import { ActorModel } from '../actor/actor'
90import { ActorImageModel } from '../actor/actor-image'
d95d1559
C
91import { VideoRedundancyModel } from '../redundancy/video-redundancy'
92import { ServerModel } from '../server/server'
d9a2a031
C
93import { TrackerModel } from '../server/tracker'
94import { VideoTrackerModel } from '../server/video-tracker'
fa47956e 95import { setAsUpdated } from '../shared'
7d9ba5c0
C
96import { UserModel } from '../user/user'
97import { UserVideoHistoryModel } from '../user/user-video-history'
d95d1559 98import { buildTrigramSearchIndex, buildWhereIdOrUUID, getVideoSort, isOutdated, throwIfNotValid } from '../utils'
e5dbd508
C
99import {
100 videoFilesModelToFormattedJSON,
101 VideoFormattingJSONOptions,
102 videoModelToActivityPubObject,
103 videoModelToFormattedDetailsJSON,
104 videoModelToFormattedJSON
105} from './formatter/video-format-utils'
d95d1559 106import { ScheduleVideoUpdateModel } from './schedule-video-update'
3c10840f 107import { VideoModelGetQueryBuilder } from './sql/video-model-get-query-builder'
2760b454 108import { BuildVideosListQueryOptions, DisplayOnlyForFollowerOptions, VideosIdListQueryBuilder } from './sql/videos-id-list-query-builder'
e5dbd508 109import { VideosModelListQueryBuilder } from './sql/videos-model-list-query-builder'
d95d1559
C
110import { TagModel } from './tag'
111import { ThumbnailModel } from './thumbnail'
112import { VideoBlacklistModel } from './video-blacklist'
113import { VideoCaptionModel } from './video-caption'
114import { ScopeNames as VideoChannelScopeNames, SummaryOptions, VideoChannelModel } from './video-channel'
115import { VideoCommentModel } from './video-comment'
116import { VideoFileModel } from './video-file'
d95d1559 117import { VideoImportModel } from './video-import'
0305db28 118import { VideoJobInfoModel } from './video-job-info'
af4ae64f 119import { VideoLiveModel } from './video-live'
d95d1559 120import { VideoPlaylistElementModel } from './video-playlist-element'
d95d1559
C
121import { VideoShareModel } from './video-share'
122import { VideoStreamingPlaylistModel } from './video-streaming-playlist'
123import { VideoTagModel } from './video-tag'
124import { VideoViewModel } from './video-view'
6e46de09 125
2baea0c7 126export enum ScopeNames {
afd2cba5 127 FOR_API = 'FOR_API',
4cb6d457 128 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
d48ff09d 129 WITH_TAGS = 'WITH_TAGS',
d7a25329 130 WITH_WEBTORRENT_FILES = 'WITH_WEBTORRENT_FILES',
191764f3 131 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
6e46de09 132 WITH_BLACKLISTED = 'WITH_BLACKLISTED',
09209296 133 WITH_STREAMING_PLAYLISTS = 'WITH_STREAMING_PLAYLISTS',
943e5193 134 WITH_IMMUTABLE_ATTRIBUTES = 'WITH_IMMUTABLE_ATTRIBUTES',
69322042
C
135 WITH_USER_HISTORY = 'WITH_USER_HISTORY',
136 WITH_THUMBNAILS = 'WITH_THUMBNAILS'
d48ff09d
C
137}
138
bfbd9128
C
139export type ForAPIOptions = {
140 ids?: number[]
418d092a
C
141
142 videoPlaylistId?: number
143
bfbd9128 144 withAccountBlockerIds?: number[]
afd2cba5
C
145}
146
3acc5084 147@Scopes(() => ({
943e5193
C
148 [ScopeNames.WITH_IMMUTABLE_ATTRIBUTES]: {
149 attributes: [ 'id', 'url', 'uuid', 'remote' ]
150 },
a1587156 151 [ScopeNames.FOR_API]: (options: ForAPIOptions) => {
b49f22d8
C
152 const include: Includeable[] = [
153 {
154 model: VideoChannelModel.scope({
155 method: [
156 VideoChannelScopeNames.SUMMARY, {
157 withAccount: true,
158 withAccountBlockerIds: options.withAccountBlockerIds
159 } as SummaryOptions
160 ]
161 }),
162 required: true
163 },
164 {
165 attributes: [ 'type', 'filename' ],
166 model: ThumbnailModel,
167 required: false
168 }
169 ]
170
171 const query: FindOptions = {}
afd2cba5 172
bfbd9128
C
173 if (options.ids) {
174 query.where = {
175 id: {
a1587156 176 [Op.in]: options.ids
bfbd9128
C
177 }
178 }
179 }
180
418d092a 181 if (options.videoPlaylistId) {
b49f22d8 182 include.push({
418d092a 183 model: VideoPlaylistElementModel.unscoped(),
15e9d5ca
C
184 required: true,
185 where: {
186 videoPlaylistId: options.videoPlaylistId
187 }
418d092a
C
188 })
189 }
190
b49f22d8
C
191 query.include = include
192
afd2cba5
C
193 return query
194 },
a1587156 195 [ScopeNames.WITH_THUMBNAILS]: {
e8bafea3
C
196 include: [
197 {
3acc5084 198 model: ThumbnailModel,
e8bafea3
C
199 required: false
200 }
201 ]
202 },
a1587156 203 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
d48ff09d
C
204 include: [
205 {
3acc5084 206 model: VideoChannelModel.unscoped(),
d48ff09d
C
207 required: true,
208 include: [
6120941f
C
209 {
210 attributes: {
211 exclude: [ 'privateKey', 'publicKey' ]
212 },
3acc5084 213 model: ActorModel.unscoped(),
3e500247
C
214 required: true,
215 include: [
216 {
217 attributes: [ 'host' ],
3acc5084 218 model: ServerModel.unscoped(),
3e500247 219 required: false
52d9f792
C
220 },
221 {
f4796856
C
222 model: ActorImageModel.unscoped(),
223 as: 'Avatar',
52d9f792 224 required: false
3e500247
C
225 }
226 ]
6120941f 227 },
d48ff09d 228 {
3acc5084 229 model: AccountModel.unscoped(),
d48ff09d
C
230 required: true,
231 include: [
232 {
3acc5084 233 model: ActorModel.unscoped(),
6120941f
C
234 attributes: {
235 exclude: [ 'privateKey', 'publicKey' ]
236 },
50d6de9c
C
237 required: true,
238 include: [
239 {
3e500247 240 attributes: [ 'host' ],
3acc5084 241 model: ServerModel.unscoped(),
50d6de9c 242 required: false
b6a4fd6b
C
243 },
244 {
f4796856
C
245 model: ActorImageModel.unscoped(),
246 as: 'Avatar',
b6a4fd6b 247 required: false
50d6de9c
C
248 }
249 ]
d48ff09d
C
250 }
251 ]
252 }
253 ]
254 }
3acc5084 255 ]
d48ff09d 256 },
a1587156 257 [ScopeNames.WITH_TAGS]: {
3acc5084 258 include: [ TagModel ]
d48ff09d 259 },
a1587156 260 [ScopeNames.WITH_BLACKLISTED]: {
191764f3
C
261 include: [
262 {
453e83ea 263 attributes: [ 'id', 'reason', 'unfederated' ],
3acc5084 264 model: VideoBlacklistModel,
191764f3
C
265 required: false
266 }
267 ]
268 },
a1587156 269 [ScopeNames.WITH_WEBTORRENT_FILES]: (withRedundancies = false) => {
09209296
C
270 let subInclude: any[] = []
271
272 if (withRedundancies === true) {
273 subInclude = [
274 {
275 attributes: [ 'fileUrl' ],
276 model: VideoRedundancyModel.unscoped(),
277 required: false
278 }
279 ]
280 }
281
282 return {
283 include: [
284 {
8319d6ae 285 model: VideoFileModel,
d7df188f 286 separate: true,
09209296
C
287 required: false,
288 include: subInclude
289 }
290 ]
291 }
292 },
a1587156 293 [ScopeNames.WITH_STREAMING_PLAYLISTS]: (withRedundancies = false) => {
d7a25329
C
294 const subInclude: IncludeOptions[] = [
295 {
8319d6ae 296 model: VideoFileModel,
d7a25329
C
297 required: false
298 }
299 ]
09209296
C
300
301 if (withRedundancies === true) {
d7a25329
C
302 subInclude.push({
303 attributes: [ 'fileUrl' ],
304 model: VideoRedundancyModel.unscoped(),
305 required: false
306 })
09209296
C
307 }
308
309 return {
310 include: [
311 {
312 model: VideoStreamingPlaylistModel.unscoped(),
09209296 313 required: false,
d7df188f 314 separate: true,
09209296
C
315 include: subInclude
316 }
317 ]
318 }
bbe0f064 319 },
a1587156 320 [ScopeNames.WITH_SCHEDULED_UPDATE]: {
bbe0f064
C
321 include: [
322 {
3acc5084 323 model: ScheduleVideoUpdateModel.unscoped(),
bbe0f064
C
324 required: false
325 }
326 ]
6e46de09 327 },
a1587156 328 [ScopeNames.WITH_USER_HISTORY]: (userId: number) => {
6e46de09
C
329 return {
330 include: [
331 {
332 attributes: [ 'currentTime' ],
333 model: UserVideoHistoryModel.unscoped(),
334 required: false,
335 where: {
336 userId
337 }
338 }
339 ]
340 }
d48ff09d 341 }
3acc5084 342}))
3fd3ab2d
C
343@Table({
344 tableName: 'video',
0374b6b5
C
345 indexes: [
346 buildTrigramSearchIndex('video_name_trigram', 'name'),
347
348 { fields: [ 'createdAt' ] },
349 {
350 fields: [
351 { name: 'publishedAt', order: 'DESC' },
352 { name: 'id', order: 'ASC' }
353 ]
354 },
355 { fields: [ 'duration' ] },
53455605
C
356 {
357 fields: [
358 { name: 'views', order: 'DESC' },
359 { name: 'id', order: 'ASC' }
360 ]
361 },
0374b6b5
C
362 { fields: [ 'channelId' ] },
363 {
364 fields: [ 'originallyPublishedAt' ],
365 where: {
366 originallyPublishedAt: {
367 [Op.ne]: null
368 }
369 }
370 },
371 {
372 fields: [ 'category' ], // We don't care videos with an unknown category
373 where: {
374 category: {
375 [Op.ne]: null
376 }
377 }
378 },
379 {
380 fields: [ 'licence' ], // We don't care videos with an unknown licence
381 where: {
382 licence: {
383 [Op.ne]: null
384 }
385 }
386 },
387 {
388 fields: [ 'language' ], // We don't care videos with an unknown language
389 where: {
390 language: {
391 [Op.ne]: null
392 }
393 }
394 },
395 {
396 fields: [ 'nsfw' ], // Most of the videos are not NSFW
397 where: {
398 nsfw: true
399 }
400 },
401 {
402 fields: [ 'remote' ], // Only index local videos
403 where: {
404 remote: false
405 }
406 },
407 {
408 fields: [ 'uuid' ],
409 unique: true
410 },
411 {
412 fields: [ 'url' ],
413 unique: true
414 }
415 ]
3fd3ab2d 416})
16c016e8 417export class VideoModel extends Model<Partial<AttributesOnly<VideoModel>>> {
3fd3ab2d
C
418
419 @AllowNull(false)
420 @Default(DataType.UUIDV4)
421 @IsUUID(4)
422 @Column(DataType.UUID)
423 uuid: string
424
425 @AllowNull(false)
426 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
427 @Column
428 name: string
429
430 @AllowNull(true)
431 @Default(null)
3fd3ab2d
C
432 @Column
433 category: number
434
435 @AllowNull(true)
436 @Default(null)
3fd3ab2d
C
437 @Column
438 licence: number
439
440 @AllowNull(true)
441 @Default(null)
9d3ef9fe
C
442 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
443 language: string
3fd3ab2d
C
444
445 @AllowNull(false)
446 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
447 @Column
1ba471c5 448 privacy: VideoPrivacy
3fd3ab2d
C
449
450 @AllowNull(false)
47564bbe 451 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
3fd3ab2d
C
452 @Column
453 nsfw: boolean
454
455 @AllowNull(true)
456 @Default(null)
1735c825 457 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description', true))
3fd3ab2d
C
458 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
459 description: string
460
2422c46b
C
461 @AllowNull(true)
462 @Default(null)
1735c825 463 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support', true))
2422c46b
C
464 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
465 support: string
466
3fd3ab2d
C
467 @AllowNull(false)
468 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
469 @Column
470 duration: number
471
472 @AllowNull(false)
473 @Default(0)
474 @IsInt
475 @Min(0)
476 @Column
477 views: number
478
479 @AllowNull(false)
480 @Default(0)
481 @IsInt
482 @Min(0)
483 @Column
484 likes: number
485
486 @AllowNull(false)
487 @Default(0)
488 @IsInt
489 @Min(0)
490 @Column
491 dislikes: number
492
493 @AllowNull(false)
494 @Column
495 remote: boolean
496
497 @AllowNull(false)
c6c0fa6c
C
498 @Default(false)
499 @Column
500 isLive: boolean
501
502 @AllowNull(false)
3fd3ab2d
C
503 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
504 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
505 url: string
506
47564bbe
C
507 @AllowNull(false)
508 @Column
509 commentsEnabled: boolean
510
156c50af
LD
511 @AllowNull(false)
512 @Column
7f2cfe3a 513 downloadEnabled: boolean
156c50af 514
2186386c
C
515 @AllowNull(false)
516 @Column
517 waitTranscoding: boolean
518
519 @AllowNull(false)
520 @Default(null)
521 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
522 @Column
523 state: VideoState
524
3fd3ab2d
C
525 @CreatedAt
526 createdAt: Date
527
528 @UpdatedAt
529 updatedAt: Date
530
2922e048 531 @AllowNull(false)
1735c825 532 @Default(DataType.NOW)
2922e048
JLB
533 @Column
534 publishedAt: Date
535
7519127b
C
536 @AllowNull(true)
537 @Default(null)
c8034165 538 @Column
539 originallyPublishedAt: Date
540
3fd3ab2d
C
541 @ForeignKey(() => VideoChannelModel)
542 @Column
543 channelId: number
544
545 @BelongsTo(() => VideoChannelModel, {
feb4bdfd 546 foreignKey: {
50d6de9c 547 allowNull: true
feb4bdfd 548 },
693c6586 549 onDelete: 'cascade'
feb4bdfd 550 })
3fd3ab2d 551 VideoChannel: VideoChannelModel
7920c273 552
3fd3ab2d 553 @BelongsToMany(() => TagModel, {
7920c273 554 foreignKey: 'videoId',
3fd3ab2d
C
555 through: () => VideoTagModel,
556 onDelete: 'CASCADE'
7920c273 557 })
3fd3ab2d 558 Tags: TagModel[]
55fa55a9 559
d9a2a031
C
560 @BelongsToMany(() => TrackerModel, {
561 foreignKey: 'videoId',
562 through: () => VideoTrackerModel,
563 onDelete: 'CASCADE'
564 })
565 Trackers: TrackerModel[]
566
e8bafea3
C
567 @HasMany(() => ThumbnailModel, {
568 foreignKey: {
569 name: 'videoId',
570 allowNull: true
571 },
572 hooks: true,
573 onDelete: 'cascade'
574 })
575 Thumbnails: ThumbnailModel[]
576
418d092a
C
577 @HasMany(() => VideoPlaylistElementModel, {
578 foreignKey: {
579 name: 'videoId',
bfbd9128 580 allowNull: true
418d092a 581 },
bfbd9128 582 onDelete: 'set null'
418d092a
C
583 })
584 VideoPlaylistElements: VideoPlaylistElementModel[]
585
3fd3ab2d 586 @HasMany(() => VideoAbuseModel, {
55fa55a9
C
587 foreignKey: {
588 name: 'videoId',
68d19a0a 589 allowNull: true
55fa55a9 590 },
68d19a0a 591 onDelete: 'set null'
55fa55a9 592 })
3fd3ab2d 593 VideoAbuses: VideoAbuseModel[]
93e1258c 594
3fd3ab2d 595 @HasMany(() => VideoFileModel, {
93e1258c
C
596 foreignKey: {
597 name: 'videoId',
d7a25329 598 allowNull: true
93e1258c 599 },
c48e82b5 600 hooks: true,
93e1258c
C
601 onDelete: 'cascade'
602 })
3fd3ab2d 603 VideoFiles: VideoFileModel[]
e71bcc0f 604
09209296
C
605 @HasMany(() => VideoStreamingPlaylistModel, {
606 foreignKey: {
607 name: 'videoId',
608 allowNull: false
609 },
610 hooks: true,
611 onDelete: 'cascade'
612 })
613 VideoStreamingPlaylists: VideoStreamingPlaylistModel[]
614
3fd3ab2d 615 @HasMany(() => VideoShareModel, {
e71bcc0f
C
616 foreignKey: {
617 name: 'videoId',
618 allowNull: false
619 },
620 onDelete: 'cascade'
621 })
3fd3ab2d 622 VideoShares: VideoShareModel[]
16b90975 623
3fd3ab2d 624 @HasMany(() => AccountVideoRateModel, {
16b90975
C
625 foreignKey: {
626 name: 'videoId',
627 allowNull: false
628 },
629 onDelete: 'cascade'
630 })
3fd3ab2d 631 AccountVideoRates: AccountVideoRateModel[]
f285faa0 632
da854ddd
C
633 @HasMany(() => VideoCommentModel, {
634 foreignKey: {
635 name: 'videoId',
636 allowNull: false
637 },
f05a1c30
C
638 onDelete: 'cascade',
639 hooks: true
da854ddd
C
640 })
641 VideoComments: VideoCommentModel[]
642
9a629c6e
C
643 @HasMany(() => VideoViewModel, {
644 foreignKey: {
645 name: 'videoId',
646 allowNull: false
647 },
6e46de09 648 onDelete: 'cascade'
9a629c6e
C
649 })
650 VideoViews: VideoViewModel[]
651
6e46de09
C
652 @HasMany(() => UserVideoHistoryModel, {
653 foreignKey: {
654 name: 'videoId',
655 allowNull: false
656 },
657 onDelete: 'cascade'
658 })
659 UserVideoHistories: UserVideoHistoryModel[]
660
2baea0c7
C
661 @HasOne(() => ScheduleVideoUpdateModel, {
662 foreignKey: {
663 name: 'videoId',
664 allowNull: false
665 },
666 onDelete: 'cascade'
667 })
668 ScheduleVideoUpdate: ScheduleVideoUpdateModel
669
26b7305a
C
670 @HasOne(() => VideoBlacklistModel, {
671 foreignKey: {
672 name: 'videoId',
673 allowNull: false
674 },
675 onDelete: 'cascade'
676 })
677 VideoBlacklist: VideoBlacklistModel
678
31c82cd9
C
679 @HasOne(() => VideoLiveModel, {
680 foreignKey: {
681 name: 'videoId',
682 allowNull: false
683 },
684 onDelete: 'cascade'
685 })
686 VideoLive: VideoLiveModel
687
dc133480
C
688 @HasOne(() => VideoImportModel, {
689 foreignKey: {
690 name: 'videoId',
691 allowNull: true
692 },
693 onDelete: 'set null'
694 })
695 VideoImport: VideoImportModel
696
40e87e9e
C
697 @HasMany(() => VideoCaptionModel, {
698 foreignKey: {
699 name: 'videoId',
700 allowNull: false
701 },
702 onDelete: 'cascade',
703 hooks: true,
a1587156 704 ['separate' as any]: true
40e87e9e
C
705 })
706 VideoCaptions: VideoCaptionModel[]
707
0305db28
JB
708 @HasOne(() => VideoJobInfoModel, {
709 foreignKey: {
710 name: 'videoId',
711 allowNull: false
712 },
713 onDelete: 'cascade'
714 })
715 VideoJobInfo: VideoJobInfoModel
716
f05a1c30 717 @BeforeDestroy
453e83ea 718 static async sendDelete (instance: MVideoAccountLight, options) {
42ec411b 719 if (!instance.isOwned()) return undefined
f05a1c30 720
42ec411b
C
721 // Lazy load channels
722 if (!instance.VideoChannel) {
723 instance.VideoChannel = await instance.$get('VideoChannel', {
724 include: [
725 ActorModel,
726 AccountModel
727 ],
728 transaction: options.transaction
729 }) as MChannelAccountDefault
f05a1c30
C
730 }
731
42ec411b 732 return sendDeleteVideo(instance, options.transaction)
f05a1c30
C
733 }
734
6b738c7a 735 @BeforeDestroy
9f7657b6 736 static async removeFiles (instance: VideoModel, options) {
f05a1c30 737 const tasks: Promise<any>[] = []
f285faa0 738
8e0fd45e 739 logger.info('Removing files of video %s.', instance.url)
6b738c7a 740
3fd3ab2d 741 if (instance.isOwned()) {
f05a1c30 742 if (!Array.isArray(instance.VideoFiles)) {
9f7657b6 743 instance.VideoFiles = await instance.$get('VideoFiles', { transaction: options.transaction })
f05a1c30
C
744 }
745
3fd3ab2d
C
746 // Remove physical files and torrents
747 instance.VideoFiles.forEach(file => {
b46cf4b9 748 tasks.push(instance.removeWebTorrentFileAndTorrent(file))
3fd3ab2d 749 })
09209296
C
750
751 // Remove playlists file
ffc65cbd 752 if (!Array.isArray(instance.VideoStreamingPlaylists)) {
9f7657b6 753 instance.VideoStreamingPlaylists = await instance.$get('VideoStreamingPlaylists', { transaction: options.transaction })
ffc65cbd
C
754 }
755
756 for (const p of instance.VideoStreamingPlaylists) {
757 tasks.push(instance.removeStreamingPlaylistFiles(p))
758 }
3fd3ab2d 759 }
40298b02 760
6b738c7a
C
761 // Do not wait video deletion because we could be in a transaction
762 Promise.all(tasks)
8ea6f49a
C
763 .catch(err => {
764 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
765 })
6b738c7a
C
766
767 return undefined
3fd3ab2d 768 }
f285faa0 769
a5cf76af
C
770 @BeforeDestroy
771 static stopLiveIfNeeded (instance: VideoModel) {
772 if (!instance.isLive) return
773
68e70a74
C
774 logger.info('Stopping live of video %s after video deletion.', instance.uuid)
775
9f7657b6 776 LiveManager.Instance.stopSessionOf(instance.id)
a5cf76af
C
777 }
778
7eba5e1f
C
779 @BeforeDestroy
780 static invalidateCache (instance: VideoModel) {
781 ModelCache.Instance.invalidateCache('video', instance.id)
782 }
783
68d19a0a
RK
784 @BeforeDestroy
785 static async saveEssentialDataToAbuses (instance: VideoModel, options) {
786 const tasks: Promise<any>[] = []
787
68d19a0a 788 if (!Array.isArray(instance.VideoAbuses)) {
9f7657b6 789 instance.VideoAbuses = await instance.$get('VideoAbuses', { transaction: options.transaction })
68d19a0a
RK
790
791 if (instance.VideoAbuses.length === 0) return undefined
792 }
793
57f6896f
C
794 logger.info('Saving video abuses details of video %s.', instance.url)
795
42ec411b 796 if (!instance.Trackers) instance.Trackers = await instance.$get('Trackers', { transaction: options.transaction })
86521a67 797 const details = instance.toFormattedDetailsJSON()
68d19a0a
RK
798
799 for (const abuse of instance.VideoAbuses) {
0251197e
RK
800 abuse.deletedVideo = details
801 tasks.push(abuse.save({ transaction: options.transaction }))
68d19a0a
RK
802 }
803
9f7657b6 804 await Promise.all(tasks)
68d19a0a
RK
805 }
806
e1ab52d7 807 static listLocalIds (): Promise<number[]> {
9f1ddd24 808 const query = {
e1ab52d7 809 attributes: [ 'id' ],
810 raw: true,
9f1ddd24
C
811 where: {
812 remote: false
813 }
814 }
815
90a8bd30 816 return VideoModel.findAll(query)
e1ab52d7 817 .then(rows => rows.map(r => r.id))
9f1ddd24
C
818 }
819
50d6de9c 820 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
3fd3ab2d
C
821 function getRawQuery (select: string) {
822 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
823 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
50d6de9c
C
824 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
825 'WHERE "Account"."actorId" = ' + actorId
3fd3ab2d
C
826 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
827 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
50d6de9c 828 'WHERE "VideoShare"."actorId" = ' + actorId
558d7c23 829
3fd3ab2d
C
830 return `(${queryVideo}) UNION (${queryVideoShare})`
831 }
aaf61f38 832
3fd3ab2d
C
833 const rawQuery = getRawQuery('"Video"."id"')
834 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
835
836 const query = {
837 distinct: true,
838 offset: start,
839 limit: count,
0c691a18 840 order: getVideoSort('-createdAt', [ 'Tags', 'name', 'ASC' ]),
3fd3ab2d
C
841 where: {
842 id: {
a1587156 843 [Op.in]: Sequelize.literal('(' + rawQuery + ')')
3c75ce12 844 },
3092e9bb 845 [Op.or]: getPrivaciesForFederation()
3fd3ab2d
C
846 },
847 include: [
40e87e9e 848 {
1afb3c47 849 attributes: [ 'filename', 'language', 'fileUrl' ],
40e87e9e
C
850 model: VideoCaptionModel.unscoped(),
851 required: false
852 },
3fd3ab2d 853 {
1d230c44 854 attributes: [ 'id', 'url' ],
2c897999 855 model: VideoShareModel.unscoped(),
3fd3ab2d 856 required: false,
e3d5ea4f
C
857 // We only want videos shared by this actor
858 where: {
a1587156 859 [Op.and]: [
e3d5ea4f
C
860 {
861 id: {
a1587156 862 [Op.not]: null
e3d5ea4f
C
863 }
864 },
865 {
866 actorId
867 }
868 ]
869 },
50d6de9c
C
870 include: [
871 {
2c897999
C
872 attributes: [ 'id', 'url' ],
873 model: ActorModel.unscoped()
50d6de9c
C
874 }
875 ]
3fd3ab2d
C
876 },
877 {
2c897999 878 model: VideoChannelModel.unscoped(),
3fd3ab2d
C
879 required: true,
880 include: [
881 {
2c897999
C
882 attributes: [ 'name' ],
883 model: AccountModel.unscoped(),
884 required: true,
885 include: [
886 {
e3d5ea4f 887 attributes: [ 'id', 'url', 'followersUrl' ],
2c897999
C
888 model: ActorModel.unscoped(),
889 required: true
890 }
891 ]
892 },
893 {
e3d5ea4f 894 attributes: [ 'id', 'url', 'followersUrl' ],
2c897999 895 model: ActorModel.unscoped(),
3fd3ab2d
C
896 required: true
897 }
898 ]
899 },
af4ae64f
C
900 {
901 model: VideoStreamingPlaylistModel.unscoped(),
902 required: false,
903 include: [
904 {
905 model: VideoFileModel,
906 required: false
907 }
908 ]
909 },
c8f3cfeb 910 VideoLiveModel.unscoped(),
3fd3ab2d 911 VideoFileModel,
2c897999 912 TagModel
3fd3ab2d
C
913 ]
914 }
164174a6 915
3fd3ab2d 916 return Bluebird.all([
3acc5084
C
917 VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findAll(query),
918 VideoModel.sequelize.query<{ total: string }>(rawCountQuery, { type: QueryTypes.SELECT })
3fd3ab2d
C
919 ]).then(([ rows, totals ]) => {
920 // totals: totalVideos + totalVideoShares
921 let totalVideos = 0
922 let totalVideoShares = 0
a1587156
C
923 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
924 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
3fd3ab2d
C
925
926 const total = totalVideos + totalVideoShares
927 return {
928 data: rows,
929 total: total
930 }
931 })
932 }
93e1258c 933
9e2e51dc 934 static async listPublishedLiveUUIDs () {
5c0904fc 935 const options = {
9e2e51dc 936 attributes: [ 'uuid' ],
5c0904fc
C
937 where: {
938 isLive: true,
f49b3231 939 remote: false,
5c0904fc
C
940 state: VideoState.PUBLISHED
941 }
942 }
943
b49f22d8
C
944 const result = await VideoModel.findAll(options)
945
9e2e51dc 946 return result.map(v => v.uuid)
5c0904fc
C
947 }
948
a4d2ca07
C
949 static listUserVideosForApi (options: {
950 accountId: number
951 start: number
952 count: number
953 sort: string
978c87e7
C
954
955 channelId?: number
1fd61899 956 isLive?: boolean
bf64ed41 957 search?: string
a4d2ca07 958 }) {
978c87e7 959 const { accountId, channelId, start, count, sort, search, isLive } = options
a4d2ca07 960
3acc5084 961 function buildBaseQuery (): FindOptions {
1fd61899
C
962 const where: WhereOptions = {}
963
964 if (search) {
965 where.name = {
966 [Op.iLike]: '%' + search + '%'
967 }
968 }
969
c4c0c311 970 if (exists(isLive)) {
1fd61899
C
971 where.isLive = isLive
972 }
973
978c87e7
C
974 const channelWhere = channelId
975 ? { id: channelId }
976 : {}
977
1fd61899 978 const baseQuery = {
3acc5084
C
979 offset: start,
980 limit: count,
1fd61899 981 where,
3acc5084
C
982 order: getVideoSort(sort),
983 include: [
984 {
985 model: VideoChannelModel,
986 required: true,
978c87e7 987 where: channelWhere,
3acc5084
C
988 include: [
989 {
990 model: AccountModel,
991 where: {
992 id: accountId
993 },
994 required: true
995 }
996 ]
997 }
998 ]
999 }
bf64ed41 1000
bf64ed41 1001 return baseQuery
3fd3ab2d 1002 }
d8755eed 1003
3acc5084
C
1004 const countQuery = buildBaseQuery()
1005 const findQuery = buildBaseQuery()
1006
bf64ed41 1007 const findScopes: (string | ScopeOptions)[] = [
a18f275d
C
1008 ScopeNames.WITH_SCHEDULED_UPDATE,
1009 ScopeNames.WITH_BLACKLISTED,
1010 ScopeNames.WITH_THUMBNAILS
1011 ]
3acc5084 1012
3acc5084
C
1013 return Promise.all([
1014 VideoModel.count(countQuery),
0283eaac 1015 VideoModel.scope(findScopes).findAll<MVideoForUser>(findQuery)
3acc5084
C
1016 ]).then(([ count, rows ]) => {
1017 return {
0283eaac 1018 data: rows,
3acc5084
C
1019 total: count
1020 }
1021 })
3fd3ab2d 1022 }
93e1258c 1023
48dce1c9 1024 static async listForApi (options: {
a1587156
C
1025 start: number
1026 count: number
1027 sort: string
1fd61899 1028
a1587156 1029 nsfw: boolean
1fd61899 1030 isLive?: boolean
2760b454
C
1031 isLocal?: boolean
1032 include?: VideoInclude
1fd61899 1033
3c10840f 1034 hasFiles?: boolean // default false
d324756e
C
1035 hasWebtorrentFiles?: boolean
1036 hasHLSFiles?: boolean
1fd61899 1037
a1587156
C
1038 categoryOneOf?: number[]
1039 licenceOneOf?: number[]
1040 languageOneOf?: string[]
1041 tagsOneOf?: string[]
1042 tagsAllOf?: string[]
527a52ac 1043 privacyOneOf?: VideoPrivacy[]
1fd61899 1044
a1587156
C
1045 accountId?: number
1046 videoChannelId?: number
1fd61899 1047
2760b454 1048 displayOnlyForFollower: DisplayOnlyForFollowerOptions | null
1fd61899 1049
a1587156 1050 videoPlaylistId?: number
1fd61899 1051
a1587156 1052 trendingDays?: number
1fd61899 1053
a1587156
C
1054 user?: MUserAccountId
1055 historyOfUser?: MUserId
1fd61899 1056
fe987656 1057 countVideos?: boolean
1fd61899 1058
d8b34ee5 1059 search?: string
fe987656 1060 }) {
d324756e 1061 VideoModel.throwIfPrivateIncludeWithoutUser(options.include, options.user)
527a52ac 1062 VideoModel.throwIfPrivacyOneOfWithoutUser(options.privacyOneOf, options.user)
1cd3facc 1063
5f3e2425
C
1064 const trendingDays = options.sort.endsWith('trending')
1065 ? CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1066 : undefined
d6886027
C
1067
1068 let trendingAlgorithm: string
3d4e112d
RK
1069 if (options.sort.endsWith('hot')) trendingAlgorithm = 'hot'
1070 if (options.sort.endsWith('best')) trendingAlgorithm = 'best'
93e1258c 1071
7ad9b984
C
1072 const serverActor = await getServerActor()
1073
afd2cba5 1074 const queryOptions = {
9c9a236b
C
1075 ...pick(options, [
1076 'start',
1077 'count',
1078 'sort',
1079 'nsfw',
1080 'isLive',
1081 'categoryOneOf',
1082 'licenceOneOf',
1083 'languageOneOf',
1084 'tagsOneOf',
1085 'tagsAllOf',
527a52ac 1086 'privacyOneOf',
2760b454
C
1087 'isLocal',
1088 'include',
1089 'displayOnlyForFollower',
3c10840f 1090 'hasFiles',
9c9a236b
C
1091 'accountId',
1092 'videoChannelId',
1093 'videoPlaylistId',
9c9a236b
C
1094 'user',
1095 'historyOfUser',
d324756e
C
1096 'hasHLSFiles',
1097 'hasWebtorrentFiles',
9c9a236b
C
1098 'search'
1099 ]),
1100
2760b454 1101 serverAccountIdForBlock: serverActor.Account.id,
d8b34ee5 1102 trendingDays,
9c9a236b 1103 trendingAlgorithm
48dce1c9
C
1104 }
1105
5f3e2425 1106 return VideoModel.getAvailableForApi(queryOptions, options.countVideos)
93e1258c
C
1107 }
1108
0b18f4aa 1109 static async searchAndPopulateAccountAndServer (options: {
9c9a236b
C
1110 start: number
1111 count: number
1112 sort: string
d324756e 1113
0b18f4aa 1114 nsfw?: boolean
1fd61899 1115 isLive?: boolean
2760b454
C
1116 isLocal?: boolean
1117 include?: VideoInclude
d324756e 1118
0b18f4aa
C
1119 categoryOneOf?: number[]
1120 licenceOneOf?: number[]
1121 languageOneOf?: string[]
1122 tagsOneOf?: string[]
1123 tagsAllOf?: string[]
527a52ac 1124 privacyOneOf?: VideoPrivacy[]
d324756e
C
1125
1126 displayOnlyForFollower: DisplayOnlyForFollowerOptions | null
1127
1128 user?: MUserAccountId
1129
1130 hasWebtorrentFiles?: boolean
1131 hasHLSFiles?: boolean
1132
1133 search?: string
1134
1135 host?: string
1136 startDate?: string // ISO 8601
1137 endDate?: string // ISO 8601
1138 originallyPublishedStartDate?: string
1139 originallyPublishedEndDate?: string
1140
0b18f4aa
C
1141 durationMin?: number // seconds
1142 durationMax?: number // seconds
fbd67e7f 1143 uuids?: string[]
0b18f4aa 1144 }) {
d324756e 1145 VideoModel.throwIfPrivateIncludeWithoutUser(options.include, options.user)
527a52ac 1146 VideoModel.throwIfPrivacyOneOfWithoutUser(options.privacyOneOf, options.user)
d324756e 1147
f05a1c30 1148 const serverActor = await getServerActor()
1fd61899 1149
afd2cba5 1150 const queryOptions = {
9c9a236b 1151 ...pick(options, [
2760b454 1152 'include',
9c9a236b
C
1153 'nsfw',
1154 'isLive',
1155 'categoryOneOf',
1156 'licenceOneOf',
1157 'languageOneOf',
1158 'tagsOneOf',
1159 'tagsAllOf',
527a52ac 1160 'privacyOneOf',
9c9a236b 1161 'user',
2760b454 1162 'isLocal',
9c9a236b
C
1163 'host',
1164 'start',
1165 'count',
1166 'sort',
1167 'startDate',
1168 'endDate',
1169 'originallyPublishedStartDate',
1170 'originallyPublishedEndDate',
1171 'durationMin',
1172 'durationMax',
d324756e
C
1173 'hasHLSFiles',
1174 'hasWebtorrentFiles',
9c9a236b 1175 'uuids',
2760b454
C
1176 'search',
1177 'displayOnlyForFollower'
9c9a236b 1178 ]),
2760b454 1179 serverAccountIdForBlock: serverActor.Account.id
48dce1c9 1180 }
f05a1c30 1181
5f3e2425 1182 return VideoModel.getAvailableForApi(queryOptions)
f05a1c30
C
1183 }
1184
a056ca48
C
1185 static countLocalLives () {
1186 const options = {
1187 where: {
1188 remote: false,
875f0610
C
1189 isLive: true,
1190 state: {
1191 [Op.ne]: VideoState.LIVE_ENDED
1192 }
a056ca48
C
1193 }
1194 }
1195
1196 return VideoModel.count(options)
1197 }
1198
77d7e851
C
1199 static countVideosUploadedByUserSince (userId: number, since: Date) {
1200 const options = {
1201 include: [
1202 {
1203 model: VideoChannelModel.unscoped(),
1204 required: true,
1205 include: [
1206 {
1207 model: AccountModel.unscoped(),
1208 required: true,
1209 include: [
1210 {
1211 model: UserModel.unscoped(),
1212 required: true,
1213 where: {
1214 id: userId
1215 }
1216 }
1217 ]
1218 }
1219 ]
1220 }
1221 ],
1222 where: {
1223 createdAt: {
1224 [Op.gte]: since
1225 }
1226 }
1227 }
1228
1229 return VideoModel.unscoped().count(options)
1230 }
1231
a056ca48
C
1232 static countLivesOfAccount (accountId: number) {
1233 const options = {
1234 where: {
1235 remote: false,
fb4b3f91
C
1236 isLive: true,
1237 state: {
1238 [Op.ne]: VideoState.LIVE_ENDED
1239 }
a056ca48
C
1240 },
1241 include: [
1242 {
1243 required: true,
1244 model: VideoChannelModel.unscoped(),
1245 where: {
1246 accountId
1247 }
1248 }
1249 ]
1250 }
1251
1252 return VideoModel.count(options)
1253 }
1254
71d4af1e 1255 static load (id: number | string, transaction?: Transaction): Promise<MVideoThumbnail> {
3c10840f 1256 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
d8755eed 1257
71d4af1e 1258 return queryBuilder.queryVideo({ id, transaction, type: 'thumbnails' })
3fd3ab2d 1259 }
d8755eed 1260
71d4af1e 1261 static loadWithBlacklist (id: number | string, transaction?: Transaction): Promise<MVideoThumbnailBlacklist> {
3c10840f 1262 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
d636ab58 1263
71d4af1e 1264 return queryBuilder.queryVideo({ id, transaction, type: 'thumbnails-blacklist' })
d636ab58
C
1265 }
1266
b49f22d8 1267 static loadImmutableAttributes (id: number | string, t?: Transaction): Promise<MVideoImmutable> {
7eba5e1f 1268 const fun = () => {
943e5193
C
1269 const query = {
1270 where: buildWhereIdOrUUID(id),
7eba5e1f
C
1271 transaction: t
1272 }
1273
943e5193 1274 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
7eba5e1f
C
1275 }
1276
1277 return ModelCache.Instance.doCache({
943e5193 1278 cacheType: 'load-video-immutable-id',
7eba5e1f
C
1279 key: '' + id,
1280 deleteKey: 'video',
1281 fun
1282 })
1283 }
1284
b49f22d8 1285 static loadByUrlImmutableAttributes (url: string, transaction?: Transaction): Promise<MVideoImmutable> {
943e5193
C
1286 const fun = () => {
1287 const query: FindOptions = {
1288 where: {
1289 url
1290 },
1291 transaction
1292 }
1293
1294 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1295 }
1296
1297 return ModelCache.Instance.doCache({
1298 cacheType: 'load-video-immutable-url',
1299 key: url,
1300 deleteKey: 'video',
1301 fun
1302 })
1303 }
1304
71d4af1e 1305 static loadOnlyId (id: number | string, transaction?: Transaction): Promise<MVideoId> {
3c10840f 1306 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
627621c1 1307
71d4af1e 1308 return queryBuilder.queryVideo({ id, transaction, type: 'id' })
627621c1
C
1309 }
1310
71d4af1e 1311 static loadWithFiles (id: number | string, transaction?: Transaction, logging?: boolean): Promise<MVideoWithAllFiles> {
3c10840f 1312 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
627621c1 1313
71d4af1e
C
1314 return queryBuilder.queryVideo({ id, transaction, type: 'all-files', logging })
1315 }
fd45e8f4 1316
71d4af1e 1317 static loadByUrl (url: string, transaction?: Transaction): Promise<MVideoThumbnail> {
3c10840f 1318 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
09209296 1319
71d4af1e
C
1320 return queryBuilder.queryVideo({ url, transaction, type: 'thumbnails' })
1321 }
1322
1323 static loadByUrlAndPopulateAccount (url: string, transaction?: Transaction): Promise<MVideoAccountLightBlacklistAllFiles> {
3c10840f 1324 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
71d4af1e
C
1325
1326 return queryBuilder.queryVideo({ url, transaction, type: 'account-blacklist-files' })
1327 }
1328
1329 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Transaction, userId?: number): Promise<MVideoFullLight> {
3c10840f 1330 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
09209296 1331
71d4af1e 1332 return queryBuilder.queryVideo({ id, transaction: t, type: 'full-light', userId })
09209296
C
1333 }
1334
89cd1275 1335 static loadForGetAPI (parameters: {
a1587156 1336 id: number | string
ca4b4b2e 1337 transaction?: Transaction
89cd1275 1338 userId?: number
b49f22d8 1339 }): Promise<MVideoDetails> {
ca4b4b2e 1340 const { id, transaction, userId } = parameters
3c10840f 1341 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
09209296 1342
71d4af1e 1343 return queryBuilder.queryVideo({ id, transaction, type: 'api', userId })
da854ddd
C
1344 }
1345
09cababd
C
1346 static async getStats () {
1347 const totalLocalVideos = await VideoModel.count({
1348 where: {
1349 remote: false
1350 }
1351 })
09cababd
C
1352
1353 let totalLocalVideoViews = await VideoModel.sum('views', {
1354 where: {
1355 remote: false
1356 }
1357 })
baab47ca 1358
09cababd
C
1359 // Sequelize could return null...
1360 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1361
2760b454
C
1362 const serverActor = await getServerActor()
1363
baab47ca
C
1364 const { total: totalVideos } = await VideoModel.listForApi({
1365 start: 0,
1366 count: 0,
1367 sort: '-publishedAt',
1368 nsfw: buildNSFWFilter(),
2760b454
C
1369 displayOnlyForFollower: {
1370 actorId: serverActor.id,
1371 orLocalVideos: true
3c10840f 1372 }
baab47ca
C
1373 })
1374
09cababd
C
1375 return {
1376 totalLocalVideos,
1377 totalLocalVideoViews,
1378 totalVideos
1379 }
1380 }
1381
6b616860
C
1382 static incrementViews (id: number, views: number) {
1383 return VideoModel.increment('views', {
1384 by: views,
1385 where: {
1386 id
1387 }
1388 })
1389 }
1390
74d249bc
C
1391 static updateRatesOf (videoId: number, type: VideoRateType, t: Transaction) {
1392 const field = type === 'like'
1393 ? 'likes'
1394 : 'dislikes'
1395
1396 const rawQuery = `UPDATE "video" SET "${field}" = ` +
1397 '(' +
69322042 1398 'SELECT COUNT(id) FROM "accountVideoRate" WHERE "accountVideoRate"."videoId" = "video"."id" AND type = :rateType' +
74d249bc
C
1399 ') ' +
1400 'WHERE "video"."id" = :videoId'
1401
1402 return AccountVideoRateModel.sequelize.query(rawQuery, {
1403 transaction: t,
1404 replacements: { videoId, rateType: type },
1405 type: QueryTypes.UPDATE
1406 })
1407 }
1408
8d427346
C
1409 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1410 // Instances only share videos
1411 const query = 'SELECT 1 FROM "videoShare" ' +
a1587156 1412 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
f046e2fa 1413 'WHERE "actorFollow"."actorId" = $followerActorId AND "actorFollow"."state" = \'accepted\' AND "videoShare"."videoId" = $videoId ' +
a1587156 1414 'LIMIT 1'
8d427346
C
1415
1416 const options = {
d5d9b6d7 1417 type: QueryTypes.SELECT as QueryTypes.SELECT,
8d427346
C
1418 bind: { followerActorId, videoId },
1419 raw: true
1420 }
1421
1422 return VideoModel.sequelize.query(query, options)
1423 .then(results => results.length === 1)
1424 }
1425
69322042 1426 static bulkUpdateSupportField (ofChannel: MChannel, t: Transaction) {
7d14d4d2
C
1427 const options = {
1428 where: {
69322042 1429 channelId: ofChannel.id
7d14d4d2
C
1430 },
1431 transaction: t
1432 }
1433
69322042 1434 return VideoModel.update({ support: ofChannel.support }, options)
7d14d4d2
C
1435 }
1436
b49f22d8 1437 static getAllIdsFromChannel (videoChannel: MChannelId): Promise<number[]> {
7d14d4d2
C
1438 const query = {
1439 attributes: [ 'id' ],
1440 where: {
1441 channelId: videoChannel.id
1442 }
1443 }
1444
1445 return VideoModel.findAll(query)
a1587156 1446 .then(videos => videos.map(v => v.id))
7d14d4d2
C
1447 }
1448
2d3741d6 1449 // threshold corresponds to how many video the field should have to be returned
7348b1fd 1450 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
65b21c96 1451 const serverActor = await getServerActor()
7348b1fd 1452
e5dbd508 1453 const queryOptions: BuildVideosListQueryOptions = {
5f3e2425
C
1454 attributes: [ `"${field}"` ],
1455 group: `GROUP BY "${field}"`,
1456 having: `HAVING COUNT("${field}") >= ${threshold}`,
1457 start: 0,
1458 sort: 'random',
1459 count,
2760b454
C
1460 serverAccountIdForBlock: serverActor.Account.id,
1461 displayOnlyForFollower: {
1462 actorId: serverActor.id,
1463 orLocalVideos: true
1464 }
7348b1fd
C
1465 }
1466
e5dbd508 1467 const queryBuilder = new VideosIdListQueryBuilder(VideoModel.sequelize)
2d3741d6 1468
e5dbd508
C
1469 return queryBuilder.queryVideoIds(queryOptions)
1470 .then(rows => rows.map(r => r[field]))
2d3741d6
C
1471 }
1472
b36f41ca
C
1473 static buildTrendingQuery (trendingDays: number) {
1474 return {
1475 attributes: [],
1476 subQuery: false,
1477 model: VideoViewModel,
1478 required: false,
1479 where: {
1480 startDate: {
a1587156 1481 [Op.gte]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
b36f41ca
C
1482 }
1483 }
1484 }
1485 }
1486
6e46de09 1487 private static async getAvailableForApi (
e5dbd508 1488 options: BuildVideosListQueryOptions,
6e46de09 1489 countVideos = true
b84d4c80 1490 ): Promise<ResultList<VideoModel>> {
6b842050
C
1491 function getCount () {
1492 if (countVideos !== true) return Promise.resolve(undefined)
8ea6f49a 1493
6b842050 1494 const countOptions = Object.assign({}, options, { isCount: true })
e5dbd508 1495 const queryBuilder = new VideosIdListQueryBuilder(VideoModel.sequelize)
3caf77d3 1496
e5dbd508 1497 return queryBuilder.countVideoIds(countOptions)
6b842050
C
1498 }
1499
1500 function getModels () {
baab47ca
C
1501 if (options.count === 0) return Promise.resolve([])
1502
e5dbd508 1503 const queryBuilder = new VideosModelListQueryBuilder(VideoModel.sequelize)
6b842050 1504
e5dbd508 1505 return queryBuilder.queryVideos(options)
6b842050
C
1506 }
1507
1508 const [ count, rows ] = await Promise.all([ getCount(), getModels() ])
afd2cba5 1509
ddc07312
C
1510 return {
1511 data: rows,
1512 total: count
1513 }
1514 }
1515
d324756e
C
1516 private static throwIfPrivateIncludeWithoutUser (include: VideoInclude, user: MUserAccountId) {
1517 if (VideoModel.isPrivateInclude(include) && !user?.hasRight(UserRight.SEE_ALL_VIDEOS)) {
527a52ac
C
1518 throw new Error('Try to filter all-local but user cannot see all videos')
1519 }
1520 }
1521
1522 private static throwIfPrivacyOneOfWithoutUser (privacyOneOf: VideoPrivacy[], user: MUserAccountId) {
1523 if (privacyOneOf && !user?.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1524 throw new Error('Try to choose video privacies but user cannot see all videos')
d324756e
C
1525 }
1526 }
1527
3c10840f
C
1528 private static isPrivateInclude (include: VideoInclude) {
1529 return include & VideoInclude.BLACKLISTED ||
1530 include & VideoInclude.BLOCKED_OWNER ||
3c10840f
C
1531 include & VideoInclude.NOT_PUBLISHED_STATE
1532 }
1533
5b77537c
C
1534 isBlacklisted () {
1535 return !!this.VideoBlacklist
1536 }
1537
bfbd9128 1538 isBlocked () {
faa9d434 1539 return this.VideoChannel.Account.Actor.Server?.isBlocked() || this.VideoChannel.Account.isBlocked()
bfbd9128
C
1540 }
1541
a1587156 1542 getQualityFileBy<T extends MVideoWithFile> (this: T, fun: (files: MVideoFile[], it: (file: MVideoFile) => number) => MVideoFile) {
24516aa2 1543 // We first transcode to WebTorrent format, so try this array first
d7a25329 1544 if (Array.isArray(this.VideoFiles) && this.VideoFiles.length !== 0) {
92e0f42e 1545 const file = fun(this.VideoFiles, file => file.resolution)
d7a25329
C
1546
1547 return Object.assign(file, { Video: this })
1548 }
1549
1550 // No webtorrent files, try with streaming playlist files
1551 if (Array.isArray(this.VideoStreamingPlaylists) && this.VideoStreamingPlaylists.length !== 0) {
1552 const streamingPlaylistWithVideo = Object.assign(this.VideoStreamingPlaylists[0], { Video: this })
1553
92e0f42e 1554 const file = fun(streamingPlaylistWithVideo.VideoFiles, file => file.resolution)
d7a25329
C
1555 return Object.assign(file, { VideoStreamingPlaylist: streamingPlaylistWithVideo })
1556 }
aaf61f38 1557
d7a25329 1558 return undefined
e4f97bab 1559 }
aaf61f38 1560
a1587156 1561 getMaxQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
92e0f42e
C
1562 return this.getQualityFileBy(maxBy)
1563 }
1564
a1587156 1565 getMinQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
92e0f42e
C
1566 return this.getQualityFileBy(minBy)
1567 }
1568
a1587156 1569 getWebTorrentFile<T extends MVideoWithFile> (this: T, resolution: number): MVideoFileVideo {
29d4e137
C
1570 if (Array.isArray(this.VideoFiles) === false) return undefined
1571
d7a25329
C
1572 const file = this.VideoFiles.find(f => f.resolution === resolution)
1573 if (!file) return undefined
1574
1575 return Object.assign(file, { Video: this })
29d4e137
C
1576 }
1577
6939cbac
C
1578 hasWebTorrentFiles () {
1579 return Array.isArray(this.VideoFiles) === true && this.VideoFiles.length !== 0
1580 }
1581
28dfb44b 1582 async addAndSaveThumbnail (thumbnail: MThumbnail, transaction?: Transaction) {
3acc5084
C
1583 thumbnail.videoId = this.id
1584
1585 const savedThumbnail = await thumbnail.save({ transaction })
1586
e8bafea3
C
1587 if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = []
1588
17ddba49 1589 this.Thumbnails = this.Thumbnails.filter(t => t.id !== savedThumbnail.id)
3acc5084 1590 this.Thumbnails.push(savedThumbnail)
e8bafea3
C
1591 }
1592
3acc5084 1593 getMiniature () {
e8bafea3
C
1594 if (Array.isArray(this.Thumbnails) === false) return undefined
1595
3acc5084 1596 return this.Thumbnails.find(t => t.type === ThumbnailType.MINIATURE)
e8bafea3
C
1597 }
1598
6872996d
C
1599 hasPreview () {
1600 return !!this.getPreview()
1601 }
1602
e8bafea3
C
1603 getPreview () {
1604 if (Array.isArray(this.Thumbnails) === false) return undefined
1605
1606 return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW)
3fd3ab2d 1607 }
7b1f49de 1608
3fd3ab2d
C
1609 isOwned () {
1610 return this.remote === false
9567011b
C
1611 }
1612
cef534ed 1613 getWatchStaticPath () {
29837f88 1614 return buildVideoWatchPath({ shortUUID: uuidToShort(this.uuid) })
cef534ed
C
1615 }
1616
40e87e9e 1617 getEmbedStaticPath () {
15a7eafb 1618 return buildVideoEmbedPath(this)
3fd3ab2d 1619 }
e4f97bab 1620
3acc5084
C
1621 getMiniatureStaticPath () {
1622 const thumbnail = this.getMiniature()
e8bafea3
C
1623 if (!thumbnail) return null
1624
1625 return join(STATIC_PATHS.THUMBNAILS, thumbnail.filename)
e4f97bab 1626 }
227d02fe 1627
40e87e9e 1628 getPreviewStaticPath () {
e8bafea3
C
1629 const preview = this.getPreview()
1630 if (!preview) return null
1631
1632 // We use a local cache, so specify our cache endpoint instead of potential remote URL
557b13ae 1633 return join(LAZY_STATIC_PATHS.PREVIEWS, preview.filename)
3fd3ab2d 1634 }
40298b02 1635
b5fecbf4 1636 toFormattedJSON (this: MVideoFormattable, options?: VideoFormattingJSONOptions): Video {
098eb377 1637 return videoModelToFormattedJSON(this, options)
14d3270f 1638 }
14d3270f 1639
b5fecbf4 1640 toFormattedDetailsJSON (this: MVideoFormattableDetails): VideoDetails {
098eb377 1641 return videoModelToFormattedDetailsJSON(this)
244e76a5
RK
1642 }
1643
f66db4d5 1644 getFormattedVideoFilesJSON (includeMagnet = true): VideoFile[] {
7a499487 1645 let files: VideoFile[] = []
97816649 1646
97816649 1647 if (Array.isArray(this.VideoFiles)) {
f66db4d5 1648 const result = videoFilesModelToFormattedJSON(this, this.VideoFiles, includeMagnet)
7a499487 1649 files = files.concat(result)
97816649
C
1650 }
1651
1652 for (const p of (this.VideoStreamingPlaylists || [])) {
f66db4d5 1653 const result = videoFilesModelToFormattedJSON(this, p.VideoFiles, includeMagnet)
7a499487 1654 files = files.concat(result)
97816649
C
1655 }
1656
7a499487 1657 return files
3fd3ab2d 1658 }
e4f97bab 1659
de6310b2 1660 toActivityPubObject (this: MVideoAP): VideoObject {
098eb377 1661 return videoModelToActivityPubObject(this)
3fd3ab2d
C
1662 }
1663
1664 getTruncatedDescription () {
1665 if (!this.description) return null
93e1258c 1666
bffbebbe 1667 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
687c6180 1668 return peertubeTruncate(this.description, { length: maxLength })
93e1258c
C
1669 }
1670
d7a25329
C
1671 getMaxQualityResolution () {
1672 const file = this.getMaxQualityFile()
1673 const videoOrPlaylist = file.getVideoOrStreamingPlaylist()
0d0e8dd0 1674
ad5db104 1675 return VideoPathManager.Instance.makeAvailableVideoFile(file.withVideoOrPlaylist(videoOrPlaylist), originalFilePath => {
0305db28
JB
1676 return getVideoFileResolution(originalFilePath)
1677 })
3fd3ab2d 1678 }
0d0e8dd0 1679
96f29c0f 1680 getDescriptionAPIPath () {
3fd3ab2d 1681 return `/api/${API_VERSION}/videos/${this.uuid}/description`
feb4bdfd
C
1682 }
1683
d7a25329 1684 getHLSPlaylist (): MStreamingPlaylistFilesVideo {
e2600d8b
C
1685 if (!this.VideoStreamingPlaylists) return undefined
1686
d7a25329 1687 const playlist = this.VideoStreamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
e1ab52d7 1688 if (!playlist) return undefined
1689
d7a25329
C
1690 playlist.Video = this
1691
1692 return playlist
e2600d8b
C
1693 }
1694
d7a25329
C
1695 setHLSPlaylist (playlist: MStreamingPlaylist) {
1696 const toAdd = [ playlist ] as [ VideoStreamingPlaylistModel ]
b9fffa29 1697
d7a25329
C
1698 if (Array.isArray(this.VideoStreamingPlaylists) === false || this.VideoStreamingPlaylists.length === 0) {
1699 this.VideoStreamingPlaylists = toAdd
1700 return
1701 }
1702
1703 this.VideoStreamingPlaylists = this.VideoStreamingPlaylists
a1587156
C
1704 .filter(s => s.type !== VideoStreamingPlaylistType.HLS)
1705 .concat(toAdd)
d7a25329
C
1706 }
1707
b46cf4b9 1708 removeWebTorrentFileAndTorrent (videoFile: MVideoFile, isRedundancy = false) {
0305db28
JB
1709 const filePath = isRedundancy
1710 ? VideoPathManager.Instance.getFSRedundancyVideoFilePath(this, videoFile)
1711 : VideoPathManager.Instance.getFSVideoFileOutputPath(this, videoFile)
764b1a14
C
1712
1713 const promises: Promise<any>[] = [ remove(filePath) ]
1714 if (!isRedundancy) promises.push(videoFile.removeTorrent())
1715
0305db28
JB
1716 if (videoFile.storage === VideoStorage.OBJECT_STORAGE) {
1717 promises.push(removeWebTorrentObjectStorage(videoFile))
1718 }
1719
764b1a14 1720 return Promise.all(promises)
feb4bdfd
C
1721 }
1722
ffc65cbd 1723 async removeStreamingPlaylistFiles (streamingPlaylist: MStreamingPlaylist, isRedundancy = false) {
0305db28
JB
1724 const directoryPath = isRedundancy
1725 ? getHLSRedundancyDirectory(this)
1726 : getHLSDirectory(this)
09209296 1727
ffc65cbd
C
1728 await remove(directoryPath)
1729
1730 if (isRedundancy !== true) {
a1587156 1731 const streamingPlaylistWithFiles = streamingPlaylist as MStreamingPlaylistFilesVideo
ffc65cbd
C
1732 streamingPlaylistWithFiles.Video = this
1733
1734 if (!Array.isArray(streamingPlaylistWithFiles.VideoFiles)) {
1735 streamingPlaylistWithFiles.VideoFiles = await streamingPlaylistWithFiles.$get('VideoFiles')
1736 }
1737
1738 // Remove physical files and torrents
1739 await Promise.all(
90a8bd30 1740 streamingPlaylistWithFiles.VideoFiles.map(file => file.removeTorrent())
ffc65cbd 1741 )
0305db28
JB
1742
1743 if (streamingPlaylist.storage === VideoStorage.OBJECT_STORAGE) {
ad5db104 1744 await removeHLSObjectStorage(streamingPlaylist.withVideo(this))
0305db28 1745 }
ffc65cbd 1746 }
09209296
C
1747 }
1748
1297eb5d
C
1749 isOutdated () {
1750 if (this.isOwned()) return false
1751
9f79ade6 1752 return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)
1297eb5d
C
1753 }
1754
22a73cb8 1755 hasPrivacyForFederation () {
3092e9bb 1756 return isPrivacyForFederation(this.privacy)
22a73cb8
C
1757 }
1758
68e70a74
C
1759 hasStateForFederation () {
1760 return isStateForFederation(this.state)
1761 }
1762
22a73cb8 1763 isNewVideo (newPrivacy: VideoPrivacy) {
3092e9bb 1764 return this.hasPrivacyForFederation() === false && isPrivacyForFederation(newPrivacy) === true
22a73cb8
C
1765 }
1766
597f771f
C
1767 setAsRefreshed (transaction?: Transaction) {
1768 return setAsUpdated('video', this.id, transaction)
04b8c3fb
C
1769 }
1770
22a73cb8
C
1771 requiresAuth () {
1772 return this.privacy === VideoPrivacy.PRIVATE || this.privacy === VideoPrivacy.INTERNAL || !!this.VideoBlacklist
1773 }
1774
1775 setPrivacy (newPrivacy: VideoPrivacy) {
1776 if (this.privacy === VideoPrivacy.PRIVATE && newPrivacy !== VideoPrivacy.PRIVATE) {
1777 this.publishedAt = new Date()
1778 }
1779
1780 this.privacy = newPrivacy
1781 }
1782
1783 isConfidential () {
1784 return this.privacy === VideoPrivacy.PRIVATE ||
1785 this.privacy === VideoPrivacy.UNLISTED ||
1786 this.privacy === VideoPrivacy.INTERNAL
1787 }
1788
9db2330e 1789 async setNewState (newState: VideoState, isNewVideo: boolean, transaction: Transaction) {
0305db28
JB
1790 if (this.state === newState) throw new Error('Cannot use same state ' + newState)
1791
1792 this.state = newState
7920c273 1793
9db2330e 1794 if (this.state === VideoState.PUBLISHED && isNewVideo) {
0305db28 1795 this.publishedAt = new Date()
6fcd19ba 1796 }
aaf61f38 1797
0305db28 1798 await this.save({ transaction })
15d4ee04 1799 }
a96aed15 1800
e1ab52d7 1801 getBandwidthBits (this: MVideo, videoFile: MVideoFile) {
d9a2a031 1802 return Math.ceil((videoFile.size * 8) / this.duration)
c48e82b5
C
1803 }
1804
d9a2a031
C
1805 getTrackerUrls () {
1806 if (this.isOwned()) {
1807 return [
1808 WEBSERVER.URL + '/tracker/announce',
1809 WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT + '/tracker/socket'
1810 ]
1811 }
09209296 1812
d9a2a031 1813 return this.Trackers.map(t => t.url)
09209296 1814 }
a96aed15 1815}