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