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