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