1 import * as Bluebird from 'bluebird'
2 import { maxBy, minBy } from 'lodash'
3 import { join } from 'path'
36 } from 'sequelize-typescript'
37 import { UserRight, VideoPrivacy, VideoState } from '../../../shared'
38 import { VideoTorrentObject } from '../../../shared/models/activitypub/objects'
39 import { Video, VideoDetails } from '../../../shared/models/videos'
40 import { VideoFilter } from '../../../shared/models/videos/video-query.type'
41 import { peertubeTruncate } from '../../helpers/core-utils'
42 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
43 import { isBooleanValid } from '../../helpers/custom-validators/misc'
46 isVideoDescriptionValid,
54 } from '../../helpers/custom-validators/videos'
55 import { getVideoFileResolution } from '../../helpers/ffmpeg-utils'
56 import { logger } from '../../helpers/logger'
57 import { getServerActor } from '../../helpers/utils'
64 STATIC_DOWNLOAD_PATHS,
72 } from '../../initializers/constants'
73 import { sendDeleteVideo } from '../../lib/activitypub/send'
74 import { AccountModel } from '../account/account'
75 import { AccountVideoRateModel } from '../account/account-video-rate'
76 import { ActorModel } from '../activitypub/actor'
77 import { AvatarModel } from '../avatar/avatar'
78 import { ServerModel } from '../server/server'
80 buildBlockedAccountSQL,
81 buildTrigramSearchIndex,
84 createSimilarityAttribute,
89 import { TagModel } from './tag'
90 import { VideoAbuseModel } from './video-abuse'
91 import { ScopeNames as VideoChannelScopeNames, SummaryOptions, VideoChannelModel } from './video-channel'
92 import { VideoCommentModel } from './video-comment'
93 import { VideoFileModel } from './video-file'
94 import { VideoShareModel } from './video-share'
95 import { VideoTagModel } from './video-tag'
96 import { ScheduleVideoUpdateModel } from './schedule-video-update'
97 import { VideoCaptionModel } from './video-caption'
98 import { VideoBlacklistModel } from './video-blacklist'
99 import { remove } from 'fs-extra'
100 import { VideoViewModel } from './video-views'
101 import { VideoRedundancyModel } from '../redundancy/video-redundancy'
103 videoFilesModelToFormattedJSON,
104 VideoFormattingJSONOptions,
105 videoModelToActivityPubObject,
106 videoModelToFormattedDetailsJSON,
107 videoModelToFormattedJSON
108 } from './video-format-utils'
109 import { UserVideoHistoryModel } from '../account/user-video-history'
110 import { VideoImportModel } from './video-import'
111 import { VideoStreamingPlaylistModel } from './video-streaming-playlist'
112 import { VideoPlaylistElementModel } from './video-playlist-element'
113 import { CONFIG } from '../../initializers/config'
114 import { ThumbnailModel } from './thumbnail'
115 import { ThumbnailType } from '../../../shared/models/videos/thumbnail.type'
116 import { VideoStreamingPlaylistType } from '../../../shared/models/videos/video-streaming-playlist.type'
119 MChannelAccountDefault,
122 MStreamingPlaylistFilesVideo,
126 MVideoAccountLightBlacklistAllFiles,
131 MVideoFormattableDetails,
136 MVideoThumbnailBlacklist,
140 MStreamingPlaylistFiles
141 } from '../../typings/models'
142 import { MVideoFile, MVideoFileStreamingPlaylistVideo } from '../../typings/models/video/video-file'
143 import { MThumbnail } from '../../typings/models/video/thumbnail'
144 import { VideoFile } from '@shared/models/videos/video-file.model'
145 import { getHLSDirectory, getTorrentFileName, getTorrentFilePath, getVideoFilename, getVideoFilePath } from '@server/lib/video-paths'
146 import validator from 'validator'
148 // FIXME: Define indexes here because there is an issue with TS and Sequelize.literal when called directly in the annotation
149 const indexes: (ModelIndexesOptions & { where?: WhereOptions })[] = [
150 buildTrigramSearchIndex('video_name_trigram', 'name'),
152 { fields: [ 'createdAt' ] },
155 { name: 'publishedAt', order: 'DESC' },
156 { name: 'id', order: 'ASC' }
159 { fields: [ 'duration' ] },
160 { fields: [ 'views' ] },
161 { fields: [ 'channelId' ] },
163 fields: [ 'originallyPublishedAt' ],
165 originallyPublishedAt: {
171 fields: [ 'category' ], // We don't care videos with an unknown category
179 fields: [ 'licence' ], // We don't care videos with an unknown licence
187 fields: [ 'language' ], // We don't care videos with an unknown language
195 fields: [ 'nsfw' ], // Most of the videos are not NSFW
201 fields: [ 'remote' ], // Only index local videos
216 export enum ScopeNames {
217 AVAILABLE_FOR_LIST_IDS = 'AVAILABLE_FOR_LIST_IDS',
219 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
220 WITH_TAGS = 'WITH_TAGS',
221 WITH_WEBTORRENT_FILES = 'WITH_WEBTORRENT_FILES',
222 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
223 WITH_BLACKLISTED = 'WITH_BLACKLISTED',
224 WITH_USER_HISTORY = 'WITH_USER_HISTORY',
225 WITH_STREAMING_PLAYLISTS = 'WITH_STREAMING_PLAYLISTS',
226 WITH_USER_ID = 'WITH_USER_ID',
227 WITH_THUMBNAILS = 'WITH_THUMBNAILS'
230 export type ForAPIOptions = {
233 videoPlaylistId?: number
237 withAccountBlockerIds?: number[]
240 export type AvailableForListIDsOptions = {
241 serverAccountId: number
242 followerActorId: number
243 includeLocalVideos: boolean
245 attributesType?: 'none' | 'id' | 'all'
248 categoryOneOf?: number[]
250 licenceOneOf?: number[]
251 languageOneOf?: string[]
258 videoChannelId?: number
260 videoPlaylistId?: number
262 trendingDays?: number
263 user?: MUserAccountId
264 historyOfUser?: MUserId
266 baseWhere?: WhereOptions[]
270 [ ScopeNames.FOR_API ]: (options: ForAPIOptions) => {
271 const query: FindOptions = {
274 model: VideoChannelModel.scope({
276 VideoChannelScopeNames.SUMMARY, {
278 withAccountBlockerIds: options.withAccountBlockerIds
285 attributes: [ 'type', 'filename' ],
286 model: ThumbnailModel,
295 [ Op.in ]: options.ids // FIXME: sequelize ANY seems broken
300 if (options.withFiles === true) {
302 model: VideoFileModel.unscoped(),
307 if (options.videoPlaylistId) {
309 model: VideoPlaylistElementModel.unscoped(),
312 videoPlaylistId: options.videoPlaylistId
319 [ ScopeNames.AVAILABLE_FOR_LIST_IDS ]: (options: AvailableForListIDsOptions) => {
320 const whereAnd = options.baseWhere ? [].concat(options.baseWhere) : []
322 const query: FindOptions = {
327 const attributesType = options.attributesType || 'id'
329 if (attributesType === 'id') query.attributes = [ 'id' ]
330 else if (attributesType === 'none') query.attributes = [ ]
334 [ Op.notIn ]: Sequelize.literal(
335 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
340 if (options.serverAccountId) {
343 [ Op.notIn ]: Sequelize.literal(
345 'SELECT id FROM "videoChannel" WHERE "accountId" IN (' +
346 buildBlockedAccountSQL(options.serverAccountId, options.user ? options.user.Account.id : undefined) +
354 // Only list public/published videos
355 if (!options.filter || options.filter !== 'all-local') {
357 const publishWhere = {
358 // Always list published videos, or videos that are being transcoded but on which we don't want to wait for transcoding
361 state: VideoState.PUBLISHED
365 state: VideoState.TO_TRANSCODE,
366 waitTranscoding: false
371 whereAnd.push(publishWhere)
373 // List internal videos if the user is logged in
375 const privacyWhere = {
378 privacy: VideoPrivacy.INTERNAL
381 privacy: VideoPrivacy.PUBLIC
386 whereAnd.push(privacyWhere)
387 } else { // Or only public videos
388 const privacyWhere = { privacy: VideoPrivacy.PUBLIC }
389 whereAnd.push(privacyWhere)
393 if (options.videoPlaylistId) {
396 model: VideoPlaylistElementModel.unscoped(),
399 videoPlaylistId: options.videoPlaylistId
403 query.subQuery = false
406 if (options.filter && (options.filter === 'local' || options.filter === 'all-local')) {
412 if (options.accountId || options.videoChannelId) {
413 const videoChannelInclude: IncludeOptions = {
415 model: VideoChannelModel.unscoped(),
419 if (options.videoChannelId) {
420 videoChannelInclude.where = {
421 id: options.videoChannelId
425 if (options.accountId) {
426 const accountInclude: IncludeOptions = {
428 model: AccountModel.unscoped(),
432 accountInclude.where = { id: options.accountId }
433 videoChannelInclude.include = [ accountInclude ]
436 query.include.push(videoChannelInclude)
439 if (options.followerActorId) {
440 let localVideosReq: WhereOptions = {}
441 if (options.includeLocalVideos === true) {
442 localVideosReq = { remote: false }
445 // Force actorId to be a number to avoid SQL injections
446 const actorIdNumber = parseInt(options.followerActorId.toString(), 10)
451 [ Op.in ]: Sequelize.literal(
453 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
454 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
455 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
462 [ Op.in ]: Sequelize.literal(
464 'SELECT "video"."id" AS "id" FROM "video" ' +
465 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
466 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
467 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
468 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
469 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
479 if (options.withFiles === true) {
482 [ Op.in ]: Sequelize.literal(
483 '(SELECT "videoId" FROM "videoFile")'
489 // FIXME: issues with sequelize count when making a join on n:m relation, so we just make a IN()
490 if (options.tagsAllOf || options.tagsOneOf) {
491 if (options.tagsOneOf) {
492 const tagsOneOfLower = options.tagsOneOf.map(t => t.toLowerCase())
496 [ Op.in ]: Sequelize.literal(
498 'SELECT "videoId" FROM "videoTag" ' +
499 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
500 'WHERE lower("tag"."name") IN (' + createSafeIn(VideoModel, tagsOneOfLower) + ')' +
507 if (options.tagsAllOf) {
508 const tagsAllOfLower = options.tagsAllOf.map(t => t.toLowerCase())
512 [ Op.in ]: Sequelize.literal(
514 'SELECT "videoId" FROM "videoTag" ' +
515 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
516 'WHERE lower("tag"."name") IN (' + createSafeIn(VideoModel, tagsAllOfLower) + ')' +
517 'GROUP BY "videoTag"."videoId" HAVING COUNT(*) = ' + tagsAllOfLower.length +
525 if (options.nsfw === true || options.nsfw === false) {
526 whereAnd.push({ nsfw: options.nsfw })
529 if (options.categoryOneOf) {
532 [ Op.or ]: options.categoryOneOf
537 if (options.licenceOneOf) {
540 [ Op.or ]: options.licenceOneOf
545 if (options.languageOneOf) {
546 let videoLanguages = options.languageOneOf
547 if (options.languageOneOf.find(l => l === '_unknown')) {
548 videoLanguages = videoLanguages.concat([ null ])
555 [ Op.or ]: videoLanguages
560 [ Op.in ]: Sequelize.literal(
562 'SELECT "videoId" FROM "videoCaption" ' +
563 'WHERE "language" IN (' + createSafeIn(VideoModel, options.languageOneOf) + ') ' +
572 if (options.trendingDays) {
573 query.include.push(VideoModel.buildTrendingQuery(options.trendingDays))
575 query.subQuery = false
578 if (options.historyOfUser) {
580 model: UserVideoHistoryModel,
583 userId: options.historyOfUser.id
587 // Even if the relation is n:m, we know that a user only have 0..1 video history
588 // So we won't have multiple rows for the same video
589 // Without this, we would not be able to sort on "updatedAt" column of UserVideoHistoryModel
590 query.subQuery = false
599 [ ScopeNames.WITH_THUMBNAILS ]: {
602 model: ThumbnailModel,
607 [ ScopeNames.WITH_USER_ID ]: {
610 attributes: [ 'accountId' ],
611 model: VideoChannelModel.unscoped(),
615 attributes: [ 'userId' ],
616 model: AccountModel.unscoped(),
623 [ ScopeNames.WITH_ACCOUNT_DETAILS ]: {
626 model: VideoChannelModel.unscoped(),
631 exclude: [ 'privateKey', 'publicKey' ]
633 model: ActorModel.unscoped(),
637 attributes: [ 'host' ],
638 model: ServerModel.unscoped(),
642 model: AvatarModel.unscoped(),
648 model: AccountModel.unscoped(),
652 model: ActorModel.unscoped(),
654 exclude: [ 'privateKey', 'publicKey' ]
659 attributes: [ 'host' ],
660 model: ServerModel.unscoped(),
664 model: AvatarModel.unscoped(),
675 [ ScopeNames.WITH_TAGS ]: {
676 include: [ TagModel ]
678 [ ScopeNames.WITH_BLACKLISTED ]: {
681 attributes: [ 'id', 'reason', 'unfederated' ],
682 model: VideoBlacklistModel,
687 [ ScopeNames.WITH_WEBTORRENT_FILES ]: (withRedundancies = false) => {
688 let subInclude: any[] = []
690 if (withRedundancies === true) {
693 attributes: [ 'fileUrl' ],
694 model: VideoRedundancyModel.unscoped(),
703 model: VideoFileModel.unscoped(),
704 separate: true, // We may have multiple files, having multiple redundancies so let's separate this join
711 [ ScopeNames.WITH_STREAMING_PLAYLISTS ]: (withRedundancies = false) => {
712 const subInclude: IncludeOptions[] = [
714 model: VideoFileModel.unscoped(),
719 if (withRedundancies === true) {
721 attributes: [ 'fileUrl' ],
722 model: VideoRedundancyModel.unscoped(),
730 model: VideoStreamingPlaylistModel.unscoped(),
731 separate: true, // We may have multiple streaming playlists, having multiple redundancies so let's separate this join
738 [ ScopeNames.WITH_SCHEDULED_UPDATE ]: {
741 model: ScheduleVideoUpdateModel.unscoped(),
746 [ ScopeNames.WITH_USER_HISTORY ]: (userId: number) => {
750 attributes: [ 'currentTime' ],
751 model: UserVideoHistoryModel.unscoped(),
765 export class VideoModel extends Model<VideoModel> {
768 @Default(DataType.UUIDV4)
770 @Column(DataType.UUID)
774 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
780 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category', true))
786 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence', true))
792 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language', true))
793 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
797 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
802 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
808 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description', true))
809 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
814 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support', true))
815 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
819 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
849 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
850 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
855 commentsEnabled: boolean
859 downloadEnabled: boolean
863 waitTranscoding: boolean
867 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
878 @Default(DataType.NOW)
885 originallyPublishedAt: Date
887 @ForeignKey(() => VideoChannelModel)
891 @BelongsTo(() => VideoChannelModel, {
897 VideoChannel: VideoChannelModel
899 @BelongsToMany(() => TagModel, {
900 foreignKey: 'videoId',
901 through: () => VideoTagModel,
906 @HasMany(() => ThumbnailModel, {
914 Thumbnails: ThumbnailModel[]
916 @HasMany(() => VideoPlaylistElementModel, {
923 VideoPlaylistElements: VideoPlaylistElementModel[]
925 @HasMany(() => VideoAbuseModel, {
932 VideoAbuses: VideoAbuseModel[]
934 @HasMany(() => VideoFileModel, {
942 VideoFiles: VideoFileModel[]
944 @HasMany(() => VideoStreamingPlaylistModel, {
952 VideoStreamingPlaylists: VideoStreamingPlaylistModel[]
954 @HasMany(() => VideoShareModel, {
961 VideoShares: VideoShareModel[]
963 @HasMany(() => AccountVideoRateModel, {
970 AccountVideoRates: AccountVideoRateModel[]
972 @HasMany(() => VideoCommentModel, {
980 VideoComments: VideoCommentModel[]
982 @HasMany(() => VideoViewModel, {
989 VideoViews: VideoViewModel[]
991 @HasMany(() => UserVideoHistoryModel, {
998 UserVideoHistories: UserVideoHistoryModel[]
1000 @HasOne(() => ScheduleVideoUpdateModel, {
1007 ScheduleVideoUpdate: ScheduleVideoUpdateModel
1009 @HasOne(() => VideoBlacklistModel, {
1016 VideoBlacklist: VideoBlacklistModel
1018 @HasOne(() => VideoImportModel, {
1023 onDelete: 'set null'
1025 VideoImport: VideoImportModel
1027 @HasMany(() => VideoCaptionModel, {
1032 onDelete: 'cascade',
1034 [ 'separate' as any ]: true
1036 VideoCaptions: VideoCaptionModel[]
1039 static async sendDelete (instance: MVideoAccountLight, options) {
1040 if (instance.isOwned()) {
1041 if (!instance.VideoChannel) {
1042 instance.VideoChannel = await instance.$get('VideoChannel', {
1047 transaction: options.transaction
1048 }) as MChannelAccountDefault
1051 return sendDeleteVideo(instance, options.transaction)
1058 static async removeFiles (instance: VideoModel) {
1059 const tasks: Promise<any>[] = []
1061 logger.info('Removing files of video %s.', instance.url)
1063 if (instance.isOwned()) {
1064 if (!Array.isArray(instance.VideoFiles)) {
1065 instance.VideoFiles = await instance.$get('VideoFiles')
1068 // Remove physical files and torrents
1069 instance.VideoFiles.forEach(file => {
1070 tasks.push(instance.removeFile(file))
1071 tasks.push(instance.removeTorrent(file))
1074 // Remove playlists file
1075 if (!Array.isArray(instance.VideoStreamingPlaylists)) {
1076 instance.VideoStreamingPlaylists = await instance.$get('VideoStreamingPlaylists')
1079 for (const p of instance.VideoStreamingPlaylists) {
1080 tasks.push(instance.removeStreamingPlaylistFiles(p))
1084 // Do not wait video deletion because we could be in a transaction
1087 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
1093 static listLocal (): Bluebird<MVideoWithAllFiles[]> {
1100 return VideoModel.scope([
1101 ScopeNames.WITH_WEBTORRENT_FILES,
1102 ScopeNames.WITH_STREAMING_PLAYLISTS,
1103 ScopeNames.WITH_THUMBNAILS
1107 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
1108 function getRawQuery (select: string) {
1109 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
1110 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
1111 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
1112 'WHERE "Account"."actorId" = ' + actorId
1113 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
1114 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
1115 'WHERE "VideoShare"."actorId" = ' + actorId
1117 return `(${queryVideo}) UNION (${queryVideoShare})`
1120 const rawQuery = getRawQuery('"Video"."id"')
1121 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
1127 order: getVideoSort('createdAt', [ 'Tags', 'name', 'ASC' ] as any), // FIXME: sequelize typings
1130 [ Op.in ]: Sequelize.literal('(' + rawQuery + ')')
1133 { privacy: VideoPrivacy.PUBLIC },
1134 { privacy: VideoPrivacy.UNLISTED }
1139 attributes: [ 'language' ],
1140 model: VideoCaptionModel.unscoped(),
1144 attributes: [ 'id', 'url' ],
1145 model: VideoShareModel.unscoped(),
1147 // We only want videos shared by this actor
1162 attributes: [ 'id', 'url' ],
1163 model: ActorModel.unscoped()
1168 model: VideoChannelModel.unscoped(),
1172 attributes: [ 'name' ],
1173 model: AccountModel.unscoped(),
1177 attributes: [ 'id', 'url', 'followersUrl' ],
1178 model: ActorModel.unscoped(),
1184 attributes: [ 'id', 'url', 'followersUrl' ],
1185 model: ActorModel.unscoped(),
1195 return Bluebird.all([
1196 VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findAll(query),
1197 VideoModel.sequelize.query<{ total: string }>(rawCountQuery, { type: QueryTypes.SELECT })
1198 ]).then(([ rows, totals ]) => {
1199 // totals: totalVideos + totalVideoShares
1201 let totalVideoShares = 0
1202 if (totals[ 0 ]) totalVideos = parseInt(totals[ 0 ].total, 10)
1203 if (totals[ 1 ]) totalVideoShares = parseInt(totals[ 1 ].total, 10)
1205 const total = totalVideos + totalVideoShares
1213 static listUserVideosForApi (
1220 function buildBaseQuery (): FindOptions {
1224 order: getVideoSort(sort),
1227 model: VideoChannelModel,
1231 model: AccountModel,
1243 baseQuery = Object.assign(baseQuery, {
1246 [ Op.iLike ]: '%' + search + '%'
1255 const countQuery = buildBaseQuery()
1256 const findQuery = buildBaseQuery()
1258 const findScopes: (string | ScopeOptions)[] = [
1259 ScopeNames.WITH_SCHEDULED_UPDATE,
1260 ScopeNames.WITH_BLACKLISTED,
1261 ScopeNames.WITH_THUMBNAILS
1264 return Promise.all([
1265 VideoModel.count(countQuery),
1266 VideoModel.scope(findScopes).findAll<MVideoForUser>(findQuery)
1267 ]).then(([ count, rows ]) => {
1275 static async listForApi (options: {
1280 includeLocalVideos: boolean,
1282 categoryOneOf?: number[],
1283 licenceOneOf?: number[],
1284 languageOneOf?: string[],
1285 tagsOneOf?: string[],
1286 tagsAllOf?: string[],
1287 filter?: VideoFilter,
1289 videoChannelId?: number,
1290 followerActorId?: number
1291 videoPlaylistId?: number,
1292 trendingDays?: number,
1293 user?: MUserAccountId,
1294 historyOfUser?: MUserId,
1295 countVideos?: boolean
1297 if (options.filter && options.filter === 'all-local' && !options.user.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1298 throw new Error('Try to filter all-local but no user has not the see all videos right')
1301 const query: FindOptions & { where?: null } = {
1302 offset: options.start,
1303 limit: options.count,
1304 order: getVideoSort(options.sort)
1307 let trendingDays: number
1308 if (options.sort.endsWith('trending')) {
1309 trendingDays = CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1311 query.group = 'VideoModel.id'
1314 const serverActor = await getServerActor()
1316 // followerActorId === null has a meaning, so just check undefined
1317 const followerActorId = options.followerActorId !== undefined ? options.followerActorId : serverActor.id
1319 const queryOptions = {
1321 serverAccountId: serverActor.Account.id,
1323 categoryOneOf: options.categoryOneOf,
1324 licenceOneOf: options.licenceOneOf,
1325 languageOneOf: options.languageOneOf,
1326 tagsOneOf: options.tagsOneOf,
1327 tagsAllOf: options.tagsAllOf,
1328 filter: options.filter,
1329 withFiles: options.withFiles,
1330 accountId: options.accountId,
1331 videoChannelId: options.videoChannelId,
1332 videoPlaylistId: options.videoPlaylistId,
1333 includeLocalVideos: options.includeLocalVideos,
1335 historyOfUser: options.historyOfUser,
1339 return VideoModel.getAvailableForApi(query, queryOptions, options.countVideos)
1342 static async searchAndPopulateAccountAndServer (options: {
1343 includeLocalVideos: boolean
1348 startDate?: string // ISO 8601
1349 endDate?: string // ISO 8601
1350 originallyPublishedStartDate?: string
1351 originallyPublishedEndDate?: string
1353 categoryOneOf?: number[]
1354 licenceOneOf?: number[]
1355 languageOneOf?: string[]
1356 tagsOneOf?: string[]
1357 tagsAllOf?: string[]
1358 durationMin?: number // seconds
1359 durationMax?: number // seconds
1360 user?: MUserAccountId,
1361 filter?: VideoFilter
1365 if (options.startDate || options.endDate) {
1366 const publishedAtRange = {}
1368 if (options.startDate) publishedAtRange[ Op.gte ] = options.startDate
1369 if (options.endDate) publishedAtRange[ Op.lte ] = options.endDate
1371 whereAnd.push({ publishedAt: publishedAtRange })
1374 if (options.originallyPublishedStartDate || options.originallyPublishedEndDate) {
1375 const originallyPublishedAtRange = {}
1377 if (options.originallyPublishedStartDate) originallyPublishedAtRange[ Op.gte ] = options.originallyPublishedStartDate
1378 if (options.originallyPublishedEndDate) originallyPublishedAtRange[ Op.lte ] = options.originallyPublishedEndDate
1380 whereAnd.push({ originallyPublishedAt: originallyPublishedAtRange })
1383 if (options.durationMin || options.durationMax) {
1384 const durationRange = {}
1386 if (options.durationMin) durationRange[ Op.gte ] = options.durationMin
1387 if (options.durationMax) durationRange[ Op.lte ] = options.durationMax
1389 whereAnd.push({ duration: durationRange })
1392 const attributesInclude = []
1393 const escapedSearch = VideoModel.sequelize.escape(options.search)
1394 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
1395 if (options.search) {
1396 const trigramSearch = {
1398 [ Op.in ]: Sequelize.literal(
1400 'SELECT "video"."id" FROM "video" ' +
1402 'lower(immutable_unaccent("video"."name")) % lower(immutable_unaccent(' + escapedSearch + ')) OR ' +
1403 'lower(immutable_unaccent("video"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))' +
1405 'SELECT "video"."id" FROM "video" LEFT JOIN "videoTag" ON "videoTag"."videoId" = "video"."id" ' +
1406 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
1407 'WHERE lower("tag"."name") = lower(' + escapedSearch + ')' +
1413 if (validator.isUUID(options.search)) {
1418 uuid: options.search
1423 whereAnd.push(trigramSearch)
1426 attributesInclude.push(createSimilarityAttribute('VideoModel.name', options.search))
1429 // Cannot search on similarity if we don't have a search
1430 if (!options.search) {
1431 attributesInclude.push(
1432 Sequelize.literal('0 as similarity')
1438 include: attributesInclude
1440 offset: options.start,
1441 limit: options.count,
1442 order: getVideoSort(options.sort)
1445 const serverActor = await getServerActor()
1446 const queryOptions = {
1447 followerActorId: serverActor.id,
1448 serverAccountId: serverActor.Account.id,
1449 includeLocalVideos: options.includeLocalVideos,
1451 categoryOneOf: options.categoryOneOf,
1452 licenceOneOf: options.licenceOneOf,
1453 languageOneOf: options.languageOneOf,
1454 tagsOneOf: options.tagsOneOf,
1455 tagsAllOf: options.tagsAllOf,
1457 filter: options.filter,
1461 return VideoModel.getAvailableForApi(query, queryOptions)
1464 static load (id: number | string, t?: Transaction): Bluebird<MVideoThumbnail> {
1465 const where = buildWhereIdOrUUID(id)
1471 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1474 static loadWithBlacklist (id: number | string, t?: Transaction): Bluebird<MVideoThumbnailBlacklist> {
1475 const where = buildWhereIdOrUUID(id)
1481 return VideoModel.scope([
1482 ScopeNames.WITH_THUMBNAILS,
1483 ScopeNames.WITH_BLACKLISTED
1487 static loadWithRights (id: number | string, t?: Transaction): Bluebird<MVideoWithRights> {
1488 const where = buildWhereIdOrUUID(id)
1494 return VideoModel.scope([
1495 ScopeNames.WITH_BLACKLISTED,
1496 ScopeNames.WITH_USER_ID,
1497 ScopeNames.WITH_THUMBNAILS
1501 static loadOnlyId (id: number | string, t?: Transaction): Bluebird<MVideoIdThumbnail> {
1502 const where = buildWhereIdOrUUID(id)
1505 attributes: [ 'id' ],
1510 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1513 static loadWithFiles (id: number | string, t?: Transaction, logging?: boolean): Bluebird<MVideoWithAllFiles> {
1514 const where = buildWhereIdOrUUID(id)
1522 return VideoModel.scope([
1523 ScopeNames.WITH_WEBTORRENT_FILES,
1524 ScopeNames.WITH_STREAMING_PLAYLISTS,
1525 ScopeNames.WITH_THUMBNAILS
1529 static loadByUUID (uuid: string): Bluebird<MVideoThumbnail> {
1536 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1539 static loadByUrl (url: string, transaction?: Transaction): Bluebird<MVideoThumbnail> {
1540 const query: FindOptions = {
1547 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(query)
1550 static loadByUrlAndPopulateAccount (url: string, transaction?: Transaction): Bluebird<MVideoAccountLightBlacklistAllFiles> {
1551 const query: FindOptions = {
1558 return VideoModel.scope([
1559 ScopeNames.WITH_ACCOUNT_DETAILS,
1560 ScopeNames.WITH_WEBTORRENT_FILES,
1561 ScopeNames.WITH_STREAMING_PLAYLISTS,
1562 ScopeNames.WITH_THUMBNAILS,
1563 ScopeNames.WITH_BLACKLISTED
1567 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Transaction, userId?: number): Bluebird<MVideoFullLight> {
1568 const where = buildWhereIdOrUUID(id)
1571 order: [ [ 'Tags', 'name', 'ASC' ] ] as any,
1576 const scopes: (string | ScopeOptions)[] = [
1577 ScopeNames.WITH_TAGS,
1578 ScopeNames.WITH_BLACKLISTED,
1579 ScopeNames.WITH_ACCOUNT_DETAILS,
1580 ScopeNames.WITH_SCHEDULED_UPDATE,
1581 ScopeNames.WITH_WEBTORRENT_FILES,
1582 ScopeNames.WITH_STREAMING_PLAYLISTS,
1583 ScopeNames.WITH_THUMBNAILS
1587 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1595 static loadForGetAPI (parameters: {
1596 id: number | string,
1599 }): Bluebird<MVideoDetails> {
1600 const { id, t, userId } = parameters
1601 const where = buildWhereIdOrUUID(id)
1604 order: [ [ 'Tags', 'name', 'ASC' ] ] as any, // FIXME: sequelize typings
1609 const scopes: (string | ScopeOptions)[] = [
1610 ScopeNames.WITH_TAGS,
1611 ScopeNames.WITH_BLACKLISTED,
1612 ScopeNames.WITH_ACCOUNT_DETAILS,
1613 ScopeNames.WITH_SCHEDULED_UPDATE,
1614 ScopeNames.WITH_THUMBNAILS,
1615 { method: [ ScopeNames.WITH_WEBTORRENT_FILES, true ] },
1616 { method: [ ScopeNames.WITH_STREAMING_PLAYLISTS, true ] }
1620 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1628 static async getStats () {
1629 const totalLocalVideos = await VideoModel.count({
1634 const totalVideos = await VideoModel.count()
1636 let totalLocalVideoViews = await VideoModel.sum('views', {
1641 // Sequelize could return null...
1642 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1646 totalLocalVideoViews,
1651 static incrementViews (id: number, views: number) {
1652 return VideoModel.increment('views', {
1660 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1661 // Instances only share videos
1662 const query = 'SELECT 1 FROM "videoShare" ' +
1663 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1664 'WHERE "actorFollow"."actorId" = $followerActorId AND "videoShare"."videoId" = $videoId ' +
1668 type: QueryTypes.SELECT as QueryTypes.SELECT,
1669 bind: { followerActorId, videoId },
1673 return VideoModel.sequelize.query(query, options)
1674 .then(results => results.length === 1)
1677 static bulkUpdateSupportField (videoChannel: MChannel, t: Transaction) {
1680 channelId: videoChannel.id
1685 return VideoModel.update({ support: videoChannel.support }, options)
1688 static getAllIdsFromChannel (videoChannel: MChannelId): Bluebird<number[]> {
1690 attributes: [ 'id' ],
1692 channelId: videoChannel.id
1696 return VideoModel.findAll(query)
1697 .then(videos => videos.map(v => v.id))
1700 // threshold corresponds to how many video the field should have to be returned
1701 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1702 const serverActor = await getServerActor()
1703 const followerActorId = serverActor.id
1705 const scopeOptions: AvailableForListIDsOptions = {
1706 serverAccountId: serverActor.Account.id,
1708 includeLocalVideos: true,
1709 attributesType: 'none' // Don't break aggregation
1712 const query: FindOptions = {
1713 attributes: [ field ],
1716 having: Sequelize.where(
1717 Sequelize.fn('COUNT', Sequelize.col(field)), { [ Op.gte ]: threshold }
1719 order: [ (this.sequelize as any).random() ]
1722 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST_IDS, scopeOptions ] })
1724 .then(rows => rows.map(r => r[ field ]))
1727 static buildTrendingQuery (trendingDays: number) {
1731 model: VideoViewModel,
1735 [ Op.gte ]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1741 private static async getAvailableForApi (
1742 query: FindOptions & { where?: null }, // Forbid where field in query
1743 options: AvailableForListIDsOptions,
1746 const idsScope: ScopeOptions = {
1748 ScopeNames.AVAILABLE_FOR_LIST_IDS, options
1752 // Remove trending sort on count, because it uses a group by
1753 const countOptions = Object.assign({}, options, { trendingDays: undefined })
1754 const countQuery: CountOptions = Object.assign({}, query, { attributes: undefined, group: undefined })
1755 const countScope: ScopeOptions = {
1757 ScopeNames.AVAILABLE_FOR_LIST_IDS, countOptions
1761 const [ count, rows ] = await Promise.all([
1763 ? VideoModel.scope(countScope).count(countQuery)
1764 : Promise.resolve<number>(undefined),
1766 VideoModel.scope(idsScope)
1767 .findAll(Object.assign({}, query, { raw: true }))
1768 .then(rows => rows.map(r => r.id))
1769 .then(ids => VideoModel.loadCompleteVideosForApi(ids, query, options))
1778 private static loadCompleteVideosForApi (ids: number[], query: FindOptions, options: AvailableForListIDsOptions) {
1779 if (ids.length === 0) return []
1781 const secondQuery: FindOptions = {
1784 attributes: query.attributes,
1785 order: [ // Keep original order
1787 ids.map(id => `"VideoModel".id = ${id} DESC`).join(', ')
1792 const apiScope: (string | ScopeOptions)[] = []
1795 apiScope.push({ method: [ ScopeNames.WITH_USER_HISTORY, options.user.id ] })
1800 ScopeNames.FOR_API, {
1802 withFiles: options.withFiles,
1803 videoPlaylistId: options.videoPlaylistId
1808 return VideoModel.scope(apiScope).findAll(secondQuery)
1811 private static isPrivacyForFederation (privacy: VideoPrivacy) {
1812 const castedPrivacy = parseInt(privacy + '', 10)
1814 return castedPrivacy === VideoPrivacy.PUBLIC || castedPrivacy === VideoPrivacy.UNLISTED
1817 static getCategoryLabel (id: number) {
1818 return VIDEO_CATEGORIES[ id ] || 'Misc'
1821 static getLicenceLabel (id: number) {
1822 return VIDEO_LICENCES[ id ] || 'Unknown'
1825 static getLanguageLabel (id: string) {
1826 return VIDEO_LANGUAGES[ id ] || 'Unknown'
1829 static getPrivacyLabel (id: number) {
1830 return VIDEO_PRIVACIES[ id ] || 'Unknown'
1833 static getStateLabel (id: number) {
1834 return VIDEO_STATES[ id ] || 'Unknown'
1838 return !!this.VideoBlacklist
1842 return (this.VideoChannel.Account.Actor.Server && this.VideoChannel.Account.Actor.Server.isBlocked()) ||
1843 this.VideoChannel.Account.isBlocked()
1846 getQualityFileBy <T extends MVideoWithFile> (this: T, fun: (files: MVideoFile[], it: (file: MVideoFile) => number) => MVideoFile) {
1847 if (Array.isArray(this.VideoFiles) && this.VideoFiles.length !== 0) {
1848 const file = fun(this.VideoFiles, file => file.resolution)
1850 return Object.assign(file, { Video: this })
1853 // No webtorrent files, try with streaming playlist files
1854 if (Array.isArray(this.VideoStreamingPlaylists) && this.VideoStreamingPlaylists.length !== 0) {
1855 const streamingPlaylistWithVideo = Object.assign(this.VideoStreamingPlaylists[0], { Video: this })
1857 const file = fun(streamingPlaylistWithVideo.VideoFiles, file => file.resolution)
1858 return Object.assign(file, { VideoStreamingPlaylist: streamingPlaylistWithVideo })
1864 getMaxQualityFile <T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1865 return this.getQualityFileBy(maxBy)
1868 getMinQualityFile <T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1869 return this.getQualityFileBy(minBy)
1872 getWebTorrentFile <T extends MVideoWithFile> (this: T, resolution: number): MVideoFileVideo {
1873 if (Array.isArray(this.VideoFiles) === false) return undefined
1875 const file = this.VideoFiles.find(f => f.resolution === resolution)
1876 if (!file) return undefined
1878 return Object.assign(file, { Video: this })
1881 async addAndSaveThumbnail (thumbnail: MThumbnail, transaction: Transaction) {
1882 thumbnail.videoId = this.id
1884 const savedThumbnail = await thumbnail.save({ transaction })
1886 if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = []
1888 // Already have this thumbnail, skip
1889 if (this.Thumbnails.find(t => t.id === savedThumbnail.id)) return
1891 this.Thumbnails.push(savedThumbnail)
1894 generateThumbnailName () {
1895 return this.uuid + '.jpg'
1899 if (Array.isArray(this.Thumbnails) === false) return undefined
1901 return this.Thumbnails.find(t => t.type === ThumbnailType.MINIATURE)
1904 generatePreviewName () {
1905 return this.uuid + '.jpg'
1909 if (Array.isArray(this.Thumbnails) === false) return undefined
1911 return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW)
1915 return this.remote === false
1918 getWatchStaticPath () {
1919 return '/videos/watch/' + this.uuid
1922 getEmbedStaticPath () {
1923 return '/videos/embed/' + this.uuid
1926 getMiniatureStaticPath () {
1927 const thumbnail = this.getMiniature()
1928 if (!thumbnail) return null
1930 return join(STATIC_PATHS.THUMBNAILS, thumbnail.filename)
1933 getPreviewStaticPath () {
1934 const preview = this.getPreview()
1935 if (!preview) return null
1937 // We use a local cache, so specify our cache endpoint instead of potential remote URL
1938 return join(LAZY_STATIC_PATHS.PREVIEWS, preview.filename)
1941 toFormattedJSON (this: MVideoFormattable, options?: VideoFormattingJSONOptions): Video {
1942 return videoModelToFormattedJSON(this, options)
1945 toFormattedDetailsJSON (this: MVideoFormattableDetails): VideoDetails {
1946 return videoModelToFormattedDetailsJSON(this)
1949 getFormattedVideoFilesJSON (): VideoFile[] {
1950 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1951 return videoFilesModelToFormattedJSON(this, baseUrlHttp, baseUrlWs, this.VideoFiles)
1954 toActivityPubObject (this: MVideoAP): VideoTorrentObject {
1955 return videoModelToActivityPubObject(this)
1958 getTruncatedDescription () {
1959 if (!this.description) return null
1961 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1962 return peertubeTruncate(this.description, { length: maxLength })
1965 getMaxQualityResolution () {
1966 const file = this.getMaxQualityFile()
1967 const videoOrPlaylist = file.getVideoOrStreamingPlaylist()
1968 const originalFilePath = getVideoFilePath(videoOrPlaylist, file)
1970 return getVideoFileResolution(originalFilePath)
1973 getDescriptionAPIPath () {
1974 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1977 getHLSPlaylist (): MStreamingPlaylistFilesVideo {
1978 if (!this.VideoStreamingPlaylists) return undefined
1980 const playlist = this.VideoStreamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
1981 playlist.Video = this
1986 setHLSPlaylist (playlist: MStreamingPlaylist) {
1987 const toAdd = [ playlist ] as [ VideoStreamingPlaylistModel ]
1989 if (Array.isArray(this.VideoStreamingPlaylists) === false || this.VideoStreamingPlaylists.length === 0) {
1990 this.VideoStreamingPlaylists = toAdd
1994 this.VideoStreamingPlaylists = this.VideoStreamingPlaylists
1995 .filter(s => s.type !== VideoStreamingPlaylistType.HLS)
1999 removeFile (videoFile: MVideoFile, isRedundancy = false) {
2000 const filePath = getVideoFilePath(this, videoFile, isRedundancy)
2001 return remove(filePath)
2002 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
2005 removeTorrent (videoFile: MVideoFile) {
2006 const torrentPath = getTorrentFilePath(this, videoFile)
2007 return remove(torrentPath)
2008 .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err }))
2011 async removeStreamingPlaylistFiles (streamingPlaylist: MStreamingPlaylist, isRedundancy = false) {
2012 const directoryPath = getHLSDirectory(this, isRedundancy)
2014 await remove(directoryPath)
2016 if (isRedundancy !== true) {
2017 let streamingPlaylistWithFiles = streamingPlaylist as MStreamingPlaylistFilesVideo
2018 streamingPlaylistWithFiles.Video = this
2020 if (!Array.isArray(streamingPlaylistWithFiles.VideoFiles)) {
2021 streamingPlaylistWithFiles.VideoFiles = await streamingPlaylistWithFiles.$get('VideoFiles')
2024 // Remove physical files and torrents
2026 streamingPlaylistWithFiles.VideoFiles.map(file => streamingPlaylistWithFiles.removeTorrent(file))
2032 if (this.isOwned()) return false
2034 return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)
2037 hasPrivacyForFederation () {
2038 return VideoModel.isPrivacyForFederation(this.privacy)
2041 isNewVideo (newPrivacy: VideoPrivacy) {
2042 return this.hasPrivacyForFederation() === false && VideoModel.isPrivacyForFederation(newPrivacy) === true
2046 this.changed('updatedAt', true)
2052 return this.privacy === VideoPrivacy.PRIVATE || this.privacy === VideoPrivacy.INTERNAL || !!this.VideoBlacklist
2055 setPrivacy (newPrivacy: VideoPrivacy) {
2056 if (this.privacy === VideoPrivacy.PRIVATE && newPrivacy !== VideoPrivacy.PRIVATE) {
2057 this.publishedAt = new Date()
2060 this.privacy = newPrivacy
2064 return this.privacy === VideoPrivacy.PRIVATE ||
2065 this.privacy === VideoPrivacy.UNLISTED ||
2066 this.privacy === VideoPrivacy.INTERNAL
2069 async publishIfNeededAndSave (t: Transaction) {
2070 if (this.state !== VideoState.PUBLISHED) {
2071 this.state = VideoState.PUBLISHED
2072 this.publishedAt = new Date()
2073 await this.save({ transaction: t })
2082 if (this.isOwned()) {
2084 baseUrlHttp: WEBSERVER.URL,
2085 baseUrlWs: WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT
2090 baseUrlHttp: REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host,
2091 baseUrlWs: REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
2095 getTrackerUrls (baseUrlHttp: string, baseUrlWs: string) {
2096 return [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
2099 getTorrentUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2100 return baseUrlHttp + STATIC_PATHS.TORRENTS + getTorrentFileName(this, videoFile)
2103 getTorrentDownloadUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2104 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + getTorrentFileName(this, videoFile)
2107 getVideoFileUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2108 return baseUrlHttp + STATIC_PATHS.WEBSEED + getVideoFilename(this, videoFile)
2111 getVideoRedundancyUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2112 return baseUrlHttp + STATIC_PATHS.REDUNDANCY + getVideoFilename(this, videoFile)
2115 getVideoFileDownloadUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2116 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + getVideoFilename(this, videoFile)
2119 getBandwidthBits (videoFile: MVideoFile) {
2120 return Math.ceil((videoFile.size * 8) / this.duration)