1 import * as Bluebird from 'bluebird'
2 import { maxBy, minBy } from 'lodash'
3 import { join } from 'path'
4 import { CountOptions, FindOptions, IncludeOptions, Op, QueryTypes, ScopeOptions, Sequelize, Transaction, WhereOptions } from 'sequelize'
25 } from 'sequelize-typescript'
26 import { UserRight, VideoPrivacy, VideoState } from '../../../shared'
27 import { VideoTorrentObject } from '../../../shared/models/activitypub/objects'
28 import { Video, VideoDetails } from '../../../shared/models/videos'
29 import { VideoFilter } from '../../../shared/models/videos/video-query.type'
30 import { peertubeTruncate } from '../../helpers/core-utils'
31 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
32 import { isBooleanValid } from '../../helpers/custom-validators/misc'
35 isVideoDescriptionValid,
43 } from '../../helpers/custom-validators/videos'
44 import { getVideoFileResolution } from '../../helpers/ffmpeg-utils'
45 import { logger } from '../../helpers/logger'
46 import { getServerActor } from '../../helpers/utils'
53 STATIC_DOWNLOAD_PATHS,
61 } from '../../initializers/constants'
62 import { sendDeleteVideo } from '../../lib/activitypub/send'
63 import { AccountModel } from '../account/account'
64 import { AccountVideoRateModel } from '../account/account-video-rate'
65 import { ActorModel } from '../activitypub/actor'
66 import { AvatarModel } from '../avatar/avatar'
67 import { ServerModel } from '../server/server'
69 buildBlockedAccountSQL,
70 buildTrigramSearchIndex,
73 createSimilarityAttribute,
78 import { TagModel } from './tag'
79 import { VideoAbuseModel } from './video-abuse'
80 import { ScopeNames as VideoChannelScopeNames, SummaryOptions, VideoChannelModel } from './video-channel'
81 import { VideoCommentModel } from './video-comment'
82 import { VideoFileModel } from './video-file'
83 import { VideoShareModel } from './video-share'
84 import { VideoTagModel } from './video-tag'
85 import { ScheduleVideoUpdateModel } from './schedule-video-update'
86 import { VideoCaptionModel } from './video-caption'
87 import { VideoBlacklistModel } from './video-blacklist'
88 import { remove } from 'fs-extra'
89 import { VideoViewModel } from './video-views'
90 import { VideoRedundancyModel } from '../redundancy/video-redundancy'
92 videoFilesModelToFormattedJSON,
93 VideoFormattingJSONOptions,
94 videoModelToActivityPubObject,
95 videoModelToFormattedDetailsJSON,
96 videoModelToFormattedJSON
97 } from './video-format-utils'
98 import { UserVideoHistoryModel } from '../account/user-video-history'
99 import { VideoImportModel } from './video-import'
100 import { VideoStreamingPlaylistModel } from './video-streaming-playlist'
101 import { VideoPlaylistElementModel } from './video-playlist-element'
102 import { CONFIG } from '../../initializers/config'
103 import { ThumbnailModel } from './thumbnail'
104 import { ThumbnailType } from '../../../shared/models/videos/thumbnail.type'
105 import { VideoStreamingPlaylistType } from '../../../shared/models/videos/video-streaming-playlist.type'
108 MChannelAccountDefault,
111 MStreamingPlaylistFilesVideo,
115 MVideoAccountLightBlacklistAllFiles,
120 MVideoFormattableDetails,
125 MVideoThumbnailBlacklist,
129 } from '../../typings/models'
130 import { MVideoFile, MVideoFileStreamingPlaylistVideo } from '../../typings/models/video/video-file'
131 import { MThumbnail } from '../../typings/models/video/thumbnail'
132 import { VideoFile } from '@shared/models/videos/video-file.model'
133 import { getHLSDirectory, getTorrentFileName, getTorrentFilePath, getVideoFilename, getVideoFilePath } from '@server/lib/video-paths'
134 import validator from 'validator'
136 export enum ScopeNames {
137 AVAILABLE_FOR_LIST_IDS = 'AVAILABLE_FOR_LIST_IDS',
139 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
140 WITH_TAGS = 'WITH_TAGS',
141 WITH_WEBTORRENT_FILES = 'WITH_WEBTORRENT_FILES',
142 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
143 WITH_BLACKLISTED = 'WITH_BLACKLISTED',
144 WITH_USER_HISTORY = 'WITH_USER_HISTORY',
145 WITH_STREAMING_PLAYLISTS = 'WITH_STREAMING_PLAYLISTS',
146 WITH_USER_ID = 'WITH_USER_ID',
147 WITH_THUMBNAILS = 'WITH_THUMBNAILS'
150 export type ForAPIOptions = {
153 videoPlaylistId?: number
157 withAccountBlockerIds?: number[]
160 export type AvailableForListIDsOptions = {
161 serverAccountId: number
162 followerActorId: number
163 includeLocalVideos: boolean
165 attributesType?: 'none' | 'id' | 'all'
168 categoryOneOf?: number[]
170 licenceOneOf?: number[]
171 languageOneOf?: string[]
178 videoChannelId?: number
180 videoPlaylistId?: number
182 trendingDays?: number
183 user?: MUserAccountId
184 historyOfUser?: MUserId
186 baseWhere?: WhereOptions[]
190 [ ScopeNames.FOR_API ]: (options: ForAPIOptions) => {
191 const query: FindOptions = {
194 model: VideoChannelModel.scope({
196 VideoChannelScopeNames.SUMMARY, {
198 withAccountBlockerIds: options.withAccountBlockerIds
205 attributes: [ 'type', 'filename' ],
206 model: ThumbnailModel,
215 [ Op.in ]: options.ids
220 if (options.withFiles === true) {
222 model: VideoFileModel.unscoped(),
227 if (options.videoPlaylistId) {
229 model: VideoPlaylistElementModel.unscoped(),
232 videoPlaylistId: options.videoPlaylistId
239 [ ScopeNames.AVAILABLE_FOR_LIST_IDS ]: (options: AvailableForListIDsOptions) => {
240 const whereAnd = options.baseWhere ? [].concat(options.baseWhere) : []
242 const query: FindOptions = {
247 const attributesType = options.attributesType || 'id'
249 if (attributesType === 'id') query.attributes = [ 'id' ]
250 else if (attributesType === 'none') query.attributes = [ ]
254 [ Op.notIn ]: Sequelize.literal(
255 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
260 if (options.serverAccountId) {
263 [ Op.notIn ]: Sequelize.literal(
265 'SELECT id FROM "videoChannel" WHERE "accountId" IN (' +
266 buildBlockedAccountSQL(options.serverAccountId, options.user ? options.user.Account.id : undefined) +
274 // Only list public/published videos
275 if (!options.filter || options.filter !== 'all-local') {
277 const publishWhere = {
278 // Always list published videos, or videos that are being transcoded but on which we don't want to wait for transcoding
281 state: VideoState.PUBLISHED
285 state: VideoState.TO_TRANSCODE,
286 waitTranscoding: false
291 whereAnd.push(publishWhere)
293 // List internal videos if the user is logged in
295 const privacyWhere = {
298 privacy: VideoPrivacy.INTERNAL
301 privacy: VideoPrivacy.PUBLIC
306 whereAnd.push(privacyWhere)
307 } else { // Or only public videos
308 const privacyWhere = { privacy: VideoPrivacy.PUBLIC }
309 whereAnd.push(privacyWhere)
313 if (options.videoPlaylistId) {
316 model: VideoPlaylistElementModel.unscoped(),
319 videoPlaylistId: options.videoPlaylistId
323 query.subQuery = false
326 if (options.filter && (options.filter === 'local' || options.filter === 'all-local')) {
332 if (options.accountId || options.videoChannelId) {
333 const videoChannelInclude: IncludeOptions = {
335 model: VideoChannelModel.unscoped(),
339 if (options.videoChannelId) {
340 videoChannelInclude.where = {
341 id: options.videoChannelId
345 if (options.accountId) {
346 const accountInclude: IncludeOptions = {
348 model: AccountModel.unscoped(),
352 accountInclude.where = { id: options.accountId }
353 videoChannelInclude.include = [ accountInclude ]
356 query.include.push(videoChannelInclude)
359 if (options.followerActorId) {
360 let localVideosReq: WhereOptions = {}
361 if (options.includeLocalVideos === true) {
362 localVideosReq = { remote: false }
365 // Force actorId to be a number to avoid SQL injections
366 const actorIdNumber = parseInt(options.followerActorId.toString(), 10)
371 [ Op.in ]: Sequelize.literal(
373 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
374 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
375 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
382 [ Op.in ]: Sequelize.literal(
384 'SELECT "video"."id" AS "id" FROM "video" ' +
385 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
386 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
387 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
388 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
389 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
399 if (options.withFiles === true) {
402 [ Op.in ]: Sequelize.literal(
403 '(SELECT "videoId" FROM "videoFile")'
409 // FIXME: issues with sequelize count when making a join on n:m relation, so we just make a IN()
410 if (options.tagsAllOf || options.tagsOneOf) {
411 if (options.tagsOneOf) {
412 const tagsOneOfLower = options.tagsOneOf.map(t => t.toLowerCase())
416 [ Op.in ]: Sequelize.literal(
418 'SELECT "videoId" FROM "videoTag" ' +
419 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
420 'WHERE lower("tag"."name") IN (' + createSafeIn(VideoModel, tagsOneOfLower) + ')' +
427 if (options.tagsAllOf) {
428 const tagsAllOfLower = options.tagsAllOf.map(t => t.toLowerCase())
432 [ Op.in ]: Sequelize.literal(
434 'SELECT "videoId" FROM "videoTag" ' +
435 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
436 'WHERE lower("tag"."name") IN (' + createSafeIn(VideoModel, tagsAllOfLower) + ')' +
437 'GROUP BY "videoTag"."videoId" HAVING COUNT(*) = ' + tagsAllOfLower.length +
445 if (options.nsfw === true || options.nsfw === false) {
446 whereAnd.push({ nsfw: options.nsfw })
449 if (options.categoryOneOf) {
452 [ Op.or ]: options.categoryOneOf
457 if (options.licenceOneOf) {
460 [ Op.or ]: options.licenceOneOf
465 if (options.languageOneOf) {
466 let videoLanguages = options.languageOneOf
467 if (options.languageOneOf.find(l => l === '_unknown')) {
468 videoLanguages = videoLanguages.concat([ null ])
475 [ Op.or ]: videoLanguages
480 [ Op.in ]: Sequelize.literal(
482 'SELECT "videoId" FROM "videoCaption" ' +
483 'WHERE "language" IN (' + createSafeIn(VideoModel, options.languageOneOf) + ') ' +
492 if (options.trendingDays) {
493 query.include.push(VideoModel.buildTrendingQuery(options.trendingDays))
495 query.subQuery = false
498 if (options.historyOfUser) {
500 model: UserVideoHistoryModel,
503 userId: options.historyOfUser.id
507 // Even if the relation is n:m, we know that a user only have 0..1 video history
508 // So we won't have multiple rows for the same video
509 // Without this, we would not be able to sort on "updatedAt" column of UserVideoHistoryModel
510 query.subQuery = false
519 [ ScopeNames.WITH_THUMBNAILS ]: {
522 model: ThumbnailModel,
527 [ ScopeNames.WITH_USER_ID ]: {
530 attributes: [ 'accountId' ],
531 model: VideoChannelModel.unscoped(),
535 attributes: [ 'userId' ],
536 model: AccountModel.unscoped(),
543 [ ScopeNames.WITH_ACCOUNT_DETAILS ]: {
546 model: VideoChannelModel.unscoped(),
551 exclude: [ 'privateKey', 'publicKey' ]
553 model: ActorModel.unscoped(),
557 attributes: [ 'host' ],
558 model: ServerModel.unscoped(),
562 model: AvatarModel.unscoped(),
568 model: AccountModel.unscoped(),
572 model: ActorModel.unscoped(),
574 exclude: [ 'privateKey', 'publicKey' ]
579 attributes: [ 'host' ],
580 model: ServerModel.unscoped(),
584 model: AvatarModel.unscoped(),
595 [ ScopeNames.WITH_TAGS ]: {
596 include: [ TagModel ]
598 [ ScopeNames.WITH_BLACKLISTED ]: {
601 attributes: [ 'id', 'reason', 'unfederated' ],
602 model: VideoBlacklistModel,
607 [ ScopeNames.WITH_WEBTORRENT_FILES ]: (withRedundancies = false) => {
608 let subInclude: any[] = []
610 if (withRedundancies === true) {
613 attributes: [ 'fileUrl' ],
614 model: VideoRedundancyModel.unscoped(),
623 model: VideoFileModel.unscoped(),
624 separate: true, // We may have multiple files, having multiple redundancies so let's separate this join
631 [ ScopeNames.WITH_STREAMING_PLAYLISTS ]: (withRedundancies = false) => {
632 const subInclude: IncludeOptions[] = [
634 model: VideoFileModel.unscoped(),
639 if (withRedundancies === true) {
641 attributes: [ 'fileUrl' ],
642 model: VideoRedundancyModel.unscoped(),
650 model: VideoStreamingPlaylistModel.unscoped(),
651 separate: true, // We may have multiple streaming playlists, having multiple redundancies so let's separate this join
658 [ ScopeNames.WITH_SCHEDULED_UPDATE ]: {
661 model: ScheduleVideoUpdateModel.unscoped(),
666 [ ScopeNames.WITH_USER_HISTORY ]: (userId: number) => {
670 attributes: [ 'currentTime' ],
671 model: UserVideoHistoryModel.unscoped(),
684 buildTrigramSearchIndex('video_name_trigram', 'name'),
686 { fields: [ 'createdAt' ] },
689 { name: 'publishedAt', order: 'DESC' },
690 { name: 'id', order: 'ASC' }
693 { fields: [ 'duration' ] },
694 { fields: [ 'views' ] },
695 { fields: [ 'channelId' ] },
697 fields: [ 'originallyPublishedAt' ],
699 originallyPublishedAt: {
705 fields: [ 'category' ], // We don't care videos with an unknown category
713 fields: [ 'licence' ], // We don't care videos with an unknown licence
721 fields: [ 'language' ], // We don't care videos with an unknown language
729 fields: [ 'nsfw' ], // Most of the videos are not NSFW
735 fields: [ 'remote' ], // Only index local videos
750 export class VideoModel extends Model<VideoModel> {
753 @Default(DataType.UUIDV4)
755 @Column(DataType.UUID)
759 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
765 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category', true))
771 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence', true))
777 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language', true))
778 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
782 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
787 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
793 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description', true))
794 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
799 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support', true))
800 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
804 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
834 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
835 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
840 commentsEnabled: boolean
844 downloadEnabled: boolean
848 waitTranscoding: boolean
852 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
863 @Default(DataType.NOW)
870 originallyPublishedAt: Date
872 @ForeignKey(() => VideoChannelModel)
876 @BelongsTo(() => VideoChannelModel, {
882 VideoChannel: VideoChannelModel
884 @BelongsToMany(() => TagModel, {
885 foreignKey: 'videoId',
886 through: () => VideoTagModel,
891 @HasMany(() => ThumbnailModel, {
899 Thumbnails: ThumbnailModel[]
901 @HasMany(() => VideoPlaylistElementModel, {
908 VideoPlaylistElements: VideoPlaylistElementModel[]
910 @HasMany(() => VideoAbuseModel, {
917 VideoAbuses: VideoAbuseModel[]
919 @HasMany(() => VideoFileModel, {
927 VideoFiles: VideoFileModel[]
929 @HasMany(() => VideoStreamingPlaylistModel, {
937 VideoStreamingPlaylists: VideoStreamingPlaylistModel[]
939 @HasMany(() => VideoShareModel, {
946 VideoShares: VideoShareModel[]
948 @HasMany(() => AccountVideoRateModel, {
955 AccountVideoRates: AccountVideoRateModel[]
957 @HasMany(() => VideoCommentModel, {
965 VideoComments: VideoCommentModel[]
967 @HasMany(() => VideoViewModel, {
974 VideoViews: VideoViewModel[]
976 @HasMany(() => UserVideoHistoryModel, {
983 UserVideoHistories: UserVideoHistoryModel[]
985 @HasOne(() => ScheduleVideoUpdateModel, {
992 ScheduleVideoUpdate: ScheduleVideoUpdateModel
994 @HasOne(() => VideoBlacklistModel, {
1001 VideoBlacklist: VideoBlacklistModel
1003 @HasOne(() => VideoImportModel, {
1008 onDelete: 'set null'
1010 VideoImport: VideoImportModel
1012 @HasMany(() => VideoCaptionModel, {
1017 onDelete: 'cascade',
1019 [ 'separate' as any ]: true
1021 VideoCaptions: VideoCaptionModel[]
1024 static async sendDelete (instance: MVideoAccountLight, options) {
1025 if (instance.isOwned()) {
1026 if (!instance.VideoChannel) {
1027 instance.VideoChannel = await instance.$get('VideoChannel', {
1032 transaction: options.transaction
1033 }) as MChannelAccountDefault
1036 return sendDeleteVideo(instance, options.transaction)
1043 static async removeFiles (instance: VideoModel) {
1044 const tasks: Promise<any>[] = []
1046 logger.info('Removing files of video %s.', instance.url)
1048 if (instance.isOwned()) {
1049 if (!Array.isArray(instance.VideoFiles)) {
1050 instance.VideoFiles = await instance.$get('VideoFiles')
1053 // Remove physical files and torrents
1054 instance.VideoFiles.forEach(file => {
1055 tasks.push(instance.removeFile(file))
1056 tasks.push(instance.removeTorrent(file))
1059 // Remove playlists file
1060 if (!Array.isArray(instance.VideoStreamingPlaylists)) {
1061 instance.VideoStreamingPlaylists = await instance.$get('VideoStreamingPlaylists')
1064 for (const p of instance.VideoStreamingPlaylists) {
1065 tasks.push(instance.removeStreamingPlaylistFiles(p))
1069 // Do not wait video deletion because we could be in a transaction
1072 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
1078 static listLocal (): Bluebird<MVideoWithAllFiles[]> {
1085 return VideoModel.scope([
1086 ScopeNames.WITH_WEBTORRENT_FILES,
1087 ScopeNames.WITH_STREAMING_PLAYLISTS,
1088 ScopeNames.WITH_THUMBNAILS
1092 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
1093 function getRawQuery (select: string) {
1094 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
1095 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
1096 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
1097 'WHERE "Account"."actorId" = ' + actorId
1098 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
1099 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
1100 'WHERE "VideoShare"."actorId" = ' + actorId
1102 return `(${queryVideo}) UNION (${queryVideoShare})`
1105 const rawQuery = getRawQuery('"Video"."id"')
1106 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
1112 order: getVideoSort('createdAt', [ 'Tags', 'name', 'ASC' ] as any), // FIXME: sequelize typings
1115 [ Op.in ]: Sequelize.literal('(' + rawQuery + ')')
1118 { privacy: VideoPrivacy.PUBLIC },
1119 { privacy: VideoPrivacy.UNLISTED }
1124 attributes: [ 'language' ],
1125 model: VideoCaptionModel.unscoped(),
1129 attributes: [ 'id', 'url' ],
1130 model: VideoShareModel.unscoped(),
1132 // We only want videos shared by this actor
1147 attributes: [ 'id', 'url' ],
1148 model: ActorModel.unscoped()
1153 model: VideoChannelModel.unscoped(),
1157 attributes: [ 'name' ],
1158 model: AccountModel.unscoped(),
1162 attributes: [ 'id', 'url', 'followersUrl' ],
1163 model: ActorModel.unscoped(),
1169 attributes: [ 'id', 'url', 'followersUrl' ],
1170 model: ActorModel.unscoped(),
1180 return Bluebird.all([
1181 VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findAll(query),
1182 VideoModel.sequelize.query<{ total: string }>(rawCountQuery, { type: QueryTypes.SELECT })
1183 ]).then(([ rows, totals ]) => {
1184 // totals: totalVideos + totalVideoShares
1186 let totalVideoShares = 0
1187 if (totals[ 0 ]) totalVideos = parseInt(totals[ 0 ].total, 10)
1188 if (totals[ 1 ]) totalVideoShares = parseInt(totals[ 1 ].total, 10)
1190 const total = totalVideos + totalVideoShares
1198 static listUserVideosForApi (
1205 function buildBaseQuery (): FindOptions {
1209 order: getVideoSort(sort),
1212 model: VideoChannelModel,
1216 model: AccountModel,
1228 baseQuery = Object.assign(baseQuery, {
1231 [ Op.iLike ]: '%' + search + '%'
1240 const countQuery = buildBaseQuery()
1241 const findQuery = buildBaseQuery()
1243 const findScopes: (string | ScopeOptions)[] = [
1244 ScopeNames.WITH_SCHEDULED_UPDATE,
1245 ScopeNames.WITH_BLACKLISTED,
1246 ScopeNames.WITH_THUMBNAILS
1249 return Promise.all([
1250 VideoModel.count(countQuery),
1251 VideoModel.scope(findScopes).findAll<MVideoForUser>(findQuery)
1252 ]).then(([ count, rows ]) => {
1260 static async listForApi (options: {
1265 includeLocalVideos: boolean,
1267 categoryOneOf?: number[],
1268 licenceOneOf?: number[],
1269 languageOneOf?: string[],
1270 tagsOneOf?: string[],
1271 tagsAllOf?: string[],
1272 filter?: VideoFilter,
1274 videoChannelId?: number,
1275 followerActorId?: number
1276 videoPlaylistId?: number,
1277 trendingDays?: number,
1278 user?: MUserAccountId,
1279 historyOfUser?: MUserId,
1280 countVideos?: boolean
1282 if (options.filter && options.filter === 'all-local' && !options.user.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1283 throw new Error('Try to filter all-local but no user has not the see all videos right')
1286 const query: FindOptions & { where?: null } = {
1287 offset: options.start,
1288 limit: options.count,
1289 order: getVideoSort(options.sort)
1292 let trendingDays: number
1293 if (options.sort.endsWith('trending')) {
1294 trendingDays = CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1296 query.group = 'VideoModel.id'
1299 const serverActor = await getServerActor()
1301 // followerActorId === null has a meaning, so just check undefined
1302 const followerActorId = options.followerActorId !== undefined ? options.followerActorId : serverActor.id
1304 const queryOptions = {
1306 serverAccountId: serverActor.Account.id,
1308 categoryOneOf: options.categoryOneOf,
1309 licenceOneOf: options.licenceOneOf,
1310 languageOneOf: options.languageOneOf,
1311 tagsOneOf: options.tagsOneOf,
1312 tagsAllOf: options.tagsAllOf,
1313 filter: options.filter,
1314 withFiles: options.withFiles,
1315 accountId: options.accountId,
1316 videoChannelId: options.videoChannelId,
1317 videoPlaylistId: options.videoPlaylistId,
1318 includeLocalVideos: options.includeLocalVideos,
1320 historyOfUser: options.historyOfUser,
1324 return VideoModel.getAvailableForApi(query, queryOptions, options.countVideos)
1327 static async searchAndPopulateAccountAndServer (options: {
1328 includeLocalVideos: boolean
1333 startDate?: string // ISO 8601
1334 endDate?: string // ISO 8601
1335 originallyPublishedStartDate?: string
1336 originallyPublishedEndDate?: string
1338 categoryOneOf?: number[]
1339 licenceOneOf?: number[]
1340 languageOneOf?: string[]
1341 tagsOneOf?: string[]
1342 tagsAllOf?: string[]
1343 durationMin?: number // seconds
1344 durationMax?: number // seconds
1345 user?: MUserAccountId,
1346 filter?: VideoFilter
1350 if (options.startDate || options.endDate) {
1351 const publishedAtRange = {}
1353 if (options.startDate) publishedAtRange[ Op.gte ] = options.startDate
1354 if (options.endDate) publishedAtRange[ Op.lte ] = options.endDate
1356 whereAnd.push({ publishedAt: publishedAtRange })
1359 if (options.originallyPublishedStartDate || options.originallyPublishedEndDate) {
1360 const originallyPublishedAtRange = {}
1362 if (options.originallyPublishedStartDate) originallyPublishedAtRange[ Op.gte ] = options.originallyPublishedStartDate
1363 if (options.originallyPublishedEndDate) originallyPublishedAtRange[ Op.lte ] = options.originallyPublishedEndDate
1365 whereAnd.push({ originallyPublishedAt: originallyPublishedAtRange })
1368 if (options.durationMin || options.durationMax) {
1369 const durationRange = {}
1371 if (options.durationMin) durationRange[ Op.gte ] = options.durationMin
1372 if (options.durationMax) durationRange[ Op.lte ] = options.durationMax
1374 whereAnd.push({ duration: durationRange })
1377 const attributesInclude = []
1378 const escapedSearch = VideoModel.sequelize.escape(options.search)
1379 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
1380 if (options.search) {
1381 const trigramSearch = {
1383 [ Op.in ]: Sequelize.literal(
1385 'SELECT "video"."id" FROM "video" ' +
1387 'lower(immutable_unaccent("video"."name")) % lower(immutable_unaccent(' + escapedSearch + ')) OR ' +
1388 'lower(immutable_unaccent("video"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))' +
1390 'SELECT "video"."id" FROM "video" LEFT JOIN "videoTag" ON "videoTag"."videoId" = "video"."id" ' +
1391 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
1392 'WHERE lower("tag"."name") = lower(' + escapedSearch + ')' +
1398 if (validator.isUUID(options.search)) {
1403 uuid: options.search
1408 whereAnd.push(trigramSearch)
1411 attributesInclude.push(createSimilarityAttribute('VideoModel.name', options.search))
1414 // Cannot search on similarity if we don't have a search
1415 if (!options.search) {
1416 attributesInclude.push(
1417 Sequelize.literal('0 as similarity')
1423 include: attributesInclude
1425 offset: options.start,
1426 limit: options.count,
1427 order: getVideoSort(options.sort)
1430 const serverActor = await getServerActor()
1431 const queryOptions = {
1432 followerActorId: serverActor.id,
1433 serverAccountId: serverActor.Account.id,
1434 includeLocalVideos: options.includeLocalVideos,
1436 categoryOneOf: options.categoryOneOf,
1437 licenceOneOf: options.licenceOneOf,
1438 languageOneOf: options.languageOneOf,
1439 tagsOneOf: options.tagsOneOf,
1440 tagsAllOf: options.tagsAllOf,
1442 filter: options.filter,
1446 return VideoModel.getAvailableForApi(query, queryOptions)
1449 static load (id: number | string, t?: Transaction): Bluebird<MVideoThumbnail> {
1450 const where = buildWhereIdOrUUID(id)
1456 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1459 static loadWithBlacklist (id: number | string, t?: Transaction): Bluebird<MVideoThumbnailBlacklist> {
1460 const where = buildWhereIdOrUUID(id)
1466 return VideoModel.scope([
1467 ScopeNames.WITH_THUMBNAILS,
1468 ScopeNames.WITH_BLACKLISTED
1472 static loadWithRights (id: number | string, t?: Transaction): Bluebird<MVideoWithRights> {
1473 const where = buildWhereIdOrUUID(id)
1479 return VideoModel.scope([
1480 ScopeNames.WITH_BLACKLISTED,
1481 ScopeNames.WITH_USER_ID,
1482 ScopeNames.WITH_THUMBNAILS
1486 static loadOnlyId (id: number | string, t?: Transaction): Bluebird<MVideoIdThumbnail> {
1487 const where = buildWhereIdOrUUID(id)
1490 attributes: [ 'id' ],
1495 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1498 static loadWithFiles (id: number | string, t?: Transaction, logging?: boolean): Bluebird<MVideoWithAllFiles> {
1499 const where = buildWhereIdOrUUID(id)
1507 return VideoModel.scope([
1508 ScopeNames.WITH_WEBTORRENT_FILES,
1509 ScopeNames.WITH_STREAMING_PLAYLISTS,
1510 ScopeNames.WITH_THUMBNAILS
1514 static loadByUUID (uuid: string): Bluebird<MVideoThumbnail> {
1521 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1524 static loadByUrl (url: string, transaction?: Transaction): Bluebird<MVideoThumbnail> {
1525 const query: FindOptions = {
1532 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(query)
1535 static loadByUrlAndPopulateAccount (url: string, transaction?: Transaction): Bluebird<MVideoAccountLightBlacklistAllFiles> {
1536 const query: FindOptions = {
1543 return VideoModel.scope([
1544 ScopeNames.WITH_ACCOUNT_DETAILS,
1545 ScopeNames.WITH_WEBTORRENT_FILES,
1546 ScopeNames.WITH_STREAMING_PLAYLISTS,
1547 ScopeNames.WITH_THUMBNAILS,
1548 ScopeNames.WITH_BLACKLISTED
1552 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Transaction, userId?: number): Bluebird<MVideoFullLight> {
1553 const where = buildWhereIdOrUUID(id)
1556 order: [ [ 'Tags', 'name', 'ASC' ] ] as any,
1561 const scopes: (string | ScopeOptions)[] = [
1562 ScopeNames.WITH_TAGS,
1563 ScopeNames.WITH_BLACKLISTED,
1564 ScopeNames.WITH_ACCOUNT_DETAILS,
1565 ScopeNames.WITH_SCHEDULED_UPDATE,
1566 ScopeNames.WITH_WEBTORRENT_FILES,
1567 ScopeNames.WITH_STREAMING_PLAYLISTS,
1568 ScopeNames.WITH_THUMBNAILS
1572 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1580 static loadForGetAPI (parameters: {
1581 id: number | string,
1584 }): Bluebird<MVideoDetails> {
1585 const { id, t, userId } = parameters
1586 const where = buildWhereIdOrUUID(id)
1589 order: [ [ 'Tags', 'name', 'ASC' ] ] as any, // FIXME: sequelize typings
1594 const scopes: (string | ScopeOptions)[] = [
1595 ScopeNames.WITH_TAGS,
1596 ScopeNames.WITH_BLACKLISTED,
1597 ScopeNames.WITH_ACCOUNT_DETAILS,
1598 ScopeNames.WITH_SCHEDULED_UPDATE,
1599 ScopeNames.WITH_THUMBNAILS,
1600 { method: [ ScopeNames.WITH_WEBTORRENT_FILES, true ] },
1601 { method: [ ScopeNames.WITH_STREAMING_PLAYLISTS, true ] }
1605 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1613 static async getStats () {
1614 const totalLocalVideos = await VideoModel.count({
1619 const totalVideos = await VideoModel.count()
1621 let totalLocalVideoViews = await VideoModel.sum('views', {
1626 // Sequelize could return null...
1627 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1631 totalLocalVideoViews,
1636 static incrementViews (id: number, views: number) {
1637 return VideoModel.increment('views', {
1645 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1646 // Instances only share videos
1647 const query = 'SELECT 1 FROM "videoShare" ' +
1648 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1649 'WHERE "actorFollow"."actorId" = $followerActorId AND "videoShare"."videoId" = $videoId ' +
1653 type: QueryTypes.SELECT as QueryTypes.SELECT,
1654 bind: { followerActorId, videoId },
1658 return VideoModel.sequelize.query(query, options)
1659 .then(results => results.length === 1)
1662 static bulkUpdateSupportField (videoChannel: MChannel, t: Transaction) {
1665 channelId: videoChannel.id
1670 return VideoModel.update({ support: videoChannel.support }, options)
1673 static getAllIdsFromChannel (videoChannel: MChannelId): Bluebird<number[]> {
1675 attributes: [ 'id' ],
1677 channelId: videoChannel.id
1681 return VideoModel.findAll(query)
1682 .then(videos => videos.map(v => v.id))
1685 // threshold corresponds to how many video the field should have to be returned
1686 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1687 const serverActor = await getServerActor()
1688 const followerActorId = serverActor.id
1690 const scopeOptions: AvailableForListIDsOptions = {
1691 serverAccountId: serverActor.Account.id,
1693 includeLocalVideos: true,
1694 attributesType: 'none' // Don't break aggregation
1697 const query: FindOptions = {
1698 attributes: [ field ],
1701 having: Sequelize.where(
1702 Sequelize.fn('COUNT', Sequelize.col(field)), { [ Op.gte ]: threshold }
1704 order: [ (this.sequelize as any).random() ]
1707 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST_IDS, scopeOptions ] })
1709 .then(rows => rows.map(r => r[ field ]))
1712 static buildTrendingQuery (trendingDays: number) {
1716 model: VideoViewModel,
1720 [ Op.gte ]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1726 private static async getAvailableForApi (
1727 query: FindOptions & { where?: null }, // Forbid where field in query
1728 options: AvailableForListIDsOptions,
1731 const idsScope: ScopeOptions = {
1733 ScopeNames.AVAILABLE_FOR_LIST_IDS, options
1737 // Remove trending sort on count, because it uses a group by
1738 const countOptions = Object.assign({}, options, { trendingDays: undefined })
1739 const countQuery: CountOptions = Object.assign({}, query, { attributes: undefined, group: undefined })
1740 const countScope: ScopeOptions = {
1742 ScopeNames.AVAILABLE_FOR_LIST_IDS, countOptions
1746 const [ count, rows ] = await Promise.all([
1748 ? VideoModel.scope(countScope).count(countQuery)
1749 : Promise.resolve<number>(undefined),
1751 VideoModel.scope(idsScope)
1752 .findAll(Object.assign({}, query, { raw: true }))
1753 .then(rows => rows.map(r => r.id))
1754 .then(ids => VideoModel.loadCompleteVideosForApi(ids, query, options))
1763 private static loadCompleteVideosForApi (ids: number[], query: FindOptions, options: AvailableForListIDsOptions) {
1764 if (ids.length === 0) return []
1766 const secondQuery: FindOptions = {
1769 attributes: query.attributes,
1770 order: [ // Keep original order
1772 ids.map(id => `"VideoModel".id = ${id} DESC`).join(', ')
1777 const apiScope: (string | ScopeOptions)[] = []
1780 apiScope.push({ method: [ ScopeNames.WITH_USER_HISTORY, options.user.id ] })
1785 ScopeNames.FOR_API, {
1787 withFiles: options.withFiles,
1788 videoPlaylistId: options.videoPlaylistId
1793 return VideoModel.scope(apiScope).findAll(secondQuery)
1796 private static isPrivacyForFederation (privacy: VideoPrivacy) {
1797 const castedPrivacy = parseInt(privacy + '', 10)
1799 return castedPrivacy === VideoPrivacy.PUBLIC || castedPrivacy === VideoPrivacy.UNLISTED
1802 static getCategoryLabel (id: number) {
1803 return VIDEO_CATEGORIES[ id ] || 'Misc'
1806 static getLicenceLabel (id: number) {
1807 return VIDEO_LICENCES[ id ] || 'Unknown'
1810 static getLanguageLabel (id: string) {
1811 return VIDEO_LANGUAGES[ id ] || 'Unknown'
1814 static getPrivacyLabel (id: number) {
1815 return VIDEO_PRIVACIES[ id ] || 'Unknown'
1818 static getStateLabel (id: number) {
1819 return VIDEO_STATES[ id ] || 'Unknown'
1823 return !!this.VideoBlacklist
1827 return (this.VideoChannel.Account.Actor.Server && this.VideoChannel.Account.Actor.Server.isBlocked()) ||
1828 this.VideoChannel.Account.isBlocked()
1831 getQualityFileBy <T extends MVideoWithFile> (this: T, fun: (files: MVideoFile[], it: (file: MVideoFile) => number) => MVideoFile) {
1832 if (Array.isArray(this.VideoFiles) && this.VideoFiles.length !== 0) {
1833 const file = fun(this.VideoFiles, file => file.resolution)
1835 return Object.assign(file, { Video: this })
1838 // No webtorrent files, try with streaming playlist files
1839 if (Array.isArray(this.VideoStreamingPlaylists) && this.VideoStreamingPlaylists.length !== 0) {
1840 const streamingPlaylistWithVideo = Object.assign(this.VideoStreamingPlaylists[0], { Video: this })
1842 const file = fun(streamingPlaylistWithVideo.VideoFiles, file => file.resolution)
1843 return Object.assign(file, { VideoStreamingPlaylist: streamingPlaylistWithVideo })
1849 getMaxQualityFile <T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1850 return this.getQualityFileBy(maxBy)
1853 getMinQualityFile <T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1854 return this.getQualityFileBy(minBy)
1857 getWebTorrentFile <T extends MVideoWithFile> (this: T, resolution: number): MVideoFileVideo {
1858 if (Array.isArray(this.VideoFiles) === false) return undefined
1860 const file = this.VideoFiles.find(f => f.resolution === resolution)
1861 if (!file) return undefined
1863 return Object.assign(file, { Video: this })
1866 async addAndSaveThumbnail (thumbnail: MThumbnail, transaction: Transaction) {
1867 thumbnail.videoId = this.id
1869 const savedThumbnail = await thumbnail.save({ transaction })
1871 if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = []
1873 // Already have this thumbnail, skip
1874 if (this.Thumbnails.find(t => t.id === savedThumbnail.id)) return
1876 this.Thumbnails.push(savedThumbnail)
1879 generateThumbnailName () {
1880 return this.uuid + '.jpg'
1884 if (Array.isArray(this.Thumbnails) === false) return undefined
1886 return this.Thumbnails.find(t => t.type === ThumbnailType.MINIATURE)
1889 generatePreviewName () {
1890 return this.uuid + '.jpg'
1894 if (Array.isArray(this.Thumbnails) === false) return undefined
1896 return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW)
1900 return this.remote === false
1903 getWatchStaticPath () {
1904 return '/videos/watch/' + this.uuid
1907 getEmbedStaticPath () {
1908 return '/videos/embed/' + this.uuid
1911 getMiniatureStaticPath () {
1912 const thumbnail = this.getMiniature()
1913 if (!thumbnail) return null
1915 return join(STATIC_PATHS.THUMBNAILS, thumbnail.filename)
1918 getPreviewStaticPath () {
1919 const preview = this.getPreview()
1920 if (!preview) return null
1922 // We use a local cache, so specify our cache endpoint instead of potential remote URL
1923 return join(LAZY_STATIC_PATHS.PREVIEWS, preview.filename)
1926 toFormattedJSON (this: MVideoFormattable, options?: VideoFormattingJSONOptions): Video {
1927 return videoModelToFormattedJSON(this, options)
1930 toFormattedDetailsJSON (this: MVideoFormattableDetails): VideoDetails {
1931 return videoModelToFormattedDetailsJSON(this)
1934 getFormattedVideoFilesJSON (): VideoFile[] {
1935 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1936 return videoFilesModelToFormattedJSON(this, baseUrlHttp, baseUrlWs, this.VideoFiles)
1939 toActivityPubObject (this: MVideoAP): VideoTorrentObject {
1940 return videoModelToActivityPubObject(this)
1943 getTruncatedDescription () {
1944 if (!this.description) return null
1946 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1947 return peertubeTruncate(this.description, { length: maxLength })
1950 getMaxQualityResolution () {
1951 const file = this.getMaxQualityFile()
1952 const videoOrPlaylist = file.getVideoOrStreamingPlaylist()
1953 const originalFilePath = getVideoFilePath(videoOrPlaylist, file)
1955 return getVideoFileResolution(originalFilePath)
1958 getDescriptionAPIPath () {
1959 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1962 getHLSPlaylist (): MStreamingPlaylistFilesVideo {
1963 if (!this.VideoStreamingPlaylists) return undefined
1965 const playlist = this.VideoStreamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
1966 playlist.Video = this
1971 setHLSPlaylist (playlist: MStreamingPlaylist) {
1972 const toAdd = [ playlist ] as [ VideoStreamingPlaylistModel ]
1974 if (Array.isArray(this.VideoStreamingPlaylists) === false || this.VideoStreamingPlaylists.length === 0) {
1975 this.VideoStreamingPlaylists = toAdd
1979 this.VideoStreamingPlaylists = this.VideoStreamingPlaylists
1980 .filter(s => s.type !== VideoStreamingPlaylistType.HLS)
1984 removeFile (videoFile: MVideoFile, isRedundancy = false) {
1985 const filePath = getVideoFilePath(this, videoFile, isRedundancy)
1986 return remove(filePath)
1987 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1990 removeTorrent (videoFile: MVideoFile) {
1991 const torrentPath = getTorrentFilePath(this, videoFile)
1992 return remove(torrentPath)
1993 .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err }))
1996 async removeStreamingPlaylistFiles (streamingPlaylist: MStreamingPlaylist, isRedundancy = false) {
1997 const directoryPath = getHLSDirectory(this, isRedundancy)
1999 await remove(directoryPath)
2001 if (isRedundancy !== true) {
2002 let streamingPlaylistWithFiles = streamingPlaylist as MStreamingPlaylistFilesVideo
2003 streamingPlaylistWithFiles.Video = this
2005 if (!Array.isArray(streamingPlaylistWithFiles.VideoFiles)) {
2006 streamingPlaylistWithFiles.VideoFiles = await streamingPlaylistWithFiles.$get('VideoFiles')
2009 // Remove physical files and torrents
2011 streamingPlaylistWithFiles.VideoFiles.map(file => streamingPlaylistWithFiles.removeTorrent(file))
2017 if (this.isOwned()) return false
2019 return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)
2022 hasPrivacyForFederation () {
2023 return VideoModel.isPrivacyForFederation(this.privacy)
2026 isNewVideo (newPrivacy: VideoPrivacy) {
2027 return this.hasPrivacyForFederation() === false && VideoModel.isPrivacyForFederation(newPrivacy) === true
2031 this.changed('updatedAt', true)
2037 return this.privacy === VideoPrivacy.PRIVATE || this.privacy === VideoPrivacy.INTERNAL || !!this.VideoBlacklist
2040 setPrivacy (newPrivacy: VideoPrivacy) {
2041 if (this.privacy === VideoPrivacy.PRIVATE && newPrivacy !== VideoPrivacy.PRIVATE) {
2042 this.publishedAt = new Date()
2045 this.privacy = newPrivacy
2049 return this.privacy === VideoPrivacy.PRIVATE ||
2050 this.privacy === VideoPrivacy.UNLISTED ||
2051 this.privacy === VideoPrivacy.INTERNAL
2054 async publishIfNeededAndSave (t: Transaction) {
2055 if (this.state !== VideoState.PUBLISHED) {
2056 this.state = VideoState.PUBLISHED
2057 this.publishedAt = new Date()
2058 await this.save({ transaction: t })
2067 if (this.isOwned()) {
2069 baseUrlHttp: WEBSERVER.URL,
2070 baseUrlWs: WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT
2075 baseUrlHttp: REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host,
2076 baseUrlWs: REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
2080 getTrackerUrls (baseUrlHttp: string, baseUrlWs: string) {
2081 return [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
2084 getTorrentUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2085 return baseUrlHttp + STATIC_PATHS.TORRENTS + getTorrentFileName(this, videoFile)
2088 getTorrentDownloadUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2089 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + getTorrentFileName(this, videoFile)
2092 getVideoFileUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2093 return baseUrlHttp + STATIC_PATHS.WEBSEED + getVideoFilename(this, videoFile)
2096 getVideoRedundancyUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2097 return baseUrlHttp + STATIC_PATHS.REDUNDANCY + getVideoFilename(this, videoFile)
2100 getVideoFileDownloadUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2101 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + getVideoFilename(this, videoFile)
2104 getBandwidthBits (videoFile: MVideoFile) {
2105 return Math.ceil((videoFile.size * 8) / this.duration)