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