]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/models/video/video.ts
Merge branch 'release/4.2.0' into develop
[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
a6585874 975 function buildBaseQuery (forCount: boolean): 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 {
a6585874
C
1004 model: forCount
1005 ? AccountModel.unscoped()
1006 : AccountModel,
3acc5084
C
1007 where: {
1008 id: accountId
1009 },
1010 required: true
1011 }
1012 ]
1013 }
1014 ]
1015 }
bf64ed41 1016
bf64ed41 1017 return baseQuery
3fd3ab2d 1018 }
d8755eed 1019
a6585874
C
1020 const countQuery = buildBaseQuery(true)
1021 const findQuery = buildBaseQuery(false)
3acc5084 1022
bf64ed41 1023 const findScopes: (string | ScopeOptions)[] = [
a18f275d
C
1024 ScopeNames.WITH_SCHEDULED_UPDATE,
1025 ScopeNames.WITH_BLACKLISTED,
1026 ScopeNames.WITH_THUMBNAILS
1027 ]
3acc5084 1028
3acc5084
C
1029 return Promise.all([
1030 VideoModel.count(countQuery),
0283eaac 1031 VideoModel.scope(findScopes).findAll<MVideoForUser>(findQuery)
3acc5084
C
1032 ]).then(([ count, rows ]) => {
1033 return {
0283eaac 1034 data: rows,
3acc5084
C
1035 total: count
1036 }
1037 })
3fd3ab2d 1038 }
93e1258c 1039
48dce1c9 1040 static async listForApi (options: {
a1587156
C
1041 start: number
1042 count: number
1043 sort: string
1fd61899 1044
a1587156 1045 nsfw: boolean
1fd61899 1046 isLive?: boolean
2760b454
C
1047 isLocal?: boolean
1048 include?: VideoInclude
1fd61899 1049
3c10840f 1050 hasFiles?: boolean // default false
d324756e
C
1051 hasWebtorrentFiles?: boolean
1052 hasHLSFiles?: boolean
1fd61899 1053
a1587156
C
1054 categoryOneOf?: number[]
1055 licenceOneOf?: number[]
1056 languageOneOf?: string[]
1057 tagsOneOf?: string[]
1058 tagsAllOf?: string[]
527a52ac 1059 privacyOneOf?: VideoPrivacy[]
1fd61899 1060
a1587156
C
1061 accountId?: number
1062 videoChannelId?: number
1fd61899 1063
2760b454 1064 displayOnlyForFollower: DisplayOnlyForFollowerOptions | null
1fd61899 1065
a1587156 1066 videoPlaylistId?: number
1fd61899 1067
a1587156 1068 trendingDays?: number
1fd61899 1069
a1587156
C
1070 user?: MUserAccountId
1071 historyOfUser?: MUserId
1fd61899 1072
fe987656 1073 countVideos?: boolean
1fd61899 1074
d8b34ee5 1075 search?: string
fe987656 1076 }) {
d324756e 1077 VideoModel.throwIfPrivateIncludeWithoutUser(options.include, options.user)
527a52ac 1078 VideoModel.throwIfPrivacyOneOfWithoutUser(options.privacyOneOf, options.user)
1cd3facc 1079
5f3e2425
C
1080 const trendingDays = options.sort.endsWith('trending')
1081 ? CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1082 : undefined
d6886027
C
1083
1084 let trendingAlgorithm: string
3d4e112d
RK
1085 if (options.sort.endsWith('hot')) trendingAlgorithm = 'hot'
1086 if (options.sort.endsWith('best')) trendingAlgorithm = 'best'
93e1258c 1087
7ad9b984
C
1088 const serverActor = await getServerActor()
1089
afd2cba5 1090 const queryOptions = {
9c9a236b
C
1091 ...pick(options, [
1092 'start',
1093 'count',
1094 'sort',
1095 'nsfw',
1096 'isLive',
1097 'categoryOneOf',
1098 'licenceOneOf',
1099 'languageOneOf',
1100 'tagsOneOf',
1101 'tagsAllOf',
527a52ac 1102 'privacyOneOf',
2760b454
C
1103 'isLocal',
1104 'include',
1105 'displayOnlyForFollower',
3c10840f 1106 'hasFiles',
9c9a236b
C
1107 'accountId',
1108 'videoChannelId',
1109 'videoPlaylistId',
9c9a236b
C
1110 'user',
1111 'historyOfUser',
d324756e
C
1112 'hasHLSFiles',
1113 'hasWebtorrentFiles',
9c9a236b
C
1114 'search'
1115 ]),
1116
2760b454 1117 serverAccountIdForBlock: serverActor.Account.id,
d8b34ee5 1118 trendingDays,
9c9a236b 1119 trendingAlgorithm
48dce1c9
C
1120 }
1121
5f3e2425 1122 return VideoModel.getAvailableForApi(queryOptions, options.countVideos)
93e1258c
C
1123 }
1124
0b18f4aa 1125 static async searchAndPopulateAccountAndServer (options: {
9c9a236b
C
1126 start: number
1127 count: number
1128 sort: string
d324756e 1129
0b18f4aa 1130 nsfw?: boolean
1fd61899 1131 isLive?: boolean
2760b454
C
1132 isLocal?: boolean
1133 include?: VideoInclude
d324756e 1134
0b18f4aa
C
1135 categoryOneOf?: number[]
1136 licenceOneOf?: number[]
1137 languageOneOf?: string[]
1138 tagsOneOf?: string[]
1139 tagsAllOf?: string[]
527a52ac 1140 privacyOneOf?: VideoPrivacy[]
d324756e
C
1141
1142 displayOnlyForFollower: DisplayOnlyForFollowerOptions | null
1143
1144 user?: MUserAccountId
1145
1146 hasWebtorrentFiles?: boolean
1147 hasHLSFiles?: boolean
1148
1149 search?: string
1150
1151 host?: string
1152 startDate?: string // ISO 8601
1153 endDate?: string // ISO 8601
1154 originallyPublishedStartDate?: string
1155 originallyPublishedEndDate?: string
1156
0b18f4aa
C
1157 durationMin?: number // seconds
1158 durationMax?: number // seconds
fbd67e7f 1159 uuids?: string[]
0b18f4aa 1160 }) {
d324756e 1161 VideoModel.throwIfPrivateIncludeWithoutUser(options.include, options.user)
527a52ac 1162 VideoModel.throwIfPrivacyOneOfWithoutUser(options.privacyOneOf, options.user)
d324756e 1163
f05a1c30 1164 const serverActor = await getServerActor()
1fd61899 1165
afd2cba5 1166 const queryOptions = {
9c9a236b 1167 ...pick(options, [
2760b454 1168 'include',
9c9a236b
C
1169 'nsfw',
1170 'isLive',
1171 'categoryOneOf',
1172 'licenceOneOf',
1173 'languageOneOf',
1174 'tagsOneOf',
1175 'tagsAllOf',
527a52ac 1176 'privacyOneOf',
9c9a236b 1177 'user',
2760b454 1178 'isLocal',
9c9a236b
C
1179 'host',
1180 'start',
1181 'count',
1182 'sort',
1183 'startDate',
1184 'endDate',
1185 'originallyPublishedStartDate',
1186 'originallyPublishedEndDate',
1187 'durationMin',
1188 'durationMax',
d324756e
C
1189 'hasHLSFiles',
1190 'hasWebtorrentFiles',
9c9a236b 1191 'uuids',
2760b454
C
1192 'search',
1193 'displayOnlyForFollower'
9c9a236b 1194 ]),
2760b454 1195 serverAccountIdForBlock: serverActor.Account.id
48dce1c9 1196 }
f05a1c30 1197
5f3e2425 1198 return VideoModel.getAvailableForApi(queryOptions)
f05a1c30
C
1199 }
1200
a056ca48
C
1201 static countLocalLives () {
1202 const options = {
1203 where: {
1204 remote: false,
875f0610
C
1205 isLive: true,
1206 state: {
1207 [Op.ne]: VideoState.LIVE_ENDED
1208 }
a056ca48
C
1209 }
1210 }
1211
1212 return VideoModel.count(options)
1213 }
1214
77d7e851
C
1215 static countVideosUploadedByUserSince (userId: number, since: Date) {
1216 const options = {
1217 include: [
1218 {
1219 model: VideoChannelModel.unscoped(),
1220 required: true,
1221 include: [
1222 {
1223 model: AccountModel.unscoped(),
1224 required: true,
1225 include: [
1226 {
1227 model: UserModel.unscoped(),
1228 required: true,
1229 where: {
1230 id: userId
1231 }
1232 }
1233 ]
1234 }
1235 ]
1236 }
1237 ],
1238 where: {
1239 createdAt: {
1240 [Op.gte]: since
1241 }
1242 }
1243 }
1244
1245 return VideoModel.unscoped().count(options)
1246 }
1247
a056ca48
C
1248 static countLivesOfAccount (accountId: number) {
1249 const options = {
1250 where: {
1251 remote: false,
fb4b3f91
C
1252 isLive: true,
1253 state: {
1254 [Op.ne]: VideoState.LIVE_ENDED
1255 }
a056ca48
C
1256 },
1257 include: [
1258 {
1259 required: true,
1260 model: VideoChannelModel.unscoped(),
1261 where: {
1262 accountId
1263 }
1264 }
1265 ]
1266 }
1267
1268 return VideoModel.count(options)
1269 }
1270
71d4af1e 1271 static load (id: number | string, transaction?: Transaction): Promise<MVideoThumbnail> {
3c10840f 1272 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
d8755eed 1273
71d4af1e 1274 return queryBuilder.queryVideo({ id, transaction, type: 'thumbnails' })
3fd3ab2d 1275 }
d8755eed 1276
71d4af1e 1277 static loadWithBlacklist (id: number | string, transaction?: Transaction): Promise<MVideoThumbnailBlacklist> {
3c10840f 1278 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
d636ab58 1279
71d4af1e 1280 return queryBuilder.queryVideo({ id, transaction, type: 'thumbnails-blacklist' })
d636ab58
C
1281 }
1282
b49f22d8 1283 static loadImmutableAttributes (id: number | string, t?: Transaction): Promise<MVideoImmutable> {
7eba5e1f 1284 const fun = () => {
943e5193
C
1285 const query = {
1286 where: buildWhereIdOrUUID(id),
7eba5e1f
C
1287 transaction: t
1288 }
1289
943e5193 1290 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
7eba5e1f
C
1291 }
1292
1293 return ModelCache.Instance.doCache({
943e5193 1294 cacheType: 'load-video-immutable-id',
7eba5e1f
C
1295 key: '' + id,
1296 deleteKey: 'video',
1297 fun
1298 })
1299 }
1300
b49f22d8 1301 static loadByUrlImmutableAttributes (url: string, transaction?: Transaction): Promise<MVideoImmutable> {
943e5193
C
1302 const fun = () => {
1303 const query: FindOptions = {
1304 where: {
1305 url
1306 },
1307 transaction
1308 }
1309
1310 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1311 }
1312
1313 return ModelCache.Instance.doCache({
1314 cacheType: 'load-video-immutable-url',
1315 key: url,
1316 deleteKey: 'video',
1317 fun
1318 })
1319 }
1320
71d4af1e 1321 static loadOnlyId (id: number | string, transaction?: Transaction): Promise<MVideoId> {
3c10840f 1322 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
627621c1 1323
71d4af1e 1324 return queryBuilder.queryVideo({ id, transaction, type: 'id' })
627621c1
C
1325 }
1326
71d4af1e 1327 static loadWithFiles (id: number | string, transaction?: Transaction, logging?: boolean): Promise<MVideoWithAllFiles> {
3c10840f 1328 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
627621c1 1329
71d4af1e
C
1330 return queryBuilder.queryVideo({ id, transaction, type: 'all-files', logging })
1331 }
fd45e8f4 1332
71d4af1e 1333 static loadByUrl (url: string, transaction?: Transaction): Promise<MVideoThumbnail> {
3c10840f 1334 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
09209296 1335
71d4af1e
C
1336 return queryBuilder.queryVideo({ url, transaction, type: 'thumbnails' })
1337 }
1338
1339 static loadByUrlAndPopulateAccount (url: string, transaction?: Transaction): Promise<MVideoAccountLightBlacklistAllFiles> {
3c10840f 1340 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
71d4af1e
C
1341
1342 return queryBuilder.queryVideo({ url, transaction, type: 'account-blacklist-files' })
1343 }
1344
1345 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Transaction, userId?: number): Promise<MVideoFullLight> {
3c10840f 1346 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
09209296 1347
71d4af1e 1348 return queryBuilder.queryVideo({ id, transaction: t, type: 'full-light', userId })
09209296
C
1349 }
1350
89cd1275 1351 static loadForGetAPI (parameters: {
a1587156 1352 id: number | string
ca4b4b2e 1353 transaction?: Transaction
89cd1275 1354 userId?: number
b49f22d8 1355 }): Promise<MVideoDetails> {
ca4b4b2e 1356 const { id, transaction, userId } = parameters
3c10840f 1357 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
09209296 1358
71d4af1e 1359 return queryBuilder.queryVideo({ id, transaction, type: 'api', userId })
da854ddd
C
1360 }
1361
09cababd
C
1362 static async getStats () {
1363 const totalLocalVideos = await VideoModel.count({
1364 where: {
1365 remote: false
1366 }
1367 })
09cababd
C
1368
1369 let totalLocalVideoViews = await VideoModel.sum('views', {
1370 where: {
1371 remote: false
1372 }
1373 })
baab47ca 1374
09cababd
C
1375 // Sequelize could return null...
1376 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1377
2760b454
C
1378 const serverActor = await getServerActor()
1379
baab47ca
C
1380 const { total: totalVideos } = await VideoModel.listForApi({
1381 start: 0,
1382 count: 0,
1383 sort: '-publishedAt',
1384 nsfw: buildNSFWFilter(),
2760b454
C
1385 displayOnlyForFollower: {
1386 actorId: serverActor.id,
1387 orLocalVideos: true
3c10840f 1388 }
baab47ca
C
1389 })
1390
09cababd
C
1391 return {
1392 totalLocalVideos,
1393 totalLocalVideoViews,
1394 totalVideos
1395 }
1396 }
1397
6b616860
C
1398 static incrementViews (id: number, views: number) {
1399 return VideoModel.increment('views', {
1400 by: views,
1401 where: {
1402 id
1403 }
1404 })
1405 }
1406
57e4e1c1
C
1407 static updateRatesOf (videoId: number, type: VideoRateType, count: number, t: Transaction) {
1408 const field = type === 'like'
1409 ? 'likes'
1410 : 'dislikes'
1411
1412 const rawQuery = `UPDATE "video" SET "${field}" = :count WHERE "video"."id" = :videoId`
1413
1414 return AccountVideoRateModel.sequelize.query(rawQuery, {
1415 transaction: t,
1416 replacements: { videoId, rateType: type, count },
1417 type: QueryTypes.UPDATE
1418 })
1419 }
1420
1421 static syncLocalRates (videoId: number, type: VideoRateType, t: Transaction) {
74d249bc
C
1422 const field = type === 'like'
1423 ? 'likes'
1424 : 'dislikes'
1425
1426 const rawQuery = `UPDATE "video" SET "${field}" = ` +
1427 '(' +
69322042 1428 'SELECT COUNT(id) FROM "accountVideoRate" WHERE "accountVideoRate"."videoId" = "video"."id" AND type = :rateType' +
74d249bc
C
1429 ') ' +
1430 'WHERE "video"."id" = :videoId'
1431
1432 return AccountVideoRateModel.sequelize.query(rawQuery, {
1433 transaction: t,
1434 replacements: { videoId, rateType: type },
1435 type: QueryTypes.UPDATE
1436 })
1437 }
1438
8d427346
C
1439 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1440 // Instances only share videos
1441 const query = 'SELECT 1 FROM "videoShare" ' +
a1587156 1442 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
f046e2fa 1443 'WHERE "actorFollow"."actorId" = $followerActorId AND "actorFollow"."state" = \'accepted\' AND "videoShare"."videoId" = $videoId ' +
a1587156 1444 'LIMIT 1'
8d427346
C
1445
1446 const options = {
d5d9b6d7 1447 type: QueryTypes.SELECT as QueryTypes.SELECT,
8d427346
C
1448 bind: { followerActorId, videoId },
1449 raw: true
1450 }
1451
1452 return VideoModel.sequelize.query(query, options)
1453 .then(results => results.length === 1)
1454 }
1455
69322042 1456 static bulkUpdateSupportField (ofChannel: MChannel, t: Transaction) {
7d14d4d2
C
1457 const options = {
1458 where: {
69322042 1459 channelId: ofChannel.id
7d14d4d2
C
1460 },
1461 transaction: t
1462 }
1463
69322042 1464 return VideoModel.update({ support: ofChannel.support }, options)
7d14d4d2
C
1465 }
1466
b49f22d8 1467 static getAllIdsFromChannel (videoChannel: MChannelId): Promise<number[]> {
7d14d4d2
C
1468 const query = {
1469 attributes: [ 'id' ],
1470 where: {
1471 channelId: videoChannel.id
1472 }
1473 }
1474
1475 return VideoModel.findAll(query)
a1587156 1476 .then(videos => videos.map(v => v.id))
7d14d4d2
C
1477 }
1478
2d3741d6 1479 // threshold corresponds to how many video the field should have to be returned
7348b1fd 1480 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
65b21c96 1481 const serverActor = await getServerActor()
7348b1fd 1482
e5dbd508 1483 const queryOptions: BuildVideosListQueryOptions = {
5f3e2425
C
1484 attributes: [ `"${field}"` ],
1485 group: `GROUP BY "${field}"`,
1486 having: `HAVING COUNT("${field}") >= ${threshold}`,
1487 start: 0,
1488 sort: 'random',
1489 count,
2760b454
C
1490 serverAccountIdForBlock: serverActor.Account.id,
1491 displayOnlyForFollower: {
1492 actorId: serverActor.id,
1493 orLocalVideos: true
1494 }
7348b1fd
C
1495 }
1496
e5dbd508 1497 const queryBuilder = new VideosIdListQueryBuilder(VideoModel.sequelize)
2d3741d6 1498
e5dbd508
C
1499 return queryBuilder.queryVideoIds(queryOptions)
1500 .then(rows => rows.map(r => r[field]))
2d3741d6
C
1501 }
1502
b36f41ca
C
1503 static buildTrendingQuery (trendingDays: number) {
1504 return {
1505 attributes: [],
1506 subQuery: false,
1507 model: VideoViewModel,
1508 required: false,
1509 where: {
1510 startDate: {
c0d2eac3
C
1511 // FIXME: ts error
1512 [Op.gte as any]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
b36f41ca
C
1513 }
1514 }
1515 }
1516 }
1517
6e46de09 1518 private static async getAvailableForApi (
e5dbd508 1519 options: BuildVideosListQueryOptions,
6e46de09 1520 countVideos = true
b84d4c80 1521 ): Promise<ResultList<VideoModel>> {
6b842050
C
1522 function getCount () {
1523 if (countVideos !== true) return Promise.resolve(undefined)
8ea6f49a 1524
6b842050 1525 const countOptions = Object.assign({}, options, { isCount: true })
e5dbd508 1526 const queryBuilder = new VideosIdListQueryBuilder(VideoModel.sequelize)
3caf77d3 1527
e5dbd508 1528 return queryBuilder.countVideoIds(countOptions)
6b842050
C
1529 }
1530
1531 function getModels () {
baab47ca
C
1532 if (options.count === 0) return Promise.resolve([])
1533
e5dbd508 1534 const queryBuilder = new VideosModelListQueryBuilder(VideoModel.sequelize)
6b842050 1535
e5dbd508 1536 return queryBuilder.queryVideos(options)
6b842050
C
1537 }
1538
1539 const [ count, rows ] = await Promise.all([ getCount(), getModels() ])
afd2cba5 1540
ddc07312
C
1541 return {
1542 data: rows,
1543 total: count
1544 }
1545 }
1546
d324756e
C
1547 private static throwIfPrivateIncludeWithoutUser (include: VideoInclude, user: MUserAccountId) {
1548 if (VideoModel.isPrivateInclude(include) && !user?.hasRight(UserRight.SEE_ALL_VIDEOS)) {
527a52ac
C
1549 throw new Error('Try to filter all-local but user cannot see all videos')
1550 }
1551 }
1552
1553 private static throwIfPrivacyOneOfWithoutUser (privacyOneOf: VideoPrivacy[], user: MUserAccountId) {
1554 if (privacyOneOf && !user?.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1555 throw new Error('Try to choose video privacies but user cannot see all videos')
d324756e
C
1556 }
1557 }
1558
3c10840f
C
1559 private static isPrivateInclude (include: VideoInclude) {
1560 return include & VideoInclude.BLACKLISTED ||
1561 include & VideoInclude.BLOCKED_OWNER ||
3c10840f
C
1562 include & VideoInclude.NOT_PUBLISHED_STATE
1563 }
1564
5b77537c
C
1565 isBlacklisted () {
1566 return !!this.VideoBlacklist
1567 }
1568
bfbd9128 1569 isBlocked () {
faa9d434 1570 return this.VideoChannel.Account.Actor.Server?.isBlocked() || this.VideoChannel.Account.isBlocked()
bfbd9128
C
1571 }
1572
a1587156 1573 getQualityFileBy<T extends MVideoWithFile> (this: T, fun: (files: MVideoFile[], it: (file: MVideoFile) => number) => MVideoFile) {
24516aa2 1574 // We first transcode to WebTorrent format, so try this array first
d7a25329 1575 if (Array.isArray(this.VideoFiles) && this.VideoFiles.length !== 0) {
92e0f42e 1576 const file = fun(this.VideoFiles, file => file.resolution)
d7a25329
C
1577
1578 return Object.assign(file, { Video: this })
1579 }
1580
1581 // No webtorrent files, try with streaming playlist files
1582 if (Array.isArray(this.VideoStreamingPlaylists) && this.VideoStreamingPlaylists.length !== 0) {
1583 const streamingPlaylistWithVideo = Object.assign(this.VideoStreamingPlaylists[0], { Video: this })
1584
92e0f42e 1585 const file = fun(streamingPlaylistWithVideo.VideoFiles, file => file.resolution)
d7a25329
C
1586 return Object.assign(file, { VideoStreamingPlaylist: streamingPlaylistWithVideo })
1587 }
aaf61f38 1588
d7a25329 1589 return undefined
e4f97bab 1590 }
aaf61f38 1591
a1587156 1592 getMaxQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
92e0f42e
C
1593 return this.getQualityFileBy(maxBy)
1594 }
1595
a1587156 1596 getMinQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
92e0f42e
C
1597 return this.getQualityFileBy(minBy)
1598 }
1599
a1587156 1600 getWebTorrentFile<T extends MVideoWithFile> (this: T, resolution: number): MVideoFileVideo {
29d4e137
C
1601 if (Array.isArray(this.VideoFiles) === false) return undefined
1602
d7a25329
C
1603 const file = this.VideoFiles.find(f => f.resolution === resolution)
1604 if (!file) return undefined
1605
1606 return Object.assign(file, { Video: this })
29d4e137
C
1607 }
1608
6939cbac
C
1609 hasWebTorrentFiles () {
1610 return Array.isArray(this.VideoFiles) === true && this.VideoFiles.length !== 0
1611 }
1612
28dfb44b 1613 async addAndSaveThumbnail (thumbnail: MThumbnail, transaction?: Transaction) {
3acc5084
C
1614 thumbnail.videoId = this.id
1615
1616 const savedThumbnail = await thumbnail.save({ transaction })
1617
e8bafea3
C
1618 if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = []
1619
17ddba49 1620 this.Thumbnails = this.Thumbnails.filter(t => t.id !== savedThumbnail.id)
3acc5084 1621 this.Thumbnails.push(savedThumbnail)
e8bafea3
C
1622 }
1623
3acc5084 1624 getMiniature () {
e8bafea3
C
1625 if (Array.isArray(this.Thumbnails) === false) return undefined
1626
3acc5084 1627 return this.Thumbnails.find(t => t.type === ThumbnailType.MINIATURE)
e8bafea3
C
1628 }
1629
6872996d
C
1630 hasPreview () {
1631 return !!this.getPreview()
1632 }
1633
e8bafea3
C
1634 getPreview () {
1635 if (Array.isArray(this.Thumbnails) === false) return undefined
1636
1637 return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW)
3fd3ab2d 1638 }
7b1f49de 1639
3fd3ab2d
C
1640 isOwned () {
1641 return this.remote === false
9567011b
C
1642 }
1643
cef534ed 1644 getWatchStaticPath () {
29837f88 1645 return buildVideoWatchPath({ shortUUID: uuidToShort(this.uuid) })
cef534ed
C
1646 }
1647
40e87e9e 1648 getEmbedStaticPath () {
15a7eafb 1649 return buildVideoEmbedPath(this)
3fd3ab2d 1650 }
e4f97bab 1651
3acc5084
C
1652 getMiniatureStaticPath () {
1653 const thumbnail = this.getMiniature()
e8bafea3
C
1654 if (!thumbnail) return null
1655
1656 return join(STATIC_PATHS.THUMBNAILS, thumbnail.filename)
e4f97bab 1657 }
227d02fe 1658
40e87e9e 1659 getPreviewStaticPath () {
e8bafea3
C
1660 const preview = this.getPreview()
1661 if (!preview) return null
1662
1663 // We use a local cache, so specify our cache endpoint instead of potential remote URL
557b13ae 1664 return join(LAZY_STATIC_PATHS.PREVIEWS, preview.filename)
3fd3ab2d 1665 }
40298b02 1666
b5fecbf4 1667 toFormattedJSON (this: MVideoFormattable, options?: VideoFormattingJSONOptions): Video {
098eb377 1668 return videoModelToFormattedJSON(this, options)
14d3270f 1669 }
14d3270f 1670
b5fecbf4 1671 toFormattedDetailsJSON (this: MVideoFormattableDetails): VideoDetails {
098eb377 1672 return videoModelToFormattedDetailsJSON(this)
244e76a5
RK
1673 }
1674
f66db4d5 1675 getFormattedVideoFilesJSON (includeMagnet = true): VideoFile[] {
7a499487 1676 let files: VideoFile[] = []
97816649 1677
97816649 1678 if (Array.isArray(this.VideoFiles)) {
f66db4d5 1679 const result = videoFilesModelToFormattedJSON(this, this.VideoFiles, includeMagnet)
7a499487 1680 files = files.concat(result)
97816649
C
1681 }
1682
1683 for (const p of (this.VideoStreamingPlaylists || [])) {
f66db4d5 1684 const result = videoFilesModelToFormattedJSON(this, p.VideoFiles, includeMagnet)
7a499487 1685 files = files.concat(result)
97816649
C
1686 }
1687
7a499487 1688 return files
3fd3ab2d 1689 }
e4f97bab 1690
de6310b2 1691 toActivityPubObject (this: MVideoAP): VideoObject {
098eb377 1692 return videoModelToActivityPubObject(this)
3fd3ab2d
C
1693 }
1694
1695 getTruncatedDescription () {
1696 if (!this.description) return null
93e1258c 1697
bffbebbe 1698 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
687c6180 1699 return peertubeTruncate(this.description, { length: maxLength })
93e1258c
C
1700 }
1701
f012319a
C
1702 getAllFiles () {
1703 let files: MVideoFile[] = []
1704
1705 if (Array.isArray(this.VideoFiles)) {
1706 files = files.concat(this.VideoFiles)
1707 }
1708
1709 if (Array.isArray(this.VideoStreamingPlaylists)) {
1710 for (const p of this.VideoStreamingPlaylists) {
1711 if (Array.isArray(p.VideoFiles)) {
1712 files = files.concat(p.VideoFiles)
1713 }
1714 }
1715 }
1716
1717 return files
1718 }
1719
c729caf6 1720 probeMaxQualityFile () {
d7a25329
C
1721 const file = this.getMaxQualityFile()
1722 const videoOrPlaylist = file.getVideoOrStreamingPlaylist()
0d0e8dd0 1723
cbe2f36d
C
1724 return VideoPathManager.Instance.makeAvailableVideoFile(file.withVideoOrPlaylist(videoOrPlaylist), async originalFilePath => {
1725 const probe = await ffprobePromise(originalFilePath)
1726
1727 const { audioStream } = await getAudioStream(originalFilePath, probe)
1728
1729 return {
1730 audioStream,
1731
c729caf6 1732 ...await getVideoStreamDimensionsInfo(originalFilePath, probe)
cbe2f36d 1733 }
0305db28 1734 })
3fd3ab2d 1735 }
0d0e8dd0 1736
96f29c0f 1737 getDescriptionAPIPath () {
3fd3ab2d 1738 return `/api/${API_VERSION}/videos/${this.uuid}/description`
feb4bdfd
C
1739 }
1740
d7a25329 1741 getHLSPlaylist (): MStreamingPlaylistFilesVideo {
e2600d8b
C
1742 if (!this.VideoStreamingPlaylists) return undefined
1743
d7a25329 1744 const playlist = this.VideoStreamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
e1ab52d7 1745 if (!playlist) return undefined
1746
d7a25329
C
1747 playlist.Video = this
1748
1749 return playlist
e2600d8b
C
1750 }
1751
d7a25329
C
1752 setHLSPlaylist (playlist: MStreamingPlaylist) {
1753 const toAdd = [ playlist ] as [ VideoStreamingPlaylistModel ]
b9fffa29 1754
d7a25329
C
1755 if (Array.isArray(this.VideoStreamingPlaylists) === false || this.VideoStreamingPlaylists.length === 0) {
1756 this.VideoStreamingPlaylists = toAdd
1757 return
1758 }
1759
1760 this.VideoStreamingPlaylists = this.VideoStreamingPlaylists
a1587156
C
1761 .filter(s => s.type !== VideoStreamingPlaylistType.HLS)
1762 .concat(toAdd)
d7a25329
C
1763 }
1764
b46cf4b9 1765 removeWebTorrentFileAndTorrent (videoFile: MVideoFile, isRedundancy = false) {
0305db28
JB
1766 const filePath = isRedundancy
1767 ? VideoPathManager.Instance.getFSRedundancyVideoFilePath(this, videoFile)
1768 : VideoPathManager.Instance.getFSVideoFileOutputPath(this, videoFile)
764b1a14
C
1769
1770 const promises: Promise<any>[] = [ remove(filePath) ]
1771 if (!isRedundancy) promises.push(videoFile.removeTorrent())
1772
0305db28
JB
1773 if (videoFile.storage === VideoStorage.OBJECT_STORAGE) {
1774 promises.push(removeWebTorrentObjectStorage(videoFile))
1775 }
1776
764b1a14 1777 return Promise.all(promises)
feb4bdfd
C
1778 }
1779
ffc65cbd 1780 async removeStreamingPlaylistFiles (streamingPlaylist: MStreamingPlaylist, isRedundancy = false) {
0305db28
JB
1781 const directoryPath = isRedundancy
1782 ? getHLSRedundancyDirectory(this)
1783 : getHLSDirectory(this)
09209296 1784
ffc65cbd
C
1785 await remove(directoryPath)
1786
1787 if (isRedundancy !== true) {
a1587156 1788 const streamingPlaylistWithFiles = streamingPlaylist as MStreamingPlaylistFilesVideo
ffc65cbd
C
1789 streamingPlaylistWithFiles.Video = this
1790
1791 if (!Array.isArray(streamingPlaylistWithFiles.VideoFiles)) {
1792 streamingPlaylistWithFiles.VideoFiles = await streamingPlaylistWithFiles.$get('VideoFiles')
1793 }
1794
1795 // Remove physical files and torrents
1796 await Promise.all(
90a8bd30 1797 streamingPlaylistWithFiles.VideoFiles.map(file => file.removeTorrent())
ffc65cbd 1798 )
0305db28
JB
1799
1800 if (streamingPlaylist.storage === VideoStorage.OBJECT_STORAGE) {
ad5db104 1801 await removeHLSObjectStorage(streamingPlaylist.withVideo(this))
0305db28 1802 }
ffc65cbd 1803 }
09209296
C
1804 }
1805
1297eb5d
C
1806 isOutdated () {
1807 if (this.isOwned()) return false
1808
9f79ade6 1809 return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)
1297eb5d
C
1810 }
1811
22a73cb8 1812 hasPrivacyForFederation () {
3092e9bb 1813 return isPrivacyForFederation(this.privacy)
22a73cb8
C
1814 }
1815
68e70a74
C
1816 hasStateForFederation () {
1817 return isStateForFederation(this.state)
1818 }
1819
22a73cb8 1820 isNewVideo (newPrivacy: VideoPrivacy) {
3092e9bb 1821 return this.hasPrivacyForFederation() === false && isPrivacyForFederation(newPrivacy) === true
22a73cb8
C
1822 }
1823
597f771f
C
1824 setAsRefreshed (transaction?: Transaction) {
1825 return setAsUpdated('video', this.id, transaction)
04b8c3fb
C
1826 }
1827
22a73cb8
C
1828 requiresAuth () {
1829 return this.privacy === VideoPrivacy.PRIVATE || this.privacy === VideoPrivacy.INTERNAL || !!this.VideoBlacklist
1830 }
1831
1832 setPrivacy (newPrivacy: VideoPrivacy) {
1833 if (this.privacy === VideoPrivacy.PRIVATE && newPrivacy !== VideoPrivacy.PRIVATE) {
1834 this.publishedAt = new Date()
1835 }
1836
1837 this.privacy = newPrivacy
1838 }
1839
1840 isConfidential () {
1841 return this.privacy === VideoPrivacy.PRIVATE ||
1842 this.privacy === VideoPrivacy.UNLISTED ||
1843 this.privacy === VideoPrivacy.INTERNAL
1844 }
1845
9db2330e 1846 async setNewState (newState: VideoState, isNewVideo: boolean, transaction: Transaction) {
0305db28
JB
1847 if (this.state === newState) throw new Error('Cannot use same state ' + newState)
1848
1849 this.state = newState
7920c273 1850
9db2330e 1851 if (this.state === VideoState.PUBLISHED && isNewVideo) {
0305db28 1852 this.publishedAt = new Date()
6fcd19ba 1853 }
aaf61f38 1854
0305db28 1855 await this.save({ transaction })
15d4ee04 1856 }
a96aed15 1857
e1ab52d7 1858 getBandwidthBits (this: MVideo, videoFile: MVideoFile) {
d9a2a031 1859 return Math.ceil((videoFile.size * 8) / this.duration)
c48e82b5
C
1860 }
1861
d9a2a031
C
1862 getTrackerUrls () {
1863 if (this.isOwned()) {
1864 return [
1865 WEBSERVER.URL + '/tracker/announce',
1866 WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT + '/tracker/socket'
1867 ]
1868 }
09209296 1869
d9a2a031 1870 return this.Trackers.map(t => t.url)
09209296 1871 }
a96aed15 1872}