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