]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/models/video/video.ts
Feature/Add replay privacy (#5692)
[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 34import { getServerActor } from '@server/models/application/application'
8c4bbd94 35import { ModelCache } from '@server/models/shared/model-cache'
0628157f 36import { buildVideoEmbedPath, buildVideoWatchPath, pick } from '@shared/core-utils'
a32bf8cd 37import { ffprobePromise, getAudioStream, hasAudioStream, 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'
8c4bbd94 106import { buildTrigramSearchIndex, buildWhereIdOrUUID, getVideoSort, isOutdated, setAsUpdated, throwIfNotValid } from '../shared'
7d9ba5c0
C
107import { UserModel } from '../user/user'
108import { UserVideoHistoryModel } from '../user/user-video-history'
b2111066 109import { VideoViewModel } from '../view/video-view'
e5dbd508
C
110import {
111 videoFilesModelToFormattedJSON,
112 VideoFormattingJSONOptions,
113 videoModelToActivityPubObject,
114 videoModelToFormattedDetailsJSON,
115 videoModelToFormattedJSON
116} from './formatter/video-format-utils'
d95d1559 117import { ScheduleVideoUpdateModel } from './schedule-video-update'
d0800f76 118import {
119 BuildVideosListQueryOptions,
120 DisplayOnlyForFollowerOptions,
121 VideoModelGetQueryBuilder,
122 VideosIdListQueryBuilder,
123 VideosModelListQueryBuilder
124} from './sql/video'
d95d1559
C
125import { TagModel } from './tag'
126import { ThumbnailModel } from './thumbnail'
127import { VideoBlacklistModel } from './video-blacklist'
128import { VideoCaptionModel } from './video-caption'
129import { ScopeNames as VideoChannelScopeNames, SummaryOptions, VideoChannelModel } from './video-channel'
130import { VideoCommentModel } from './video-comment'
131import { VideoFileModel } from './video-file'
d95d1559 132import { VideoImportModel } from './video-import'
0305db28 133import { VideoJobInfoModel } from './video-job-info'
af4ae64f 134import { VideoLiveModel } from './video-live'
d95d1559 135import { VideoPlaylistElementModel } from './video-playlist-element'
d95d1559 136import { VideoShareModel } from './video-share'
630d0a1b 137import { VideoSourceModel } from './video-source'
d95d1559
C
138import { VideoStreamingPlaylistModel } from './video-streaming-playlist'
139import { VideoTagModel } from './video-tag'
3b504f6e 140import { Hooks } from '@server/lib/plugins/hooks'
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
26e3e98f 801 LiveManager.Instance.stopSessionOf(instance.id, 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
fe987656 1089 }) {
d324756e 1090 VideoModel.throwIfPrivateIncludeWithoutUser(options.include, options.user)
527a52ac 1091 VideoModel.throwIfPrivacyOneOfWithoutUser(options.privacyOneOf, options.user)
1cd3facc 1092
5f3e2425
C
1093 const trendingDays = options.sort.endsWith('trending')
1094 ? CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1095 : undefined
d6886027
C
1096
1097 let trendingAlgorithm: string
3d4e112d
RK
1098 if (options.sort.endsWith('hot')) trendingAlgorithm = 'hot'
1099 if (options.sort.endsWith('best')) trendingAlgorithm = 'best'
93e1258c 1100
7ad9b984
C
1101 const serverActor = await getServerActor()
1102
afd2cba5 1103 const queryOptions = {
9c9a236b
C
1104 ...pick(options, [
1105 'start',
1106 'count',
1107 'sort',
1108 'nsfw',
1109 'isLive',
1110 'categoryOneOf',
1111 'licenceOneOf',
1112 'languageOneOf',
1113 'tagsOneOf',
1114 'tagsAllOf',
527a52ac 1115 'privacyOneOf',
2760b454
C
1116 'isLocal',
1117 'include',
1118 'displayOnlyForFollower',
3c10840f 1119 'hasFiles',
9c9a236b
C
1120 'accountId',
1121 'videoChannelId',
1122 'videoPlaylistId',
9c9a236b
C
1123 'user',
1124 'historyOfUser',
d324756e
C
1125 'hasHLSFiles',
1126 'hasWebtorrentFiles',
9c9a236b
C
1127 'search'
1128 ]),
1129
2760b454 1130 serverAccountIdForBlock: serverActor.Account.id,
d8b34ee5 1131 trendingDays,
9c9a236b 1132 trendingAlgorithm
48dce1c9
C
1133 }
1134
5f3e2425 1135 return VideoModel.getAvailableForApi(queryOptions, options.countVideos)
93e1258c
C
1136 }
1137
0b18f4aa 1138 static async searchAndPopulateAccountAndServer (options: {
9c9a236b
C
1139 start: number
1140 count: number
1141 sort: string
d324756e 1142
0b18f4aa 1143 nsfw?: boolean
1fd61899 1144 isLive?: boolean
2760b454
C
1145 isLocal?: boolean
1146 include?: VideoInclude
d324756e 1147
0b18f4aa
C
1148 categoryOneOf?: number[]
1149 licenceOneOf?: number[]
1150 languageOneOf?: string[]
1151 tagsOneOf?: string[]
1152 tagsAllOf?: string[]
527a52ac 1153 privacyOneOf?: VideoPrivacy[]
d324756e
C
1154
1155 displayOnlyForFollower: DisplayOnlyForFollowerOptions | null
1156
1157 user?: MUserAccountId
1158
1159 hasWebtorrentFiles?: boolean
1160 hasHLSFiles?: boolean
1161
1162 search?: string
1163
1164 host?: string
1165 startDate?: string // ISO 8601
1166 endDate?: string // ISO 8601
1167 originallyPublishedStartDate?: string
1168 originallyPublishedEndDate?: string
1169
0b18f4aa
C
1170 durationMin?: number // seconds
1171 durationMax?: number // seconds
fbd67e7f 1172 uuids?: string[]
0b18f4aa 1173 }) {
d324756e 1174 VideoModel.throwIfPrivateIncludeWithoutUser(options.include, options.user)
527a52ac 1175 VideoModel.throwIfPrivacyOneOfWithoutUser(options.privacyOneOf, options.user)
d324756e 1176
f05a1c30 1177 const serverActor = await getServerActor()
1fd61899 1178
afd2cba5 1179 const queryOptions = {
9c9a236b 1180 ...pick(options, [
2760b454 1181 'include',
9c9a236b
C
1182 'nsfw',
1183 'isLive',
1184 'categoryOneOf',
1185 'licenceOneOf',
1186 'languageOneOf',
1187 'tagsOneOf',
1188 'tagsAllOf',
527a52ac 1189 'privacyOneOf',
9c9a236b 1190 'user',
2760b454 1191 'isLocal',
9c9a236b
C
1192 'host',
1193 'start',
1194 'count',
1195 'sort',
1196 'startDate',
1197 'endDate',
1198 'originallyPublishedStartDate',
1199 'originallyPublishedEndDate',
1200 'durationMin',
1201 'durationMax',
d324756e
C
1202 'hasHLSFiles',
1203 'hasWebtorrentFiles',
9c9a236b 1204 'uuids',
2760b454
C
1205 'search',
1206 'displayOnlyForFollower'
9c9a236b 1207 ]),
2760b454 1208 serverAccountIdForBlock: serverActor.Account.id
48dce1c9 1209 }
f05a1c30 1210
5f3e2425 1211 return VideoModel.getAvailableForApi(queryOptions)
f05a1c30
C
1212 }
1213
adc94cf0
C
1214 static countLives (options: {
1215 remote: boolean
1216 mode: 'published' | 'not-ended'
1217 }) {
1218 const query = {
a056ca48 1219 where: {
adc94cf0 1220 remote: options.remote,
875f0610 1221 isLive: true,
adc94cf0
C
1222 state: options.mode === 'not-ended'
1223 ? { [Op.ne]: VideoState.LIVE_ENDED }
1224 : { [Op.eq]: VideoState.PUBLISHED }
a056ca48
C
1225 }
1226 }
1227
adc94cf0 1228 return VideoModel.count(query)
a056ca48
C
1229 }
1230
77d7e851
C
1231 static countVideosUploadedByUserSince (userId: number, since: Date) {
1232 const options = {
1233 include: [
1234 {
1235 model: VideoChannelModel.unscoped(),
1236 required: true,
1237 include: [
1238 {
1239 model: AccountModel.unscoped(),
1240 required: true,
1241 include: [
1242 {
1243 model: UserModel.unscoped(),
1244 required: true,
1245 where: {
1246 id: userId
1247 }
1248 }
1249 ]
1250 }
1251 ]
1252 }
1253 ],
1254 where: {
1255 createdAt: {
1256 [Op.gte]: since
1257 }
1258 }
1259 }
1260
1261 return VideoModel.unscoped().count(options)
1262 }
1263
a056ca48
C
1264 static countLivesOfAccount (accountId: number) {
1265 const options = {
1266 where: {
1267 remote: false,
fb4b3f91
C
1268 isLive: true,
1269 state: {
1270 [Op.ne]: VideoState.LIVE_ENDED
1271 }
a056ca48
C
1272 },
1273 include: [
1274 {
1275 required: true,
1276 model: VideoChannelModel.unscoped(),
1277 where: {
1278 accountId
1279 }
1280 }
1281 ]
1282 }
1283
1284 return VideoModel.count(options)
1285 }
1286
71d4af1e 1287 static load (id: number | string, transaction?: Transaction): Promise<MVideoThumbnail> {
3c10840f 1288 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
d8755eed 1289
71d4af1e 1290 return queryBuilder.queryVideo({ id, transaction, type: 'thumbnails' })
3fd3ab2d 1291 }
d8755eed 1292
71d4af1e 1293 static loadWithBlacklist (id: number | string, transaction?: Transaction): Promise<MVideoThumbnailBlacklist> {
3c10840f 1294 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
d636ab58 1295
71d4af1e 1296 return queryBuilder.queryVideo({ id, transaction, type: 'thumbnails-blacklist' })
d636ab58
C
1297 }
1298
b49f22d8 1299 static loadImmutableAttributes (id: number | string, t?: Transaction): Promise<MVideoImmutable> {
7eba5e1f 1300 const fun = () => {
943e5193
C
1301 const query = {
1302 where: buildWhereIdOrUUID(id),
7eba5e1f
C
1303 transaction: t
1304 }
1305
943e5193 1306 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
7eba5e1f
C
1307 }
1308
1309 return ModelCache.Instance.doCache({
943e5193 1310 cacheType: 'load-video-immutable-id',
7eba5e1f
C
1311 key: '' + id,
1312 deleteKey: 'video',
1313 fun
1314 })
1315 }
1316
b49f22d8 1317 static loadByUrlImmutableAttributes (url: string, transaction?: Transaction): Promise<MVideoImmutable> {
943e5193
C
1318 const fun = () => {
1319 const query: FindOptions = {
1320 where: {
1321 url
1322 },
1323 transaction
1324 }
1325
1326 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1327 }
1328
1329 return ModelCache.Instance.doCache({
1330 cacheType: 'load-video-immutable-url',
1331 key: url,
1332 deleteKey: 'video',
1333 fun
1334 })
1335 }
1336
71d4af1e 1337 static loadOnlyId (id: number | string, transaction?: Transaction): Promise<MVideoId> {
3c10840f 1338 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
627621c1 1339
71d4af1e 1340 return queryBuilder.queryVideo({ id, transaction, type: 'id' })
627621c1
C
1341 }
1342
71d4af1e 1343 static loadWithFiles (id: number | string, transaction?: Transaction, logging?: boolean): Promise<MVideoWithAllFiles> {
3c10840f 1344 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
627621c1 1345
71d4af1e
C
1346 return queryBuilder.queryVideo({ id, transaction, type: 'all-files', logging })
1347 }
fd45e8f4 1348
71d4af1e 1349 static loadByUrl (url: string, transaction?: Transaction): Promise<MVideoThumbnail> {
3c10840f 1350 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
09209296 1351
71d4af1e
C
1352 return queryBuilder.queryVideo({ url, transaction, type: 'thumbnails' })
1353 }
1354
1355 static loadByUrlAndPopulateAccount (url: string, transaction?: Transaction): Promise<MVideoAccountLightBlacklistAllFiles> {
3c10840f 1356 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
71d4af1e
C
1357
1358 return queryBuilder.queryVideo({ url, transaction, type: 'account-blacklist-files' })
1359 }
1360
4fae2b1f 1361 static loadFull (id: number | string, t?: Transaction, userId?: number): Promise<MVideoFullLight> {
3c10840f 1362 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
09209296 1363
4fae2b1f 1364 return queryBuilder.queryVideo({ id, transaction: t, type: 'full', userId })
09209296
C
1365 }
1366
89cd1275 1367 static loadForGetAPI (parameters: {
a1587156 1368 id: number | string
ca4b4b2e 1369 transaction?: Transaction
89cd1275 1370 userId?: number
b49f22d8 1371 }): Promise<MVideoDetails> {
ca4b4b2e 1372 const { id, transaction, userId } = parameters
3c10840f 1373 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
09209296 1374
71d4af1e 1375 return queryBuilder.queryVideo({ id, transaction, type: 'api', userId })
da854ddd
C
1376 }
1377
09cababd 1378 static async getStats () {
630d0a1b 1379 const serverActor = await getServerActor()
09cababd
C
1380
1381 let totalLocalVideoViews = await VideoModel.sum('views', {
1382 where: {
1383 remote: false
1384 }
1385 })
baab47ca 1386
09cababd
C
1387 // Sequelize could return null...
1388 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1389
630d0a1b 1390 const baseOptions = {
baab47ca
C
1391 start: 0,
1392 count: 0,
1393 sort: '-publishedAt',
630d0a1b 1394 nsfw: null,
2760b454
C
1395 displayOnlyForFollower: {
1396 actorId: serverActor.id,
1397 orLocalVideos: true
3c10840f 1398 }
630d0a1b
C
1399 }
1400
1401 const { total: totalLocalVideos } = await VideoModel.listForApi({
1402 ...baseOptions,
1403
1404 isLocal: true
baab47ca
C
1405 })
1406
630d0a1b
C
1407 const { total: totalVideos } = await VideoModel.listForApi(baseOptions)
1408
09cababd
C
1409 return {
1410 totalLocalVideos,
1411 totalLocalVideoViews,
1412 totalVideos
1413 }
1414 }
1415
6b616860
C
1416 static incrementViews (id: number, views: number) {
1417 return VideoModel.increment('views', {
1418 by: views,
1419 where: {
1420 id
1421 }
1422 })
1423 }
1424
57e4e1c1
C
1425 static updateRatesOf (videoId: number, type: VideoRateType, count: number, t: Transaction) {
1426 const field = type === 'like'
1427 ? 'likes'
1428 : 'dislikes'
1429
1430 const rawQuery = `UPDATE "video" SET "${field}" = :count WHERE "video"."id" = :videoId`
1431
1432 return AccountVideoRateModel.sequelize.query(rawQuery, {
1433 transaction: t,
1434 replacements: { videoId, rateType: type, count },
1435 type: QueryTypes.UPDATE
1436 })
1437 }
1438
1439 static syncLocalRates (videoId: number, type: VideoRateType, t: Transaction) {
74d249bc
C
1440 const field = type === 'like'
1441 ? 'likes'
1442 : 'dislikes'
1443
1444 const rawQuery = `UPDATE "video" SET "${field}" = ` +
1445 '(' +
69322042 1446 'SELECT COUNT(id) FROM "accountVideoRate" WHERE "accountVideoRate"."videoId" = "video"."id" AND type = :rateType' +
74d249bc
C
1447 ') ' +
1448 'WHERE "video"."id" = :videoId'
1449
1450 return AccountVideoRateModel.sequelize.query(rawQuery, {
1451 transaction: t,
1452 replacements: { videoId, rateType: type },
1453 type: QueryTypes.UPDATE
1454 })
1455 }
1456
8d427346
C
1457 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1458 // Instances only share videos
1459 const query = 'SELECT 1 FROM "videoShare" ' +
a1587156 1460 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
f046e2fa 1461 'WHERE "actorFollow"."actorId" = $followerActorId AND "actorFollow"."state" = \'accepted\' AND "videoShare"."videoId" = $videoId ' +
11ae7e29
C
1462 'UNION ' +
1463 'SELECT 1 FROM "video" ' +
1464 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
1465 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
1466 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "account"."actorId" ' +
1467 'WHERE "actorFollow"."actorId" = $followerActorId AND "actorFollow"."state" = \'accepted\' AND "video"."id" = $videoId ' +
a1587156 1468 'LIMIT 1'
8d427346
C
1469
1470 const options = {
d5d9b6d7 1471 type: QueryTypes.SELECT as QueryTypes.SELECT,
8d427346
C
1472 bind: { followerActorId, videoId },
1473 raw: true
1474 }
1475
1476 return VideoModel.sequelize.query(query, options)
1477 .then(results => results.length === 1)
1478 }
1479
69322042 1480 static bulkUpdateSupportField (ofChannel: MChannel, t: Transaction) {
7d14d4d2
C
1481 const options = {
1482 where: {
69322042 1483 channelId: ofChannel.id
7d14d4d2
C
1484 },
1485 transaction: t
1486 }
1487
69322042 1488 return VideoModel.update({ support: ofChannel.support }, options)
7d14d4d2
C
1489 }
1490
b49f22d8 1491 static getAllIdsFromChannel (videoChannel: MChannelId): Promise<number[]> {
7d14d4d2
C
1492 const query = {
1493 attributes: [ 'id' ],
1494 where: {
1495 channelId: videoChannel.id
1496 }
1497 }
1498
1499 return VideoModel.findAll(query)
a1587156 1500 .then(videos => videos.map(v => v.id))
7d14d4d2
C
1501 }
1502
2d3741d6 1503 // threshold corresponds to how many video the field should have to be returned
7348b1fd 1504 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
65b21c96 1505 const serverActor = await getServerActor()
7348b1fd 1506
e5dbd508 1507 const queryOptions: BuildVideosListQueryOptions = {
5f3e2425
C
1508 attributes: [ `"${field}"` ],
1509 group: `GROUP BY "${field}"`,
1510 having: `HAVING COUNT("${field}") >= ${threshold}`,
1511 start: 0,
1512 sort: 'random',
1513 count,
2760b454
C
1514 serverAccountIdForBlock: serverActor.Account.id,
1515 displayOnlyForFollower: {
1516 actorId: serverActor.id,
1517 orLocalVideos: true
1518 }
7348b1fd
C
1519 }
1520
e5dbd508 1521 const queryBuilder = new VideosIdListQueryBuilder(VideoModel.sequelize)
2d3741d6 1522
e5dbd508
C
1523 return queryBuilder.queryVideoIds(queryOptions)
1524 .then(rows => rows.map(r => r[field]))
2d3741d6
C
1525 }
1526
b36f41ca
C
1527 static buildTrendingQuery (trendingDays: number) {
1528 return {
1529 attributes: [],
1530 subQuery: false,
1531 model: VideoViewModel,
1532 required: false,
1533 where: {
1534 startDate: {
c0d2eac3
C
1535 // FIXME: ts error
1536 [Op.gte as any]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
b36f41ca
C
1537 }
1538 }
1539 }
1540 }
1541
6e46de09 1542 private static async getAvailableForApi (
e5dbd508 1543 options: BuildVideosListQueryOptions,
6e46de09 1544 countVideos = true
b84d4c80 1545 ): Promise<ResultList<VideoModel>> {
ce6b3765
C
1546 const span = tracer.startSpan('peertube.VideoModel.getAvailableForApi')
1547
6b842050
C
1548 function getCount () {
1549 if (countVideos !== true) return Promise.resolve(undefined)
8ea6f49a 1550
6b842050 1551 const countOptions = Object.assign({}, options, { isCount: true })
e5dbd508 1552 const queryBuilder = new VideosIdListQueryBuilder(VideoModel.sequelize)
3caf77d3 1553
e5dbd508 1554 return queryBuilder.countVideoIds(countOptions)
6b842050
C
1555 }
1556
1557 function getModels () {
baab47ca
C
1558 if (options.count === 0) return Promise.resolve([])
1559
e5dbd508 1560 const queryBuilder = new VideosModelListQueryBuilder(VideoModel.sequelize)
6b842050 1561
e5dbd508 1562 return queryBuilder.queryVideos(options)
6b842050
C
1563 }
1564
1565 const [ count, rows ] = await Promise.all([ getCount(), getModels() ])
afd2cba5 1566
ce6b3765
C
1567 span.end()
1568
ddc07312
C
1569 return {
1570 data: rows,
1571 total: count
1572 }
1573 }
1574
d324756e
C
1575 private static throwIfPrivateIncludeWithoutUser (include: VideoInclude, user: MUserAccountId) {
1576 if (VideoModel.isPrivateInclude(include) && !user?.hasRight(UserRight.SEE_ALL_VIDEOS)) {
527a52ac
C
1577 throw new Error('Try to filter all-local but user cannot see all videos')
1578 }
1579 }
1580
1581 private static throwIfPrivacyOneOfWithoutUser (privacyOneOf: VideoPrivacy[], user: MUserAccountId) {
1582 if (privacyOneOf && !user?.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1583 throw new Error('Try to choose video privacies but user cannot see all videos')
d324756e
C
1584 }
1585 }
1586
3c10840f
C
1587 private static isPrivateInclude (include: VideoInclude) {
1588 return include & VideoInclude.BLACKLISTED ||
1589 include & VideoInclude.BLOCKED_OWNER ||
3c10840f
C
1590 include & VideoInclude.NOT_PUBLISHED_STATE
1591 }
1592
5b77537c
C
1593 isBlacklisted () {
1594 return !!this.VideoBlacklist
1595 }
1596
bfbd9128 1597 isBlocked () {
faa9d434 1598 return this.VideoChannel.Account.Actor.Server?.isBlocked() || this.VideoChannel.Account.isBlocked()
bfbd9128
C
1599 }
1600
a1587156 1601 getQualityFileBy<T extends MVideoWithFile> (this: T, fun: (files: MVideoFile[], it: (file: MVideoFile) => number) => MVideoFile) {
b42c2c7e
C
1602 const files = this.getAllFiles()
1603 const file = fun(files, file => file.resolution)
1604 if (!file) return undefined
d7a25329 1605
b42c2c7e 1606 if (file.videoId) {
d7a25329
C
1607 return Object.assign(file, { Video: this })
1608 }
1609
b42c2c7e 1610 if (file.videoStreamingPlaylistId) {
d7a25329
C
1611 const streamingPlaylistWithVideo = Object.assign(this.VideoStreamingPlaylists[0], { Video: this })
1612
d7a25329
C
1613 return Object.assign(file, { VideoStreamingPlaylist: streamingPlaylistWithVideo })
1614 }
aaf61f38 1615
b42c2c7e 1616 throw new Error('File is not associated to a video of a playlist')
e4f97bab 1617 }
aaf61f38 1618
a1587156 1619 getMaxQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
92e0f42e
C
1620 return this.getQualityFileBy(maxBy)
1621 }
1622
a1587156 1623 getMinQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
92e0f42e
C
1624 return this.getQualityFileBy(minBy)
1625 }
1626
a1587156 1627 getWebTorrentFile<T extends MVideoWithFile> (this: T, resolution: number): MVideoFileVideo {
29d4e137
C
1628 if (Array.isArray(this.VideoFiles) === false) return undefined
1629
d7a25329
C
1630 const file = this.VideoFiles.find(f => f.resolution === resolution)
1631 if (!file) return undefined
1632
1633 return Object.assign(file, { Video: this })
29d4e137
C
1634 }
1635
6939cbac
C
1636 hasWebTorrentFiles () {
1637 return Array.isArray(this.VideoFiles) === true && this.VideoFiles.length !== 0
1638 }
1639
28dfb44b 1640 async addAndSaveThumbnail (thumbnail: MThumbnail, transaction?: Transaction) {
3acc5084
C
1641 thumbnail.videoId = this.id
1642
1643 const savedThumbnail = await thumbnail.save({ transaction })
1644
e8bafea3
C
1645 if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = []
1646
17ddba49 1647 this.Thumbnails = this.Thumbnails.filter(t => t.id !== savedThumbnail.id)
3acc5084 1648 this.Thumbnails.push(savedThumbnail)
e8bafea3
C
1649 }
1650
3acc5084 1651 getMiniature () {
e8bafea3
C
1652 if (Array.isArray(this.Thumbnails) === false) return undefined
1653
3acc5084 1654 return this.Thumbnails.find(t => t.type === ThumbnailType.MINIATURE)
e8bafea3
C
1655 }
1656
6872996d
C
1657 hasPreview () {
1658 return !!this.getPreview()
1659 }
1660
e8bafea3
C
1661 getPreview () {
1662 if (Array.isArray(this.Thumbnails) === false) return undefined
1663
1664 return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW)
3fd3ab2d 1665 }
7b1f49de 1666
3fd3ab2d
C
1667 isOwned () {
1668 return this.remote === false
9567011b
C
1669 }
1670
cef534ed 1671 getWatchStaticPath () {
29837f88 1672 return buildVideoWatchPath({ shortUUID: uuidToShort(this.uuid) })
cef534ed
C
1673 }
1674
40e87e9e 1675 getEmbedStaticPath () {
15a7eafb 1676 return buildVideoEmbedPath(this)
3fd3ab2d 1677 }
e4f97bab 1678
3acc5084
C
1679 getMiniatureStaticPath () {
1680 const thumbnail = this.getMiniature()
e8bafea3
C
1681 if (!thumbnail) return null
1682
1683 return join(STATIC_PATHS.THUMBNAILS, thumbnail.filename)
e4f97bab 1684 }
227d02fe 1685
40e87e9e 1686 getPreviewStaticPath () {
e8bafea3
C
1687 const preview = this.getPreview()
1688 if (!preview) return null
1689
1690 // We use a local cache, so specify our cache endpoint instead of potential remote URL
557b13ae 1691 return join(LAZY_STATIC_PATHS.PREVIEWS, preview.filename)
3fd3ab2d 1692 }
40298b02 1693
b5fecbf4 1694 toFormattedJSON (this: MVideoFormattable, options?: VideoFormattingJSONOptions): Video {
098eb377 1695 return videoModelToFormattedJSON(this, options)
14d3270f 1696 }
14d3270f 1697
b5fecbf4 1698 toFormattedDetailsJSON (this: MVideoFormattableDetails): VideoDetails {
098eb377 1699 return videoModelToFormattedDetailsJSON(this)
244e76a5
RK
1700 }
1701
f66db4d5 1702 getFormattedVideoFilesJSON (includeMagnet = true): VideoFile[] {
7a499487 1703 let files: VideoFile[] = []
97816649 1704
97816649 1705 if (Array.isArray(this.VideoFiles)) {
3545e72c 1706 const result = videoFilesModelToFormattedJSON(this, this.VideoFiles, { includeMagnet })
7a499487 1707 files = files.concat(result)
97816649
C
1708 }
1709
1710 for (const p of (this.VideoStreamingPlaylists || [])) {
3545e72c 1711 const result = videoFilesModelToFormattedJSON(this, p.VideoFiles, { includeMagnet })
7a499487 1712 files = files.concat(result)
97816649
C
1713 }
1714
7a499487 1715 return files
3fd3ab2d 1716 }
e4f97bab 1717
3b504f6e
C
1718 toActivityPubObject (this: MVideoAP): Promise<VideoObject> {
1719 return Hooks.wrapObject(
1720 videoModelToActivityPubObject(this),
58e735dd 1721 'filter:activity-pub.video.json-ld.build.result',
3b504f6e
C
1722 { video: this }
1723 )
3fd3ab2d
C
1724 }
1725
1726 getTruncatedDescription () {
1727 if (!this.description) return null
93e1258c 1728
bffbebbe 1729 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
687c6180 1730 return peertubeTruncate(this.description, { length: maxLength })
93e1258c
C
1731 }
1732
f012319a
C
1733 getAllFiles () {
1734 let files: MVideoFile[] = []
1735
1736 if (Array.isArray(this.VideoFiles)) {
1737 files = files.concat(this.VideoFiles)
1738 }
1739
1740 if (Array.isArray(this.VideoStreamingPlaylists)) {
1741 for (const p of this.VideoStreamingPlaylists) {
1742 if (Array.isArray(p.VideoFiles)) {
1743 files = files.concat(p.VideoFiles)
1744 }
1745 }
1746 }
1747
1748 return files
1749 }
1750
c729caf6 1751 probeMaxQualityFile () {
d7a25329
C
1752 const file = this.getMaxQualityFile()
1753 const videoOrPlaylist = file.getVideoOrStreamingPlaylist()
0d0e8dd0 1754
cbe2f36d
C
1755 return VideoPathManager.Instance.makeAvailableVideoFile(file.withVideoOrPlaylist(videoOrPlaylist), async originalFilePath => {
1756 const probe = await ffprobePromise(originalFilePath)
1757
1758 const { audioStream } = await getAudioStream(originalFilePath, probe)
a32bf8cd 1759 const hasAudio = await hasAudioStream(originalFilePath, probe)
cbe2f36d
C
1760
1761 return {
1762 audioStream,
a32bf8cd 1763 hasAudio,
cbe2f36d 1764
c729caf6 1765 ...await getVideoStreamDimensionsInfo(originalFilePath, probe)
cbe2f36d 1766 }
0305db28 1767 })
3fd3ab2d 1768 }
0d0e8dd0 1769
96f29c0f 1770 getDescriptionAPIPath () {
3fd3ab2d 1771 return `/api/${API_VERSION}/videos/${this.uuid}/description`
feb4bdfd
C
1772 }
1773
d7a25329 1774 getHLSPlaylist (): MStreamingPlaylistFilesVideo {
e2600d8b
C
1775 if (!this.VideoStreamingPlaylists) return undefined
1776
d7a25329 1777 const playlist = this.VideoStreamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
e1ab52d7 1778 if (!playlist) return undefined
1779
9ab330b9 1780 return playlist.withVideo(this)
e2600d8b
C
1781 }
1782
d7a25329
C
1783 setHLSPlaylist (playlist: MStreamingPlaylist) {
1784 const toAdd = [ playlist ] as [ VideoStreamingPlaylistModel ]
b9fffa29 1785
d7a25329
C
1786 if (Array.isArray(this.VideoStreamingPlaylists) === false || this.VideoStreamingPlaylists.length === 0) {
1787 this.VideoStreamingPlaylists = toAdd
1788 return
1789 }
1790
1791 this.VideoStreamingPlaylists = this.VideoStreamingPlaylists
a1587156
C
1792 .filter(s => s.type !== VideoStreamingPlaylistType.HLS)
1793 .concat(toAdd)
d7a25329
C
1794 }
1795
1bb4c9ab 1796 removeWebTorrentFile (videoFile: MVideoFile, isRedundancy = false) {
0305db28
JB
1797 const filePath = isRedundancy
1798 ? VideoPathManager.Instance.getFSRedundancyVideoFilePath(this, videoFile)
1799 : VideoPathManager.Instance.getFSVideoFileOutputPath(this, videoFile)
764b1a14
C
1800
1801 const promises: Promise<any>[] = [ remove(filePath) ]
1802 if (!isRedundancy) promises.push(videoFile.removeTorrent())
1803
0305db28
JB
1804 if (videoFile.storage === VideoStorage.OBJECT_STORAGE) {
1805 promises.push(removeWebTorrentObjectStorage(videoFile))
1806 }
1807
764b1a14 1808 return Promise.all(promises)
feb4bdfd
C
1809 }
1810
ffc65cbd 1811 async removeStreamingPlaylistFiles (streamingPlaylist: MStreamingPlaylist, isRedundancy = false) {
0305db28
JB
1812 const directoryPath = isRedundancy
1813 ? getHLSRedundancyDirectory(this)
1814 : getHLSDirectory(this)
09209296 1815
ffc65cbd
C
1816 await remove(directoryPath)
1817
1818 if (isRedundancy !== true) {
a1587156 1819 const streamingPlaylistWithFiles = streamingPlaylist as MStreamingPlaylistFilesVideo
ffc65cbd
C
1820 streamingPlaylistWithFiles.Video = this
1821
1822 if (!Array.isArray(streamingPlaylistWithFiles.VideoFiles)) {
1823 streamingPlaylistWithFiles.VideoFiles = await streamingPlaylistWithFiles.$get('VideoFiles')
1824 }
1825
1826 // Remove physical files and torrents
1827 await Promise.all(
90a8bd30 1828 streamingPlaylistWithFiles.VideoFiles.map(file => file.removeTorrent())
ffc65cbd 1829 )
0305db28
JB
1830
1831 if (streamingPlaylist.storage === VideoStorage.OBJECT_STORAGE) {
ad5db104 1832 await removeHLSObjectStorage(streamingPlaylist.withVideo(this))
0305db28 1833 }
ffc65cbd 1834 }
09209296
C
1835 }
1836
7b6b445d
C
1837 async removeStreamingPlaylistVideoFile (streamingPlaylist: MStreamingPlaylist, videoFile: MVideoFile) {
1838 const filePath = VideoPathManager.Instance.getFSHLSOutputPath(this, videoFile.filename)
1839 await videoFile.removeTorrent()
1840 await remove(filePath)
1841
1bb4c9ab
C
1842 const resolutionFilename = getHlsResolutionPlaylistFilename(videoFile.filename)
1843 await remove(VideoPathManager.Instance.getFSHLSOutputPath(this, resolutionFilename))
1844
7b6b445d 1845 if (videoFile.storage === VideoStorage.OBJECT_STORAGE) {
aa887096
C
1846 await removeHLSFileObjectStorageByFilename(streamingPlaylist.withVideo(this), videoFile.filename)
1847 await removeHLSFileObjectStorageByFilename(streamingPlaylist.withVideo(this), resolutionFilename)
7b6b445d
C
1848 }
1849 }
1850
1851 async removeStreamingPlaylistFile (streamingPlaylist: MStreamingPlaylist, filename: string) {
1852 const filePath = VideoPathManager.Instance.getFSHLSOutputPath(this, filename)
1853 await remove(filePath)
1854
1855 if (streamingPlaylist.storage === VideoStorage.OBJECT_STORAGE) {
aa887096 1856 await removeHLSFileObjectStorageByFilename(streamingPlaylist.withVideo(this), filename)
7b6b445d
C
1857 }
1858 }
1859
1297eb5d
C
1860 isOutdated () {
1861 if (this.isOwned()) return false
1862
9f79ade6 1863 return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)
1297eb5d
C
1864 }
1865
22a73cb8 1866 hasPrivacyForFederation () {
3092e9bb 1867 return isPrivacyForFederation(this.privacy)
22a73cb8
C
1868 }
1869
68e70a74
C
1870 hasStateForFederation () {
1871 return isStateForFederation(this.state)
1872 }
1873
22a73cb8 1874 isNewVideo (newPrivacy: VideoPrivacy) {
3092e9bb 1875 return this.hasPrivacyForFederation() === false && isPrivacyForFederation(newPrivacy) === true
22a73cb8
C
1876 }
1877
597f771f 1878 setAsRefreshed (transaction?: Transaction) {
8c4bbd94 1879 return setAsUpdated({ sequelize: this.sequelize, table: 'video', id: this.id, transaction })
04b8c3fb
C
1880 }
1881
9ab330b9
C
1882 // ---------------------------------------------------------------------------
1883
1884 requiresAuth (options: {
1885 urlParamId: string
1886 checkBlacklist: boolean
1887 }) {
1888 const { urlParamId, checkBlacklist } = options
1889
1890 if (this.privacy === VideoPrivacy.PRIVATE || this.privacy === VideoPrivacy.INTERNAL) {
1891 return true
1892 }
1893
3545e72c 1894 if (this.privacy === VideoPrivacy.UNLISTED) {
9ab330b9 1895 if (urlParamId && !isUUIDValid(urlParamId)) return true
22a73cb8 1896
3545e72c 1897 return false
22a73cb8
C
1898 }
1899
9ab330b9
C
1900 if (checkBlacklist && this.VideoBlacklist) return true
1901
1902 if (this.privacy !== VideoPrivacy.PUBLIC) {
1903 throw new Error(`Unknown video privacy ${this.privacy} to know if the video requires auth`)
1904 }
1905
1906 return false
22a73cb8
C
1907 }
1908
9ab330b9
C
1909 hasPrivateStaticPath () {
1910 return isVideoInPrivateDirectory(this.privacy)
1911 }
1912
1913 // ---------------------------------------------------------------------------
1914
9db2330e 1915 async setNewState (newState: VideoState, isNewVideo: boolean, transaction: Transaction) {
0305db28
JB
1916 if (this.state === newState) throw new Error('Cannot use same state ' + newState)
1917
1918 this.state = newState
7920c273 1919
9db2330e 1920 if (this.state === VideoState.PUBLISHED && isNewVideo) {
0305db28 1921 this.publishedAt = new Date()
6fcd19ba 1922 }
aaf61f38 1923
0305db28 1924 await this.save({ transaction })
15d4ee04 1925 }
a96aed15 1926
e1ab52d7 1927 getBandwidthBits (this: MVideo, videoFile: MVideoFile) {
e4fc3697
C
1928 if (!this.duration) throw new Error(`Cannot get bandwidth bits because video ${this.url} has duration of 0`)
1929
d9a2a031 1930 return Math.ceil((videoFile.size * 8) / this.duration)
c48e82b5
C
1931 }
1932
d9a2a031
C
1933 getTrackerUrls () {
1934 if (this.isOwned()) {
1935 return [
1936 WEBSERVER.URL + '/tracker/announce',
1937 WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT + '/tracker/socket'
1938 ]
1939 }
09209296 1940
d9a2a031 1941 return this.Trackers.map(t => t.url)
09209296 1942 }
a96aed15 1943}