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