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