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