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