]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/models/video/video.ts
Translated using Weblate (Vietnamese)
[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'
0c9668f7 32import { Hooks } from '@server/lib/plugins/hooks'
0305db28 33import { VideoPathManager } from '@server/lib/video-path-manager'
9ab330b9 34import { isVideoInPrivateDirectory } from '@server/lib/video-privacy'
d95d1559 35import { getServerActor } from '@server/models/application/application'
8c4bbd94 36import { ModelCache } from '@server/models/shared/model-cache'
0628157f 37import { buildVideoEmbedPath, buildVideoWatchPath, pick } from '@shared/core-utils'
0c9668f7
C
38import { uuidToShort } from '@shared/extra-utils'
39import { ffprobePromise, getAudioStream, getVideoStreamDimensionsInfo, getVideoStreamFPS, hasAudioStream } from '@shared/ffmpeg'
d17c7b4e
C
40import {
41 ResultList,
42 ThumbnailType,
43 UserRight,
44 Video,
45 VideoDetails,
46 VideoFile,
47 VideoInclude,
48 VideoObject,
49 VideoPrivacy,
50 VideoRateType,
51 VideoState,
52 VideoStorage,
53 VideoStreamingPlaylistType
54} from '@shared/models'
6b5f72be 55import { AttributesOnly } from '@shared/typescript-utils'
30ff39e7 56import { peertubeTruncate } from '../../helpers/core-utils'
da854ddd 57import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
3545e72c 58import { exists, isBooleanValid, isUUIDValid } from '../../helpers/custom-validators/misc'
3fd3ab2d 59import {
4ba3b8ea
C
60 isVideoDescriptionValid,
61 isVideoDurationValid,
418d092a 62 isVideoNameValid,
2baea0c7
C
63 isVideoPrivacyValid,
64 isVideoStateValid,
b64c950a 65 isVideoSupportValid
3fd3ab2d 66} from '../../helpers/custom-validators/videos'
da854ddd 67import { logger } from '../../helpers/logger'
d95d1559 68import { CONFIG } from '../../initializers/config'
69322042 69import { ACTIVITY_PUB, API_VERSION, CONSTRAINTS_FIELDS, LAZY_STATIC_PATHS, STATIC_PATHS, WEBSERVER } from '../../initializers/constants'
50d6de9c 70import { sendDeleteVideo } from '../../lib/activitypub/send'
453e83ea
C
71import {
72 MChannel,
0283eaac 73 MChannelAccountDefault,
453e83ea 74 MChannelId,
d7a25329
C
75 MStreamingPlaylist,
76 MStreamingPlaylistFilesVideo,
453e83ea
C
77 MUserAccountId,
78 MUserId,
90a8bd30 79 MVideo,
453e83ea 80 MVideoAccountLight,
0283eaac 81 MVideoAccountLightBlacklistAllFiles,
b5fecbf4 82 MVideoAP,
453e83ea 83 MVideoDetails,
d7a25329 84 MVideoFileVideo,
b5fecbf4
C
85 MVideoFormattable,
86 MVideoFormattableDetails,
0283eaac 87 MVideoForUser,
453e83ea 88 MVideoFullLight,
71d4af1e 89 MVideoId,
5f3e2425 90 MVideoImmutable,
453e83ea 91 MVideoThumbnail,
d636ab58 92 MVideoThumbnailBlacklist,
b5fecbf4 93 MVideoWithAllFiles,
71d4af1e 94 MVideoWithFile
26d6bf65 95} from '../../types/models'
26d6bf65 96import { MThumbnail } from '../../types/models/video/thumbnail'
1896bca0 97import { MVideoFile, MVideoFileStreamingPlaylistVideo } from '../../types/models/video/video-file'
d95d1559
C
98import { VideoAbuseModel } from '../abuse/video-abuse'
99import { AccountModel } from '../account/account'
100import { AccountVideoRateModel } from '../account/account-video-rate'
7d9ba5c0
C
101import { ActorModel } from '../actor/actor'
102import { ActorImageModel } from '../actor/actor-image'
d95d1559
C
103import { VideoRedundancyModel } from '../redundancy/video-redundancy'
104import { ServerModel } from '../server/server'
d9a2a031
C
105import { TrackerModel } from '../server/tracker'
106import { VideoTrackerModel } from '../server/video-tracker'
8c4bbd94 107import { buildTrigramSearchIndex, buildWhereIdOrUUID, getVideoSort, isOutdated, setAsUpdated, throwIfNotValid } from '../shared'
7d9ba5c0
C
108import { UserModel } from '../user/user'
109import { UserVideoHistoryModel } from '../user/user-video-history'
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 },
05a60d85 709 hooks: true,
31c82cd9
C
710 onDelete: 'cascade'
711 })
712 VideoLive: VideoLiveModel
713
dc133480
C
714 @HasOne(() => VideoImportModel, {
715 foreignKey: {
716 name: 'videoId',
717 allowNull: true
718 },
719 onDelete: 'set null'
720 })
721 VideoImport: VideoImportModel
722
40e87e9e
C
723 @HasMany(() => VideoCaptionModel, {
724 foreignKey: {
725 name: 'videoId',
726 allowNull: false
727 },
728 onDelete: 'cascade',
729 hooks: true,
a1587156 730 ['separate' as any]: true
40e87e9e
C
731 })
732 VideoCaptions: VideoCaptionModel[]
733
0305db28
JB
734 @HasOne(() => VideoJobInfoModel, {
735 foreignKey: {
736 name: 'videoId',
737 allowNull: false
738 },
739 onDelete: 'cascade'
740 })
741 VideoJobInfo: VideoJobInfoModel
742
f05a1c30 743 @BeforeDestroy
453e83ea 744 static async sendDelete (instance: MVideoAccountLight, options) {
42ec411b 745 if (!instance.isOwned()) return undefined
f05a1c30 746
42ec411b
C
747 // Lazy load channels
748 if (!instance.VideoChannel) {
749 instance.VideoChannel = await instance.$get('VideoChannel', {
750 include: [
751 ActorModel,
752 AccountModel
753 ],
754 transaction: options.transaction
755 }) as MChannelAccountDefault
f05a1c30
C
756 }
757
42ec411b 758 return sendDeleteVideo(instance, options.transaction)
f05a1c30
C
759 }
760
6b738c7a 761 @BeforeDestroy
9f7657b6 762 static async removeFiles (instance: VideoModel, options) {
f05a1c30 763 const tasks: Promise<any>[] = []
f285faa0 764
8e0fd45e 765 logger.info('Removing files of video %s.', instance.url)
6b738c7a 766
3fd3ab2d 767 if (instance.isOwned()) {
f05a1c30 768 if (!Array.isArray(instance.VideoFiles)) {
9f7657b6 769 instance.VideoFiles = await instance.$get('VideoFiles', { transaction: options.transaction })
f05a1c30
C
770 }
771
3fd3ab2d
C
772 // Remove physical files and torrents
773 instance.VideoFiles.forEach(file => {
1bb4c9ab 774 tasks.push(instance.removeWebTorrentFile(file))
3fd3ab2d 775 })
09209296
C
776
777 // Remove playlists file
ffc65cbd 778 if (!Array.isArray(instance.VideoStreamingPlaylists)) {
9f7657b6 779 instance.VideoStreamingPlaylists = await instance.$get('VideoStreamingPlaylists', { transaction: options.transaction })
ffc65cbd
C
780 }
781
782 for (const p of instance.VideoStreamingPlaylists) {
783 tasks.push(instance.removeStreamingPlaylistFiles(p))
784 }
3fd3ab2d 785 }
40298b02 786
6b738c7a
C
787 // Do not wait video deletion because we could be in a transaction
788 Promise.all(tasks)
508c1b1e
C
789 .then(() => logger.info('Removed files of video %s.', instance.url))
790 .catch(err => logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err }))
6b738c7a
C
791
792 return undefined
3fd3ab2d 793 }
f285faa0 794
a5cf76af
C
795 @BeforeDestroy
796 static stopLiveIfNeeded (instance: VideoModel) {
797 if (!instance.isLive) return
798
68e70a74
C
799 logger.info('Stopping live of video %s after video deletion.', instance.uuid)
800
0c9668f7 801 LiveManager.Instance.stopSessionOf(instance.uuid, null)
a5cf76af
C
802 }
803
7eba5e1f
C
804 @BeforeDestroy
805 static invalidateCache (instance: VideoModel) {
806 ModelCache.Instance.invalidateCache('video', instance.id)
807 }
808
68d19a0a
RK
809 @BeforeDestroy
810 static async saveEssentialDataToAbuses (instance: VideoModel, options) {
811 const tasks: Promise<any>[] = []
812
68d19a0a 813 if (!Array.isArray(instance.VideoAbuses)) {
9f7657b6 814 instance.VideoAbuses = await instance.$get('VideoAbuses', { transaction: options.transaction })
68d19a0a
RK
815
816 if (instance.VideoAbuses.length === 0) return undefined
817 }
818
57f6896f
C
819 logger.info('Saving video abuses details of video %s.', instance.url)
820
42ec411b 821 if (!instance.Trackers) instance.Trackers = await instance.$get('Trackers', { transaction: options.transaction })
86521a67 822 const details = instance.toFormattedDetailsJSON()
68d19a0a
RK
823
824 for (const abuse of instance.VideoAbuses) {
0251197e
RK
825 abuse.deletedVideo = details
826 tasks.push(abuse.save({ transaction: options.transaction }))
68d19a0a
RK
827 }
828
9f7657b6 829 await Promise.all(tasks)
68d19a0a
RK
830 }
831
e1ab52d7 832 static listLocalIds (): Promise<number[]> {
9f1ddd24 833 const query = {
e1ab52d7 834 attributes: [ 'id' ],
835 raw: true,
9f1ddd24
C
836 where: {
837 remote: false
838 }
839 }
840
90a8bd30 841 return VideoModel.findAll(query)
e1ab52d7 842 .then(rows => rows.map(r => r.id))
9f1ddd24
C
843 }
844
50d6de9c 845 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
3fd3ab2d
C
846 function getRawQuery (select: string) {
847 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
848 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
50d6de9c
C
849 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
850 'WHERE "Account"."actorId" = ' + actorId
3fd3ab2d
C
851 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
852 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
50d6de9c 853 'WHERE "VideoShare"."actorId" = ' + actorId
558d7c23 854
3fd3ab2d
C
855 return `(${queryVideo}) UNION (${queryVideoShare})`
856 }
aaf61f38 857
3fd3ab2d
C
858 const rawQuery = getRawQuery('"Video"."id"')
859 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
860
861 const query = {
862 distinct: true,
863 offset: start,
864 limit: count,
0c691a18 865 order: getVideoSort('-createdAt', [ 'Tags', 'name', 'ASC' ]),
3fd3ab2d
C
866 where: {
867 id: {
a1587156 868 [Op.in]: Sequelize.literal('(' + rawQuery + ')')
3c75ce12 869 },
3092e9bb 870 [Op.or]: getPrivaciesForFederation()
3fd3ab2d
C
871 },
872 include: [
40e87e9e 873 {
1afb3c47 874 attributes: [ 'filename', 'language', 'fileUrl' ],
40e87e9e
C
875 model: VideoCaptionModel.unscoped(),
876 required: false
877 },
3fd3ab2d 878 {
1d230c44 879 attributes: [ 'id', 'url' ],
2c897999 880 model: VideoShareModel.unscoped(),
3fd3ab2d 881 required: false,
e3d5ea4f
C
882 // We only want videos shared by this actor
883 where: {
a1587156 884 [Op.and]: [
e3d5ea4f
C
885 {
886 id: {
a1587156 887 [Op.not]: null
e3d5ea4f
C
888 }
889 },
890 {
891 actorId
892 }
893 ]
894 },
50d6de9c
C
895 include: [
896 {
2c897999
C
897 attributes: [ 'id', 'url' ],
898 model: ActorModel.unscoped()
50d6de9c
C
899 }
900 ]
3fd3ab2d
C
901 },
902 {
2c897999 903 model: VideoChannelModel.unscoped(),
3fd3ab2d
C
904 required: true,
905 include: [
906 {
2c897999
C
907 attributes: [ 'name' ],
908 model: AccountModel.unscoped(),
909 required: true,
910 include: [
911 {
e3d5ea4f 912 attributes: [ 'id', 'url', 'followersUrl' ],
2c897999
C
913 model: ActorModel.unscoped(),
914 required: true
915 }
916 ]
917 },
918 {
e3d5ea4f 919 attributes: [ 'id', 'url', 'followersUrl' ],
2c897999 920 model: ActorModel.unscoped(),
3fd3ab2d
C
921 required: true
922 }
923 ]
924 },
af4ae64f
C
925 {
926 model: VideoStreamingPlaylistModel.unscoped(),
927 required: false,
928 include: [
929 {
930 model: VideoFileModel,
931 required: false
932 }
933 ]
934 },
c8f3cfeb 935 VideoLiveModel.unscoped(),
3fd3ab2d 936 VideoFileModel,
2c897999 937 TagModel
3fd3ab2d
C
938 ]
939 }
164174a6 940
3fd3ab2d 941 return Bluebird.all([
3acc5084
C
942 VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findAll(query),
943 VideoModel.sequelize.query<{ total: string }>(rawCountQuery, { type: QueryTypes.SELECT })
3fd3ab2d
C
944 ]).then(([ rows, totals ]) => {
945 // totals: totalVideos + totalVideoShares
946 let totalVideos = 0
947 let totalVideoShares = 0
a1587156
C
948 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
949 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
3fd3ab2d
C
950
951 const total = totalVideos + totalVideoShares
952 return {
953 data: rows,
ba2684ce 954 total
3fd3ab2d
C
955 }
956 })
957 }
93e1258c 958
9e2e51dc 959 static async listPublishedLiveUUIDs () {
5c0904fc 960 const options = {
9e2e51dc 961 attributes: [ 'uuid' ],
5c0904fc
C
962 where: {
963 isLive: true,
f49b3231 964 remote: false,
5c0904fc
C
965 state: VideoState.PUBLISHED
966 }
967 }
968
b49f22d8
C
969 const result = await VideoModel.findAll(options)
970
9e2e51dc 971 return result.map(v => v.uuid)
5c0904fc
C
972 }
973
a4d2ca07
C
974 static listUserVideosForApi (options: {
975 accountId: number
976 start: number
977 count: number
978 sort: string
978c87e7
C
979
980 channelId?: number
1fd61899 981 isLive?: boolean
bf64ed41 982 search?: string
a4d2ca07 983 }) {
978c87e7 984 const { accountId, channelId, start, count, sort, search, isLive } = options
a4d2ca07 985
a6585874 986 function buildBaseQuery (forCount: boolean): FindOptions {
1fd61899
C
987 const where: WhereOptions = {}
988
989 if (search) {
990 where.name = {
991 [Op.iLike]: '%' + search + '%'
992 }
993 }
994
c4c0c311 995 if (exists(isLive)) {
1fd61899
C
996 where.isLive = isLive
997 }
998
978c87e7
C
999 const channelWhere = channelId
1000 ? { id: channelId }
1001 : {}
1002
1fd61899 1003 const baseQuery = {
3acc5084
C
1004 offset: start,
1005 limit: count,
1fd61899 1006 where,
3acc5084
C
1007 order: getVideoSort(sort),
1008 include: [
1009 {
58c44687
C
1010 model: forCount
1011 ? VideoChannelModel.unscoped()
1012 : VideoChannelModel,
3acc5084 1013 required: true,
978c87e7 1014 where: channelWhere,
3acc5084
C
1015 include: [
1016 {
a6585874
C
1017 model: forCount
1018 ? AccountModel.unscoped()
1019 : AccountModel,
3acc5084
C
1020 where: {
1021 id: accountId
1022 },
1023 required: true
1024 }
1025 ]
1026 }
1027 ]
1028 }
bf64ed41 1029
bf64ed41 1030 return baseQuery
3fd3ab2d 1031 }
d8755eed 1032
a6585874
C
1033 const countQuery = buildBaseQuery(true)
1034 const findQuery = buildBaseQuery(false)
3acc5084 1035
bf64ed41 1036 const findScopes: (string | ScopeOptions)[] = [
a18f275d
C
1037 ScopeNames.WITH_SCHEDULED_UPDATE,
1038 ScopeNames.WITH_BLACKLISTED,
1039 ScopeNames.WITH_THUMBNAILS
1040 ]
3acc5084 1041
3acc5084
C
1042 return Promise.all([
1043 VideoModel.count(countQuery),
0283eaac 1044 VideoModel.scope(findScopes).findAll<MVideoForUser>(findQuery)
3acc5084
C
1045 ]).then(([ count, rows ]) => {
1046 return {
0283eaac 1047 data: rows,
3acc5084
C
1048 total: count
1049 }
1050 })
3fd3ab2d 1051 }
93e1258c 1052
48dce1c9 1053 static async listForApi (options: {
a1587156
C
1054 start: number
1055 count: number
1056 sort: string
1fd61899 1057
a1587156 1058 nsfw: boolean
1fd61899 1059 isLive?: boolean
2760b454
C
1060 isLocal?: boolean
1061 include?: VideoInclude
1fd61899 1062
3c10840f 1063 hasFiles?: boolean // default false
d324756e
C
1064 hasWebtorrentFiles?: boolean
1065 hasHLSFiles?: boolean
1fd61899 1066
a1587156
C
1067 categoryOneOf?: number[]
1068 licenceOneOf?: number[]
1069 languageOneOf?: string[]
1070 tagsOneOf?: string[]
1071 tagsAllOf?: string[]
527a52ac 1072 privacyOneOf?: VideoPrivacy[]
1fd61899 1073
a1587156
C
1074 accountId?: number
1075 videoChannelId?: number
1fd61899 1076
2760b454 1077 displayOnlyForFollower: DisplayOnlyForFollowerOptions | null
1fd61899 1078
a1587156 1079 videoPlaylistId?: number
1fd61899 1080
a1587156 1081 trendingDays?: number
1fd61899 1082
a1587156
C
1083 user?: MUserAccountId
1084 historyOfUser?: MUserId
1fd61899 1085
fe987656 1086 countVideos?: boolean
1fd61899 1087
d8b34ee5 1088 search?: string
2a4c0d8b
W
1089
1090 excludeAlreadyWatched?: boolean
fe987656 1091 }) {
d324756e 1092 VideoModel.throwIfPrivateIncludeWithoutUser(options.include, options.user)
527a52ac 1093 VideoModel.throwIfPrivacyOneOfWithoutUser(options.privacyOneOf, options.user)
1cd3facc 1094
5f3e2425
C
1095 const trendingDays = options.sort.endsWith('trending')
1096 ? CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1097 : undefined
d6886027
C
1098
1099 let trendingAlgorithm: string
3d4e112d
RK
1100 if (options.sort.endsWith('hot')) trendingAlgorithm = 'hot'
1101 if (options.sort.endsWith('best')) trendingAlgorithm = 'best'
93e1258c 1102
7ad9b984
C
1103 const serverActor = await getServerActor()
1104
afd2cba5 1105 const queryOptions = {
9c9a236b
C
1106 ...pick(options, [
1107 'start',
1108 'count',
1109 'sort',
1110 'nsfw',
1111 'isLive',
1112 'categoryOneOf',
1113 'licenceOneOf',
1114 'languageOneOf',
1115 'tagsOneOf',
1116 'tagsAllOf',
527a52ac 1117 'privacyOneOf',
2760b454
C
1118 'isLocal',
1119 'include',
1120 'displayOnlyForFollower',
3c10840f 1121 'hasFiles',
9c9a236b
C
1122 'accountId',
1123 'videoChannelId',
1124 'videoPlaylistId',
9c9a236b
C
1125 'user',
1126 'historyOfUser',
d324756e
C
1127 'hasHLSFiles',
1128 'hasWebtorrentFiles',
2a4c0d8b
W
1129 'search',
1130 'excludeAlreadyWatched'
9c9a236b
C
1131 ]),
1132
2760b454 1133 serverAccountIdForBlock: serverActor.Account.id,
d8b34ee5 1134 trendingDays,
9c9a236b 1135 trendingAlgorithm
48dce1c9
C
1136 }
1137
5f3e2425 1138 return VideoModel.getAvailableForApi(queryOptions, options.countVideos)
93e1258c
C
1139 }
1140
0b18f4aa 1141 static async searchAndPopulateAccountAndServer (options: {
9c9a236b
C
1142 start: number
1143 count: number
1144 sort: string
d324756e 1145
0b18f4aa 1146 nsfw?: boolean
1fd61899 1147 isLive?: boolean
2760b454
C
1148 isLocal?: boolean
1149 include?: VideoInclude
d324756e 1150
0b18f4aa
C
1151 categoryOneOf?: number[]
1152 licenceOneOf?: number[]
1153 languageOneOf?: string[]
1154 tagsOneOf?: string[]
1155 tagsAllOf?: string[]
527a52ac 1156 privacyOneOf?: VideoPrivacy[]
d324756e
C
1157
1158 displayOnlyForFollower: DisplayOnlyForFollowerOptions | null
1159
1160 user?: MUserAccountId
1161
1162 hasWebtorrentFiles?: boolean
1163 hasHLSFiles?: boolean
1164
1165 search?: string
1166
1167 host?: string
1168 startDate?: string // ISO 8601
1169 endDate?: string // ISO 8601
1170 originallyPublishedStartDate?: string
1171 originallyPublishedEndDate?: string
1172
0b18f4aa
C
1173 durationMin?: number // seconds
1174 durationMax?: number // seconds
fbd67e7f 1175 uuids?: string[]
2a4c0d8b
W
1176
1177 excludeAlreadyWatched?: boolean
0b18f4aa 1178 }) {
d324756e 1179 VideoModel.throwIfPrivateIncludeWithoutUser(options.include, options.user)
527a52ac 1180 VideoModel.throwIfPrivacyOneOfWithoutUser(options.privacyOneOf, options.user)
d324756e 1181
f05a1c30 1182 const serverActor = await getServerActor()
1fd61899 1183
afd2cba5 1184 const queryOptions = {
9c9a236b 1185 ...pick(options, [
2760b454 1186 'include',
9c9a236b
C
1187 'nsfw',
1188 'isLive',
1189 'categoryOneOf',
1190 'licenceOneOf',
1191 'languageOneOf',
1192 'tagsOneOf',
1193 'tagsAllOf',
527a52ac 1194 'privacyOneOf',
9c9a236b 1195 'user',
2760b454 1196 'isLocal',
9c9a236b
C
1197 'host',
1198 'start',
1199 'count',
1200 'sort',
1201 'startDate',
1202 'endDate',
1203 'originallyPublishedStartDate',
1204 'originallyPublishedEndDate',
1205 'durationMin',
1206 'durationMax',
d324756e
C
1207 'hasHLSFiles',
1208 'hasWebtorrentFiles',
9c9a236b 1209 'uuids',
2760b454 1210 'search',
2a4c0d8b
W
1211 'displayOnlyForFollower',
1212 'excludeAlreadyWatched'
9c9a236b 1213 ]),
2760b454 1214 serverAccountIdForBlock: serverActor.Account.id
48dce1c9 1215 }
f05a1c30 1216
5f3e2425 1217 return VideoModel.getAvailableForApi(queryOptions)
f05a1c30
C
1218 }
1219
adc94cf0
C
1220 static countLives (options: {
1221 remote: boolean
1222 mode: 'published' | 'not-ended'
1223 }) {
1224 const query = {
a056ca48 1225 where: {
adc94cf0 1226 remote: options.remote,
875f0610 1227 isLive: true,
adc94cf0
C
1228 state: options.mode === 'not-ended'
1229 ? { [Op.ne]: VideoState.LIVE_ENDED }
1230 : { [Op.eq]: VideoState.PUBLISHED }
a056ca48
C
1231 }
1232 }
1233
adc94cf0 1234 return VideoModel.count(query)
a056ca48
C
1235 }
1236
77d7e851
C
1237 static countVideosUploadedByUserSince (userId: number, since: Date) {
1238 const options = {
1239 include: [
1240 {
1241 model: VideoChannelModel.unscoped(),
1242 required: true,
1243 include: [
1244 {
1245 model: AccountModel.unscoped(),
1246 required: true,
1247 include: [
1248 {
1249 model: UserModel.unscoped(),
1250 required: true,
1251 where: {
1252 id: userId
1253 }
1254 }
1255 ]
1256 }
1257 ]
1258 }
1259 ],
1260 where: {
1261 createdAt: {
1262 [Op.gte]: since
1263 }
1264 }
1265 }
1266
1267 return VideoModel.unscoped().count(options)
1268 }
1269
a056ca48
C
1270 static countLivesOfAccount (accountId: number) {
1271 const options = {
1272 where: {
1273 remote: false,
fb4b3f91
C
1274 isLive: true,
1275 state: {
1276 [Op.ne]: VideoState.LIVE_ENDED
1277 }
a056ca48
C
1278 },
1279 include: [
1280 {
1281 required: true,
1282 model: VideoChannelModel.unscoped(),
1283 where: {
1284 accountId
1285 }
1286 }
1287 ]
1288 }
1289
1290 return VideoModel.count(options)
1291 }
1292
71d4af1e 1293 static load (id: number | string, transaction?: Transaction): Promise<MVideoThumbnail> {
3c10840f 1294 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
d8755eed 1295
71d4af1e 1296 return queryBuilder.queryVideo({ id, transaction, type: 'thumbnails' })
3fd3ab2d 1297 }
d8755eed 1298
71d4af1e 1299 static loadWithBlacklist (id: number | string, transaction?: Transaction): Promise<MVideoThumbnailBlacklist> {
3c10840f 1300 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
d636ab58 1301
71d4af1e 1302 return queryBuilder.queryVideo({ id, transaction, type: 'thumbnails-blacklist' })
d636ab58
C
1303 }
1304
b49f22d8 1305 static loadImmutableAttributes (id: number | string, t?: Transaction): Promise<MVideoImmutable> {
7eba5e1f 1306 const fun = () => {
943e5193
C
1307 const query = {
1308 where: buildWhereIdOrUUID(id),
7eba5e1f
C
1309 transaction: t
1310 }
1311
943e5193 1312 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
7eba5e1f
C
1313 }
1314
1315 return ModelCache.Instance.doCache({
943e5193 1316 cacheType: 'load-video-immutable-id',
7eba5e1f
C
1317 key: '' + id,
1318 deleteKey: 'video',
1319 fun
1320 })
1321 }
1322
b49f22d8 1323 static loadByUrlImmutableAttributes (url: string, transaction?: Transaction): Promise<MVideoImmutable> {
943e5193
C
1324 const fun = () => {
1325 const query: FindOptions = {
1326 where: {
1327 url
1328 },
1329 transaction
1330 }
1331
1332 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1333 }
1334
1335 return ModelCache.Instance.doCache({
1336 cacheType: 'load-video-immutable-url',
1337 key: url,
1338 deleteKey: 'video',
1339 fun
1340 })
1341 }
1342
71d4af1e 1343 static loadOnlyId (id: number | string, transaction?: Transaction): Promise<MVideoId> {
3c10840f 1344 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
627621c1 1345
71d4af1e 1346 return queryBuilder.queryVideo({ id, transaction, type: 'id' })
627621c1
C
1347 }
1348
71d4af1e 1349 static loadWithFiles (id: number | string, transaction?: Transaction, logging?: boolean): Promise<MVideoWithAllFiles> {
3c10840f 1350 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
627621c1 1351
71d4af1e
C
1352 return queryBuilder.queryVideo({ id, transaction, type: 'all-files', logging })
1353 }
fd45e8f4 1354
71d4af1e 1355 static loadByUrl (url: string, transaction?: Transaction): Promise<MVideoThumbnail> {
3c10840f 1356 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
09209296 1357
71d4af1e
C
1358 return queryBuilder.queryVideo({ url, transaction, type: 'thumbnails' })
1359 }
1360
1361 static loadByUrlAndPopulateAccount (url: string, transaction?: Transaction): Promise<MVideoAccountLightBlacklistAllFiles> {
3c10840f 1362 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
71d4af1e
C
1363
1364 return queryBuilder.queryVideo({ url, transaction, type: 'account-blacklist-files' })
1365 }
1366
4fae2b1f 1367 static loadFull (id: number | string, t?: Transaction, userId?: number): Promise<MVideoFullLight> {
3c10840f 1368 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
09209296 1369
4fae2b1f 1370 return queryBuilder.queryVideo({ id, transaction: t, type: 'full', userId })
09209296
C
1371 }
1372
89cd1275 1373 static loadForGetAPI (parameters: {
a1587156 1374 id: number | string
ca4b4b2e 1375 transaction?: Transaction
89cd1275 1376 userId?: number
b49f22d8 1377 }): Promise<MVideoDetails> {
ca4b4b2e 1378 const { id, transaction, userId } = parameters
3c10840f 1379 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
09209296 1380
71d4af1e 1381 return queryBuilder.queryVideo({ id, transaction, type: 'api', userId })
da854ddd
C
1382 }
1383
09cababd 1384 static async getStats () {
630d0a1b 1385 const serverActor = await getServerActor()
09cababd
C
1386
1387 let totalLocalVideoViews = await VideoModel.sum('views', {
1388 where: {
1389 remote: false
1390 }
1391 })
baab47ca 1392
09cababd
C
1393 // Sequelize could return null...
1394 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1395
630d0a1b 1396 const baseOptions = {
baab47ca
C
1397 start: 0,
1398 count: 0,
1399 sort: '-publishedAt',
630d0a1b 1400 nsfw: null,
2760b454
C
1401 displayOnlyForFollower: {
1402 actorId: serverActor.id,
1403 orLocalVideos: true
3c10840f 1404 }
630d0a1b
C
1405 }
1406
1407 const { total: totalLocalVideos } = await VideoModel.listForApi({
1408 ...baseOptions,
1409
1410 isLocal: true
baab47ca
C
1411 })
1412
630d0a1b
C
1413 const { total: totalVideos } = await VideoModel.listForApi(baseOptions)
1414
09cababd
C
1415 return {
1416 totalLocalVideos,
1417 totalLocalVideoViews,
1418 totalVideos
1419 }
1420 }
1421
6b616860
C
1422 static incrementViews (id: number, views: number) {
1423 return VideoModel.increment('views', {
1424 by: views,
1425 where: {
1426 id
1427 }
1428 })
1429 }
1430
57e4e1c1
C
1431 static updateRatesOf (videoId: number, type: VideoRateType, count: number, t: Transaction) {
1432 const field = type === 'like'
1433 ? 'likes'
1434 : 'dislikes'
1435
1436 const rawQuery = `UPDATE "video" SET "${field}" = :count WHERE "video"."id" = :videoId`
1437
1438 return AccountVideoRateModel.sequelize.query(rawQuery, {
1439 transaction: t,
1440 replacements: { videoId, rateType: type, count },
1441 type: QueryTypes.UPDATE
1442 })
1443 }
1444
1445 static syncLocalRates (videoId: number, type: VideoRateType, t: Transaction) {
74d249bc
C
1446 const field = type === 'like'
1447 ? 'likes'
1448 : 'dislikes'
1449
1450 const rawQuery = `UPDATE "video" SET "${field}" = ` +
1451 '(' +
69322042 1452 'SELECT COUNT(id) FROM "accountVideoRate" WHERE "accountVideoRate"."videoId" = "video"."id" AND type = :rateType' +
74d249bc
C
1453 ') ' +
1454 'WHERE "video"."id" = :videoId'
1455
1456 return AccountVideoRateModel.sequelize.query(rawQuery, {
1457 transaction: t,
1458 replacements: { videoId, rateType: type },
1459 type: QueryTypes.UPDATE
1460 })
1461 }
1462
8d427346
C
1463 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1464 // Instances only share videos
1465 const query = 'SELECT 1 FROM "videoShare" ' +
a1587156 1466 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
f046e2fa 1467 'WHERE "actorFollow"."actorId" = $followerActorId AND "actorFollow"."state" = \'accepted\' AND "videoShare"."videoId" = $videoId ' +
11ae7e29
C
1468 'UNION ' +
1469 'SELECT 1 FROM "video" ' +
1470 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
1471 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
1472 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "account"."actorId" ' +
1473 'WHERE "actorFollow"."actorId" = $followerActorId AND "actorFollow"."state" = \'accepted\' AND "video"."id" = $videoId ' +
a1587156 1474 'LIMIT 1'
8d427346
C
1475
1476 const options = {
d5d9b6d7 1477 type: QueryTypes.SELECT as QueryTypes.SELECT,
8d427346
C
1478 bind: { followerActorId, videoId },
1479 raw: true
1480 }
1481
1482 return VideoModel.sequelize.query(query, options)
1483 .then(results => results.length === 1)
1484 }
1485
69322042 1486 static bulkUpdateSupportField (ofChannel: MChannel, t: Transaction) {
7d14d4d2
C
1487 const options = {
1488 where: {
69322042 1489 channelId: ofChannel.id
7d14d4d2
C
1490 },
1491 transaction: t
1492 }
1493
69322042 1494 return VideoModel.update({ support: ofChannel.support }, options)
7d14d4d2
C
1495 }
1496
b49f22d8 1497 static getAllIdsFromChannel (videoChannel: MChannelId): Promise<number[]> {
7d14d4d2
C
1498 const query = {
1499 attributes: [ 'id' ],
1500 where: {
1501 channelId: videoChannel.id
1502 }
1503 }
1504
1505 return VideoModel.findAll(query)
a1587156 1506 .then(videos => videos.map(v => v.id))
7d14d4d2
C
1507 }
1508
2d3741d6 1509 // threshold corresponds to how many video the field should have to be returned
7348b1fd 1510 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
65b21c96 1511 const serverActor = await getServerActor()
7348b1fd 1512
e5dbd508 1513 const queryOptions: BuildVideosListQueryOptions = {
5f3e2425
C
1514 attributes: [ `"${field}"` ],
1515 group: `GROUP BY "${field}"`,
1516 having: `HAVING COUNT("${field}") >= ${threshold}`,
1517 start: 0,
1518 sort: 'random',
1519 count,
2760b454
C
1520 serverAccountIdForBlock: serverActor.Account.id,
1521 displayOnlyForFollower: {
1522 actorId: serverActor.id,
1523 orLocalVideos: true
1524 }
7348b1fd
C
1525 }
1526
e5dbd508 1527 const queryBuilder = new VideosIdListQueryBuilder(VideoModel.sequelize)
2d3741d6 1528
e5dbd508
C
1529 return queryBuilder.queryVideoIds(queryOptions)
1530 .then(rows => rows.map(r => r[field]))
2d3741d6
C
1531 }
1532
b36f41ca
C
1533 static buildTrendingQuery (trendingDays: number) {
1534 return {
1535 attributes: [],
1536 subQuery: false,
1537 model: VideoViewModel,
1538 required: false,
1539 where: {
1540 startDate: {
c0d2eac3
C
1541 // FIXME: ts error
1542 [Op.gte as any]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
b36f41ca
C
1543 }
1544 }
1545 }
1546 }
1547
6e46de09 1548 private static async getAvailableForApi (
e5dbd508 1549 options: BuildVideosListQueryOptions,
6e46de09 1550 countVideos = true
b84d4c80 1551 ): Promise<ResultList<VideoModel>> {
ce6b3765
C
1552 const span = tracer.startSpan('peertube.VideoModel.getAvailableForApi')
1553
6b842050
C
1554 function getCount () {
1555 if (countVideos !== true) return Promise.resolve(undefined)
8ea6f49a 1556
6b842050 1557 const countOptions = Object.assign({}, options, { isCount: true })
e5dbd508 1558 const queryBuilder = new VideosIdListQueryBuilder(VideoModel.sequelize)
3caf77d3 1559
e5dbd508 1560 return queryBuilder.countVideoIds(countOptions)
6b842050
C
1561 }
1562
1563 function getModels () {
baab47ca
C
1564 if (options.count === 0) return Promise.resolve([])
1565
e5dbd508 1566 const queryBuilder = new VideosModelListQueryBuilder(VideoModel.sequelize)
6b842050 1567
e5dbd508 1568 return queryBuilder.queryVideos(options)
6b842050
C
1569 }
1570
1571 const [ count, rows ] = await Promise.all([ getCount(), getModels() ])
afd2cba5 1572
ce6b3765
C
1573 span.end()
1574
ddc07312
C
1575 return {
1576 data: rows,
1577 total: count
1578 }
1579 }
1580
d324756e
C
1581 private static throwIfPrivateIncludeWithoutUser (include: VideoInclude, user: MUserAccountId) {
1582 if (VideoModel.isPrivateInclude(include) && !user?.hasRight(UserRight.SEE_ALL_VIDEOS)) {
527a52ac
C
1583 throw new Error('Try to filter all-local but user cannot see all videos')
1584 }
1585 }
1586
1587 private static throwIfPrivacyOneOfWithoutUser (privacyOneOf: VideoPrivacy[], user: MUserAccountId) {
1588 if (privacyOneOf && !user?.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1589 throw new Error('Try to choose video privacies but user cannot see all videos')
d324756e
C
1590 }
1591 }
1592
3c10840f
C
1593 private static isPrivateInclude (include: VideoInclude) {
1594 return include & VideoInclude.BLACKLISTED ||
1595 include & VideoInclude.BLOCKED_OWNER ||
3c10840f
C
1596 include & VideoInclude.NOT_PUBLISHED_STATE
1597 }
1598
5b77537c
C
1599 isBlacklisted () {
1600 return !!this.VideoBlacklist
1601 }
1602
bfbd9128 1603 isBlocked () {
faa9d434 1604 return this.VideoChannel.Account.Actor.Server?.isBlocked() || this.VideoChannel.Account.isBlocked()
bfbd9128
C
1605 }
1606
a1587156 1607 getQualityFileBy<T extends MVideoWithFile> (this: T, fun: (files: MVideoFile[], it: (file: MVideoFile) => number) => MVideoFile) {
b42c2c7e
C
1608 const files = this.getAllFiles()
1609 const file = fun(files, file => file.resolution)
1610 if (!file) return undefined
d7a25329 1611
b42c2c7e 1612 if (file.videoId) {
d7a25329
C
1613 return Object.assign(file, { Video: this })
1614 }
1615
b42c2c7e 1616 if (file.videoStreamingPlaylistId) {
d7a25329
C
1617 const streamingPlaylistWithVideo = Object.assign(this.VideoStreamingPlaylists[0], { Video: this })
1618
d7a25329
C
1619 return Object.assign(file, { VideoStreamingPlaylist: streamingPlaylistWithVideo })
1620 }
aaf61f38 1621
b42c2c7e 1622 throw new Error('File is not associated to a video of a playlist')
e4f97bab 1623 }
aaf61f38 1624
a1587156 1625 getMaxQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
92e0f42e
C
1626 return this.getQualityFileBy(maxBy)
1627 }
1628
a1587156 1629 getMinQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
92e0f42e
C
1630 return this.getQualityFileBy(minBy)
1631 }
1632
a1587156 1633 getWebTorrentFile<T extends MVideoWithFile> (this: T, resolution: number): MVideoFileVideo {
29d4e137
C
1634 if (Array.isArray(this.VideoFiles) === false) return undefined
1635
d7a25329
C
1636 const file = this.VideoFiles.find(f => f.resolution === resolution)
1637 if (!file) return undefined
1638
1639 return Object.assign(file, { Video: this })
29d4e137
C
1640 }
1641
6939cbac
C
1642 hasWebTorrentFiles () {
1643 return Array.isArray(this.VideoFiles) === true && this.VideoFiles.length !== 0
1644 }
1645
28dfb44b 1646 async addAndSaveThumbnail (thumbnail: MThumbnail, transaction?: Transaction) {
3acc5084
C
1647 thumbnail.videoId = this.id
1648
1649 const savedThumbnail = await thumbnail.save({ transaction })
1650
e8bafea3
C
1651 if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = []
1652
17ddba49 1653 this.Thumbnails = this.Thumbnails.filter(t => t.id !== savedThumbnail.id)
3acc5084 1654 this.Thumbnails.push(savedThumbnail)
e8bafea3
C
1655 }
1656
3acc5084 1657 getMiniature () {
e8bafea3
C
1658 if (Array.isArray(this.Thumbnails) === false) return undefined
1659
3acc5084 1660 return this.Thumbnails.find(t => t.type === ThumbnailType.MINIATURE)
e8bafea3
C
1661 }
1662
6872996d
C
1663 hasPreview () {
1664 return !!this.getPreview()
1665 }
1666
e8bafea3
C
1667 getPreview () {
1668 if (Array.isArray(this.Thumbnails) === false) return undefined
1669
1670 return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW)
3fd3ab2d 1671 }
7b1f49de 1672
3fd3ab2d
C
1673 isOwned () {
1674 return this.remote === false
9567011b
C
1675 }
1676
cef534ed 1677 getWatchStaticPath () {
29837f88 1678 return buildVideoWatchPath({ shortUUID: uuidToShort(this.uuid) })
cef534ed
C
1679 }
1680
40e87e9e 1681 getEmbedStaticPath () {
15a7eafb 1682 return buildVideoEmbedPath(this)
3fd3ab2d 1683 }
e4f97bab 1684
3acc5084
C
1685 getMiniatureStaticPath () {
1686 const thumbnail = this.getMiniature()
e8bafea3
C
1687 if (!thumbnail) return null
1688
1689 return join(STATIC_PATHS.THUMBNAILS, thumbnail.filename)
e4f97bab 1690 }
227d02fe 1691
40e87e9e 1692 getPreviewStaticPath () {
e8bafea3
C
1693 const preview = this.getPreview()
1694 if (!preview) return null
1695
1696 // We use a local cache, so specify our cache endpoint instead of potential remote URL
557b13ae 1697 return join(LAZY_STATIC_PATHS.PREVIEWS, preview.filename)
3fd3ab2d 1698 }
40298b02 1699
b5fecbf4 1700 toFormattedJSON (this: MVideoFormattable, options?: VideoFormattingJSONOptions): Video {
098eb377 1701 return videoModelToFormattedJSON(this, options)
14d3270f 1702 }
14d3270f 1703
b5fecbf4 1704 toFormattedDetailsJSON (this: MVideoFormattableDetails): VideoDetails {
098eb377 1705 return videoModelToFormattedDetailsJSON(this)
244e76a5
RK
1706 }
1707
f66db4d5 1708 getFormattedVideoFilesJSON (includeMagnet = true): VideoFile[] {
7a499487 1709 let files: VideoFile[] = []
97816649 1710
97816649 1711 if (Array.isArray(this.VideoFiles)) {
3545e72c 1712 const result = videoFilesModelToFormattedJSON(this, this.VideoFiles, { includeMagnet })
7a499487 1713 files = files.concat(result)
97816649
C
1714 }
1715
1716 for (const p of (this.VideoStreamingPlaylists || [])) {
3545e72c 1717 const result = videoFilesModelToFormattedJSON(this, p.VideoFiles, { includeMagnet })
7a499487 1718 files = files.concat(result)
97816649
C
1719 }
1720
7a499487 1721 return files
3fd3ab2d 1722 }
e4f97bab 1723
3b504f6e
C
1724 toActivityPubObject (this: MVideoAP): Promise<VideoObject> {
1725 return Hooks.wrapObject(
1726 videoModelToActivityPubObject(this),
58e735dd 1727 'filter:activity-pub.video.json-ld.build.result',
3b504f6e
C
1728 { video: this }
1729 )
3fd3ab2d
C
1730 }
1731
1732 getTruncatedDescription () {
1733 if (!this.description) return null
93e1258c 1734
bffbebbe 1735 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
687c6180 1736 return peertubeTruncate(this.description, { length: maxLength })
93e1258c
C
1737 }
1738
f012319a
C
1739 getAllFiles () {
1740 let files: MVideoFile[] = []
1741
1742 if (Array.isArray(this.VideoFiles)) {
1743 files = files.concat(this.VideoFiles)
1744 }
1745
1746 if (Array.isArray(this.VideoStreamingPlaylists)) {
1747 for (const p of this.VideoStreamingPlaylists) {
1748 if (Array.isArray(p.VideoFiles)) {
1749 files = files.concat(p.VideoFiles)
1750 }
1751 }
1752 }
1753
1754 return files
1755 }
1756
c729caf6 1757 probeMaxQualityFile () {
d7a25329
C
1758 const file = this.getMaxQualityFile()
1759 const videoOrPlaylist = file.getVideoOrStreamingPlaylist()
0d0e8dd0 1760
cbe2f36d
C
1761 return VideoPathManager.Instance.makeAvailableVideoFile(file.withVideoOrPlaylist(videoOrPlaylist), async originalFilePath => {
1762 const probe = await ffprobePromise(originalFilePath)
1763
1764 const { audioStream } = await getAudioStream(originalFilePath, probe)
a32bf8cd 1765 const hasAudio = await hasAudioStream(originalFilePath, probe)
0c9668f7 1766 const fps = await getVideoStreamFPS(originalFilePath, probe)
cbe2f36d
C
1767
1768 return {
1769 audioStream,
a32bf8cd 1770 hasAudio,
0c9668f7 1771 fps,
cbe2f36d 1772
c729caf6 1773 ...await getVideoStreamDimensionsInfo(originalFilePath, probe)
cbe2f36d 1774 }
0305db28 1775 })
3fd3ab2d 1776 }
0d0e8dd0 1777
96f29c0f 1778 getDescriptionAPIPath () {
3fd3ab2d 1779 return `/api/${API_VERSION}/videos/${this.uuid}/description`
feb4bdfd
C
1780 }
1781
d7a25329 1782 getHLSPlaylist (): MStreamingPlaylistFilesVideo {
e2600d8b
C
1783 if (!this.VideoStreamingPlaylists) return undefined
1784
d7a25329 1785 const playlist = this.VideoStreamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
e1ab52d7 1786 if (!playlist) return undefined
1787
9ab330b9 1788 return playlist.withVideo(this)
e2600d8b
C
1789 }
1790
d7a25329
C
1791 setHLSPlaylist (playlist: MStreamingPlaylist) {
1792 const toAdd = [ playlist ] as [ VideoStreamingPlaylistModel ]
b9fffa29 1793
d7a25329
C
1794 if (Array.isArray(this.VideoStreamingPlaylists) === false || this.VideoStreamingPlaylists.length === 0) {
1795 this.VideoStreamingPlaylists = toAdd
1796 return
1797 }
1798
1799 this.VideoStreamingPlaylists = this.VideoStreamingPlaylists
a1587156
C
1800 .filter(s => s.type !== VideoStreamingPlaylistType.HLS)
1801 .concat(toAdd)
d7a25329
C
1802 }
1803
1bb4c9ab 1804 removeWebTorrentFile (videoFile: MVideoFile, isRedundancy = false) {
0305db28
JB
1805 const filePath = isRedundancy
1806 ? VideoPathManager.Instance.getFSRedundancyVideoFilePath(this, videoFile)
1807 : VideoPathManager.Instance.getFSVideoFileOutputPath(this, videoFile)
764b1a14
C
1808
1809 const promises: Promise<any>[] = [ remove(filePath) ]
1810 if (!isRedundancy) promises.push(videoFile.removeTorrent())
1811
0305db28
JB
1812 if (videoFile.storage === VideoStorage.OBJECT_STORAGE) {
1813 promises.push(removeWebTorrentObjectStorage(videoFile))
1814 }
1815
764b1a14 1816 return Promise.all(promises)
feb4bdfd
C
1817 }
1818
ffc65cbd 1819 async removeStreamingPlaylistFiles (streamingPlaylist: MStreamingPlaylist, isRedundancy = false) {
0305db28
JB
1820 const directoryPath = isRedundancy
1821 ? getHLSRedundancyDirectory(this)
1822 : getHLSDirectory(this)
09209296 1823
ffc65cbd
C
1824 await remove(directoryPath)
1825
1826 if (isRedundancy !== true) {
a1587156 1827 const streamingPlaylistWithFiles = streamingPlaylist as MStreamingPlaylistFilesVideo
ffc65cbd
C
1828 streamingPlaylistWithFiles.Video = this
1829
1830 if (!Array.isArray(streamingPlaylistWithFiles.VideoFiles)) {
1831 streamingPlaylistWithFiles.VideoFiles = await streamingPlaylistWithFiles.$get('VideoFiles')
1832 }
1833
1834 // Remove physical files and torrents
1835 await Promise.all(
90a8bd30 1836 streamingPlaylistWithFiles.VideoFiles.map(file => file.removeTorrent())
ffc65cbd 1837 )
0305db28
JB
1838
1839 if (streamingPlaylist.storage === VideoStorage.OBJECT_STORAGE) {
ad5db104 1840 await removeHLSObjectStorage(streamingPlaylist.withVideo(this))
0305db28 1841 }
ffc65cbd 1842 }
09209296
C
1843 }
1844
7b6b445d
C
1845 async removeStreamingPlaylistVideoFile (streamingPlaylist: MStreamingPlaylist, videoFile: MVideoFile) {
1846 const filePath = VideoPathManager.Instance.getFSHLSOutputPath(this, videoFile.filename)
1847 await videoFile.removeTorrent()
1848 await remove(filePath)
1849
1bb4c9ab
C
1850 const resolutionFilename = getHlsResolutionPlaylistFilename(videoFile.filename)
1851 await remove(VideoPathManager.Instance.getFSHLSOutputPath(this, resolutionFilename))
1852
7b6b445d 1853 if (videoFile.storage === VideoStorage.OBJECT_STORAGE) {
aa887096
C
1854 await removeHLSFileObjectStorageByFilename(streamingPlaylist.withVideo(this), videoFile.filename)
1855 await removeHLSFileObjectStorageByFilename(streamingPlaylist.withVideo(this), resolutionFilename)
7b6b445d
C
1856 }
1857 }
1858
1859 async removeStreamingPlaylistFile (streamingPlaylist: MStreamingPlaylist, filename: string) {
1860 const filePath = VideoPathManager.Instance.getFSHLSOutputPath(this, filename)
1861 await remove(filePath)
1862
1863 if (streamingPlaylist.storage === VideoStorage.OBJECT_STORAGE) {
aa887096 1864 await removeHLSFileObjectStorageByFilename(streamingPlaylist.withVideo(this), filename)
7b6b445d
C
1865 }
1866 }
1867
1297eb5d
C
1868 isOutdated () {
1869 if (this.isOwned()) return false
1870
9f79ade6 1871 return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)
1297eb5d
C
1872 }
1873
22a73cb8 1874 hasPrivacyForFederation () {
3092e9bb 1875 return isPrivacyForFederation(this.privacy)
22a73cb8
C
1876 }
1877
68e70a74
C
1878 hasStateForFederation () {
1879 return isStateForFederation(this.state)
1880 }
1881
22a73cb8 1882 isNewVideo (newPrivacy: VideoPrivacy) {
3092e9bb 1883 return this.hasPrivacyForFederation() === false && isPrivacyForFederation(newPrivacy) === true
22a73cb8
C
1884 }
1885
597f771f 1886 setAsRefreshed (transaction?: Transaction) {
8c4bbd94 1887 return setAsUpdated({ sequelize: this.sequelize, table: 'video', id: this.id, transaction })
04b8c3fb
C
1888 }
1889
9ab330b9
C
1890 // ---------------------------------------------------------------------------
1891
1892 requiresAuth (options: {
1893 urlParamId: string
1894 checkBlacklist: boolean
1895 }) {
1896 const { urlParamId, checkBlacklist } = options
1897
1898 if (this.privacy === VideoPrivacy.PRIVATE || this.privacy === VideoPrivacy.INTERNAL) {
1899 return true
1900 }
1901
3545e72c 1902 if (this.privacy === VideoPrivacy.UNLISTED) {
9ab330b9 1903 if (urlParamId && !isUUIDValid(urlParamId)) return true
22a73cb8 1904
3545e72c 1905 return false
22a73cb8
C
1906 }
1907
9ab330b9
C
1908 if (checkBlacklist && this.VideoBlacklist) return true
1909
1910 if (this.privacy !== VideoPrivacy.PUBLIC) {
1911 throw new Error(`Unknown video privacy ${this.privacy} to know if the video requires auth`)
1912 }
1913
1914 return false
22a73cb8
C
1915 }
1916
9ab330b9
C
1917 hasPrivateStaticPath () {
1918 return isVideoInPrivateDirectory(this.privacy)
1919 }
1920
1921 // ---------------------------------------------------------------------------
1922
9db2330e 1923 async setNewState (newState: VideoState, isNewVideo: boolean, transaction: Transaction) {
0305db28
JB
1924 if (this.state === newState) throw new Error('Cannot use same state ' + newState)
1925
1926 this.state = newState
7920c273 1927
9db2330e 1928 if (this.state === VideoState.PUBLISHED && isNewVideo) {
0305db28 1929 this.publishedAt = new Date()
6fcd19ba 1930 }
aaf61f38 1931
0305db28 1932 await this.save({ transaction })
15d4ee04 1933 }
a96aed15 1934
e1ab52d7 1935 getBandwidthBits (this: MVideo, videoFile: MVideoFile) {
e4fc3697
C
1936 if (!this.duration) throw new Error(`Cannot get bandwidth bits because video ${this.url} has duration of 0`)
1937
d9a2a031 1938 return Math.ceil((videoFile.size * 8) / this.duration)
c48e82b5
C
1939 }
1940
d9a2a031
C
1941 getTrackerUrls () {
1942 if (this.isOwned()) {
1943 return [
1944 WEBSERVER.URL + '/tracker/announce',
1945 WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT + '/tracker/socket'
1946 ]
1947 }
09209296 1948
d9a2a031 1949 return this.Trackers.map(t => t.url)
09209296 1950 }
a96aed15 1951}