]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/models/video/video.ts
4979cee500b8e1bb2325105f9bbdaf91848cb13d
[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 MVideoIdThumbnail,
92 MVideoImmutable,
93 MVideoThumbnail,
94 MVideoThumbnailBlacklist,
95 MVideoWithAllFiles,
96 MVideoWithFile,
97 MVideoWithRights
98 } from '../../types/models'
99 import { MThumbnail } from '../../types/models/video/thumbnail'
100 import { MVideoFile, MVideoFileStreamingPlaylistVideo } from '../../types/models/video/video-file'
101 import { VideoAbuseModel } from '../abuse/video-abuse'
102 import { AccountModel } from '../account/account'
103 import { AccountVideoRateModel } from '../account/account-video-rate'
104 import { ActorModel } from '../actor/actor'
105 import { ActorImageModel } from '../actor/actor-image'
106 import { VideoRedundancyModel } from '../redundancy/video-redundancy'
107 import { ServerModel } from '../server/server'
108 import { TrackerModel } from '../server/tracker'
109 import { VideoTrackerModel } from '../server/video-tracker'
110 import { UserModel } from '../user/user'
111 import { UserVideoHistoryModel } from '../user/user-video-history'
112 import { buildTrigramSearchIndex, buildWhereIdOrUUID, getVideoSort, isOutdated, throwIfNotValid } from '../utils'
113 import {
114 videoFilesModelToFormattedJSON,
115 VideoFormattingJSONOptions,
116 videoModelToActivityPubObject,
117 videoModelToFormattedDetailsJSON,
118 videoModelToFormattedJSON
119 } from './formatter/video-format-utils'
120 import { ScheduleVideoUpdateModel } from './schedule-video-update'
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, t?: Transaction): Promise<MVideoThumbnail> {
1304 const where = buildWhereIdOrUUID(id)
1305 const options = {
1306 where,
1307 transaction: t
1308 }
1309
1310 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1311 }
1312
1313 static loadWithBlacklist (id: number | string, t?: Transaction): Promise<MVideoThumbnailBlacklist> {
1314 const where = buildWhereIdOrUUID(id)
1315 const options = {
1316 where,
1317 transaction: t
1318 }
1319
1320 return VideoModel.scope([
1321 ScopeNames.WITH_THUMBNAILS,
1322 ScopeNames.WITH_BLACKLISTED
1323 ]).findOne(options)
1324 }
1325
1326 static loadImmutableAttributes (id: number | string, t?: Transaction): Promise<MVideoImmutable> {
1327 const fun = () => {
1328 const query = {
1329 where: buildWhereIdOrUUID(id),
1330 transaction: t
1331 }
1332
1333 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1334 }
1335
1336 return ModelCache.Instance.doCache({
1337 cacheType: 'load-video-immutable-id',
1338 key: '' + id,
1339 deleteKey: 'video',
1340 fun
1341 })
1342 }
1343
1344 static loadWithRights (id: number | string, t?: Transaction): Promise<MVideoWithRights> {
1345 const where = buildWhereIdOrUUID(id)
1346 const options = {
1347 where,
1348 transaction: t
1349 }
1350
1351 return VideoModel.scope([
1352 ScopeNames.WITH_BLACKLISTED,
1353 ScopeNames.WITH_USER_ID
1354 ]).findOne(options)
1355 }
1356
1357 static loadOnlyId (id: number | string, t?: Transaction): Promise<MVideoIdThumbnail> {
1358 const where = buildWhereIdOrUUID(id)
1359
1360 const options = {
1361 attributes: [ 'id' ],
1362 where,
1363 transaction: t
1364 }
1365
1366 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1367 }
1368
1369 static loadWithFiles (id: number | string, t?: Transaction, logging?: boolean): Promise<MVideoWithAllFiles> {
1370 const where = buildWhereIdOrUUID(id)
1371
1372 const query = {
1373 where,
1374 transaction: t,
1375 logging
1376 }
1377
1378 return VideoModel.scope([
1379 ScopeNames.WITH_WEBTORRENT_FILES,
1380 ScopeNames.WITH_STREAMING_PLAYLISTS,
1381 ScopeNames.WITH_THUMBNAILS
1382 ]).findOne(query)
1383 }
1384
1385 static loadByUUID (uuid: string): Promise<MVideoThumbnail> {
1386 const options = {
1387 where: {
1388 uuid
1389 }
1390 }
1391
1392 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1393 }
1394
1395 static loadByUrl (url: string, transaction?: Transaction): Promise<MVideoThumbnail> {
1396 const query: FindOptions = {
1397 where: {
1398 url
1399 },
1400 transaction
1401 }
1402
1403 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(query)
1404 }
1405
1406 static loadByUrlImmutableAttributes (url: string, transaction?: Transaction): Promise<MVideoImmutable> {
1407 const fun = () => {
1408 const query: FindOptions = {
1409 where: {
1410 url
1411 },
1412 transaction
1413 }
1414
1415 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1416 }
1417
1418 return ModelCache.Instance.doCache({
1419 cacheType: 'load-video-immutable-url',
1420 key: url,
1421 deleteKey: 'video',
1422 fun
1423 })
1424 }
1425
1426 static loadByUrlAndPopulateAccount (url: string, transaction?: Transaction): Promise<MVideoAccountLightBlacklistAllFiles> {
1427 const query: FindOptions = {
1428 where: {
1429 url
1430 },
1431 transaction
1432 }
1433
1434 return VideoModel.scope([
1435 ScopeNames.WITH_ACCOUNT_DETAILS,
1436 ScopeNames.WITH_WEBTORRENT_FILES,
1437 ScopeNames.WITH_STREAMING_PLAYLISTS,
1438 ScopeNames.WITH_THUMBNAILS,
1439 ScopeNames.WITH_BLACKLISTED
1440 ]).findOne(query)
1441 }
1442
1443 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Transaction, userId?: number): Promise<MVideoFullLight> {
1444 const where = buildWhereIdOrUUID(id)
1445
1446 const options = {
1447 order: [ [ 'Tags', 'name', 'ASC' ] ] as any,
1448 where,
1449 transaction: t
1450 }
1451
1452 const scopes: (string | ScopeOptions)[] = [
1453 ScopeNames.WITH_TAGS,
1454 ScopeNames.WITH_BLACKLISTED,
1455 ScopeNames.WITH_ACCOUNT_DETAILS,
1456 ScopeNames.WITH_SCHEDULED_UPDATE,
1457 ScopeNames.WITH_WEBTORRENT_FILES,
1458 ScopeNames.WITH_STREAMING_PLAYLISTS,
1459 ScopeNames.WITH_THUMBNAILS,
1460 ScopeNames.WITH_LIVE
1461 ]
1462
1463 if (userId) {
1464 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1465 }
1466
1467 return VideoModel
1468 .scope(scopes)
1469 .findOne(options)
1470 }
1471
1472 static loadForGetAPI (parameters: {
1473 id: number | string
1474 t?: Transaction
1475 userId?: number
1476 }): Promise<MVideoDetails> {
1477 const { id, t, userId } = parameters
1478 const where = buildWhereIdOrUUID(id)
1479
1480 const options = {
1481 order: [ [ 'Tags', 'name', 'ASC' ] ] as any, // FIXME: sequelize typings
1482 where,
1483 transaction: t
1484 }
1485
1486 const scopes: (string | ScopeOptions)[] = [
1487 ScopeNames.WITH_TAGS,
1488 ScopeNames.WITH_BLACKLISTED,
1489 ScopeNames.WITH_ACCOUNT_DETAILS,
1490 ScopeNames.WITH_SCHEDULED_UPDATE,
1491 ScopeNames.WITH_THUMBNAILS,
1492 ScopeNames.WITH_LIVE,
1493 ScopeNames.WITH_TRACKERS,
1494 { method: [ ScopeNames.WITH_WEBTORRENT_FILES, true ] },
1495 { method: [ ScopeNames.WITH_STREAMING_PLAYLISTS, true ] }
1496 ]
1497
1498 if (userId) {
1499 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1500 }
1501
1502 return VideoModel
1503 .scope(scopes)
1504 .findOne(options)
1505 }
1506
1507 static async getStats () {
1508 const totalLocalVideos = await VideoModel.count({
1509 where: {
1510 remote: false
1511 }
1512 })
1513
1514 let totalLocalVideoViews = await VideoModel.sum('views', {
1515 where: {
1516 remote: false
1517 }
1518 })
1519
1520 // Sequelize could return null...
1521 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1522
1523 const { total: totalVideos } = await VideoModel.listForApi({
1524 start: 0,
1525 count: 0,
1526 sort: '-publishedAt',
1527 nsfw: buildNSFWFilter(),
1528 includeLocalVideos: true,
1529 withFiles: false
1530 })
1531
1532 return {
1533 totalLocalVideos,
1534 totalLocalVideoViews,
1535 totalVideos
1536 }
1537 }
1538
1539 static incrementViews (id: number, views: number) {
1540 return VideoModel.increment('views', {
1541 by: views,
1542 where: {
1543 id
1544 }
1545 })
1546 }
1547
1548 static updateRatesOf (videoId: number, type: VideoRateType, t: Transaction) {
1549 const field = type === 'like'
1550 ? 'likes'
1551 : 'dislikes'
1552
1553 const rawQuery = `UPDATE "video" SET "${field}" = ` +
1554 '(' +
1555 'SELECT COUNT(id) FROM "accountVideoRate" WHERE "accountVideoRate"."videoId" = "video"."id" AND type = :rateType' +
1556 ') ' +
1557 'WHERE "video"."id" = :videoId'
1558
1559 return AccountVideoRateModel.sequelize.query(rawQuery, {
1560 transaction: t,
1561 replacements: { videoId, rateType: type },
1562 type: QueryTypes.UPDATE
1563 })
1564 }
1565
1566 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1567 // Instances only share videos
1568 const query = 'SELECT 1 FROM "videoShare" ' +
1569 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1570 'WHERE "actorFollow"."actorId" = $followerActorId AND "actorFollow"."state" = \'accepted\' AND "videoShare"."videoId" = $videoId ' +
1571 'LIMIT 1'
1572
1573 const options = {
1574 type: QueryTypes.SELECT as QueryTypes.SELECT,
1575 bind: { followerActorId, videoId },
1576 raw: true
1577 }
1578
1579 return VideoModel.sequelize.query(query, options)
1580 .then(results => results.length === 1)
1581 }
1582
1583 static bulkUpdateSupportField (videoChannel: MChannel, t: Transaction) {
1584 const options = {
1585 where: {
1586 channelId: videoChannel.id
1587 },
1588 transaction: t
1589 }
1590
1591 return VideoModel.update({ support: videoChannel.support }, options)
1592 }
1593
1594 static getAllIdsFromChannel (videoChannel: MChannelId): Promise<number[]> {
1595 const query = {
1596 attributes: [ 'id' ],
1597 where: {
1598 channelId: videoChannel.id
1599 }
1600 }
1601
1602 return VideoModel.findAll(query)
1603 .then(videos => videos.map(v => v.id))
1604 }
1605
1606 // threshold corresponds to how many video the field should have to be returned
1607 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1608 const serverActor = await getServerActor()
1609 const followerActorId = serverActor.id
1610
1611 const queryOptions: BuildVideosListQueryOptions = {
1612 attributes: [ `"${field}"` ],
1613 group: `GROUP BY "${field}"`,
1614 having: `HAVING COUNT("${field}") >= ${threshold}`,
1615 start: 0,
1616 sort: 'random',
1617 count,
1618 serverAccountId: serverActor.Account.id,
1619 followerActorId,
1620 includeLocalVideos: true
1621 }
1622
1623 const queryBuilder = new VideosIdListQueryBuilder(VideoModel.sequelize)
1624
1625 return queryBuilder.queryVideoIds(queryOptions)
1626 .then(rows => rows.map(r => r[field]))
1627 }
1628
1629 static buildTrendingQuery (trendingDays: number) {
1630 return {
1631 attributes: [],
1632 subQuery: false,
1633 model: VideoViewModel,
1634 required: false,
1635 where: {
1636 startDate: {
1637 [Op.gte]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1638 }
1639 }
1640 }
1641 }
1642
1643 private static async getAvailableForApi (
1644 options: BuildVideosListQueryOptions,
1645 countVideos = true
1646 ): Promise<ResultList<VideoModel>> {
1647 function getCount () {
1648 if (countVideos !== true) return Promise.resolve(undefined)
1649
1650 const countOptions = Object.assign({}, options, { isCount: true })
1651 const queryBuilder = new VideosIdListQueryBuilder(VideoModel.sequelize)
1652
1653 return queryBuilder.countVideoIds(countOptions)
1654 }
1655
1656 function getModels () {
1657 if (options.count === 0) return Promise.resolve([])
1658
1659 const queryBuilder = new VideosModelListQueryBuilder(VideoModel.sequelize)
1660
1661 return queryBuilder.queryVideos(options)
1662 }
1663
1664 const [ count, rows ] = await Promise.all([ getCount(), getModels() ])
1665
1666 return {
1667 data: rows,
1668 total: count
1669 }
1670 }
1671
1672 static getCategoryLabel (id: number) {
1673 return VIDEO_CATEGORIES[id] || 'Misc'
1674 }
1675
1676 static getLicenceLabel (id: number) {
1677 return VIDEO_LICENCES[id] || 'Unknown'
1678 }
1679
1680 static getLanguageLabel (id: string) {
1681 return VIDEO_LANGUAGES[id] || 'Unknown'
1682 }
1683
1684 static getPrivacyLabel (id: number) {
1685 return VIDEO_PRIVACIES[id] || 'Unknown'
1686 }
1687
1688 static getStateLabel (id: number) {
1689 return VIDEO_STATES[id] || 'Unknown'
1690 }
1691
1692 isBlacklisted () {
1693 return !!this.VideoBlacklist
1694 }
1695
1696 isBlocked () {
1697 return this.VideoChannel.Account.Actor.Server?.isBlocked() || this.VideoChannel.Account.isBlocked()
1698 }
1699
1700 getQualityFileBy<T extends MVideoWithFile> (this: T, fun: (files: MVideoFile[], it: (file: MVideoFile) => number) => MVideoFile) {
1701 // We first transcode to WebTorrent format, so try this array first
1702 if (Array.isArray(this.VideoFiles) && this.VideoFiles.length !== 0) {
1703 const file = fun(this.VideoFiles, file => file.resolution)
1704
1705 return Object.assign(file, { Video: this })
1706 }
1707
1708 // No webtorrent files, try with streaming playlist files
1709 if (Array.isArray(this.VideoStreamingPlaylists) && this.VideoStreamingPlaylists.length !== 0) {
1710 const streamingPlaylistWithVideo = Object.assign(this.VideoStreamingPlaylists[0], { Video: this })
1711
1712 const file = fun(streamingPlaylistWithVideo.VideoFiles, file => file.resolution)
1713 return Object.assign(file, { VideoStreamingPlaylist: streamingPlaylistWithVideo })
1714 }
1715
1716 return undefined
1717 }
1718
1719 getMaxQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1720 return this.getQualityFileBy(maxBy)
1721 }
1722
1723 getMinQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1724 return this.getQualityFileBy(minBy)
1725 }
1726
1727 getWebTorrentFile<T extends MVideoWithFile> (this: T, resolution: number): MVideoFileVideo {
1728 if (Array.isArray(this.VideoFiles) === false) return undefined
1729
1730 const file = this.VideoFiles.find(f => f.resolution === resolution)
1731 if (!file) return undefined
1732
1733 return Object.assign(file, { Video: this })
1734 }
1735
1736 hasWebTorrentFiles () {
1737 return Array.isArray(this.VideoFiles) === true && this.VideoFiles.length !== 0
1738 }
1739
1740 async addAndSaveThumbnail (thumbnail: MThumbnail, transaction?: Transaction) {
1741 thumbnail.videoId = this.id
1742
1743 const savedThumbnail = await thumbnail.save({ transaction })
1744
1745 if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = []
1746
1747 // Already have this thumbnail, skip
1748 if (this.Thumbnails.find(t => t.id === savedThumbnail.id)) return
1749
1750 this.Thumbnails.push(savedThumbnail)
1751 }
1752
1753 getMiniature () {
1754 if (Array.isArray(this.Thumbnails) === false) return undefined
1755
1756 return this.Thumbnails.find(t => t.type === ThumbnailType.MINIATURE)
1757 }
1758
1759 hasPreview () {
1760 return !!this.getPreview()
1761 }
1762
1763 getPreview () {
1764 if (Array.isArray(this.Thumbnails) === false) return undefined
1765
1766 return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW)
1767 }
1768
1769 isOwned () {
1770 return this.remote === false
1771 }
1772
1773 getWatchStaticPath () {
1774 return '/w/' + this.uuid
1775 }
1776
1777 getEmbedStaticPath () {
1778 return '/videos/embed/' + this.uuid
1779 }
1780
1781 getMiniatureStaticPath () {
1782 const thumbnail = this.getMiniature()
1783 if (!thumbnail) return null
1784
1785 return join(STATIC_PATHS.THUMBNAILS, thumbnail.filename)
1786 }
1787
1788 getPreviewStaticPath () {
1789 const preview = this.getPreview()
1790 if (!preview) return null
1791
1792 // We use a local cache, so specify our cache endpoint instead of potential remote URL
1793 return join(LAZY_STATIC_PATHS.PREVIEWS, preview.filename)
1794 }
1795
1796 toFormattedJSON (this: MVideoFormattable, options?: VideoFormattingJSONOptions): Video {
1797 return videoModelToFormattedJSON(this, options)
1798 }
1799
1800 toFormattedDetailsJSON (this: MVideoFormattableDetails): VideoDetails {
1801 return videoModelToFormattedDetailsJSON(this)
1802 }
1803
1804 getFormattedVideoFilesJSON (includeMagnet = true): VideoFile[] {
1805 let files: VideoFile[] = []
1806
1807 if (Array.isArray(this.VideoFiles)) {
1808 const result = videoFilesModelToFormattedJSON(this, this.VideoFiles, includeMagnet)
1809 files = files.concat(result)
1810 }
1811
1812 for (const p of (this.VideoStreamingPlaylists || [])) {
1813 const result = videoFilesModelToFormattedJSON(this, p.VideoFiles, includeMagnet)
1814 files = files.concat(result)
1815 }
1816
1817 return files
1818 }
1819
1820 toActivityPubObject (this: MVideoAP): VideoObject {
1821 return videoModelToActivityPubObject(this)
1822 }
1823
1824 getTruncatedDescription () {
1825 if (!this.description) return null
1826
1827 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1828 return peertubeTruncate(this.description, { length: maxLength })
1829 }
1830
1831 getMaxQualityResolution () {
1832 const file = this.getMaxQualityFile()
1833 const videoOrPlaylist = file.getVideoOrStreamingPlaylist()
1834 const originalFilePath = getVideoFilePath(videoOrPlaylist, file)
1835
1836 return getVideoFileResolution(originalFilePath)
1837 }
1838
1839 getDescriptionAPIPath () {
1840 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1841 }
1842
1843 getHLSPlaylist (): MStreamingPlaylistFilesVideo {
1844 if (!this.VideoStreamingPlaylists) return undefined
1845
1846 const playlist = this.VideoStreamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
1847 playlist.Video = this
1848
1849 return playlist
1850 }
1851
1852 setHLSPlaylist (playlist: MStreamingPlaylist) {
1853 const toAdd = [ playlist ] as [ VideoStreamingPlaylistModel ]
1854
1855 if (Array.isArray(this.VideoStreamingPlaylists) === false || this.VideoStreamingPlaylists.length === 0) {
1856 this.VideoStreamingPlaylists = toAdd
1857 return
1858 }
1859
1860 this.VideoStreamingPlaylists = this.VideoStreamingPlaylists
1861 .filter(s => s.type !== VideoStreamingPlaylistType.HLS)
1862 .concat(toAdd)
1863 }
1864
1865 removeFile (videoFile: MVideoFile, isRedundancy = false) {
1866 const filePath = getVideoFilePath(this, videoFile, isRedundancy)
1867 return remove(filePath)
1868 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1869 }
1870
1871 async removeStreamingPlaylistFiles (streamingPlaylist: MStreamingPlaylist, isRedundancy = false) {
1872 const directoryPath = getHLSDirectory(this, isRedundancy)
1873
1874 await remove(directoryPath)
1875
1876 if (isRedundancy !== true) {
1877 const streamingPlaylistWithFiles = streamingPlaylist as MStreamingPlaylistFilesVideo
1878 streamingPlaylistWithFiles.Video = this
1879
1880 if (!Array.isArray(streamingPlaylistWithFiles.VideoFiles)) {
1881 streamingPlaylistWithFiles.VideoFiles = await streamingPlaylistWithFiles.$get('VideoFiles')
1882 }
1883
1884 // Remove physical files and torrents
1885 await Promise.all(
1886 streamingPlaylistWithFiles.VideoFiles.map(file => file.removeTorrent())
1887 )
1888 }
1889 }
1890
1891 isOutdated () {
1892 if (this.isOwned()) return false
1893
1894 return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)
1895 }
1896
1897 hasPrivacyForFederation () {
1898 return isPrivacyForFederation(this.privacy)
1899 }
1900
1901 hasStateForFederation () {
1902 return isStateForFederation(this.state)
1903 }
1904
1905 isNewVideo (newPrivacy: VideoPrivacy) {
1906 return this.hasPrivacyForFederation() === false && isPrivacyForFederation(newPrivacy) === true
1907 }
1908
1909 setAsRefreshed () {
1910 return setAsUpdated('video', this.id)
1911 }
1912
1913 requiresAuth () {
1914 return this.privacy === VideoPrivacy.PRIVATE || this.privacy === VideoPrivacy.INTERNAL || !!this.VideoBlacklist
1915 }
1916
1917 setPrivacy (newPrivacy: VideoPrivacy) {
1918 if (this.privacy === VideoPrivacy.PRIVATE && newPrivacy !== VideoPrivacy.PRIVATE) {
1919 this.publishedAt = new Date()
1920 }
1921
1922 this.privacy = newPrivacy
1923 }
1924
1925 isConfidential () {
1926 return this.privacy === VideoPrivacy.PRIVATE ||
1927 this.privacy === VideoPrivacy.UNLISTED ||
1928 this.privacy === VideoPrivacy.INTERNAL
1929 }
1930
1931 async publishIfNeededAndSave (t: Transaction) {
1932 if (this.state !== VideoState.PUBLISHED) {
1933 this.state = VideoState.PUBLISHED
1934 this.publishedAt = new Date()
1935 await this.save({ transaction: t })
1936
1937 return true
1938 }
1939
1940 return false
1941 }
1942
1943 getBandwidthBits (videoFile: MVideoFile) {
1944 return Math.ceil((videoFile.size * 8) / this.duration)
1945 }
1946
1947 getTrackerUrls () {
1948 if (this.isOwned()) {
1949 return [
1950 WEBSERVER.URL + '/tracker/announce',
1951 WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT + '/tracker/socket'
1952 ]
1953 }
1954
1955 return this.Trackers.map(t => t.url)
1956 }
1957 }