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