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,
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') {
276 const publishWhere = {
277 // Always list published videos, or videos that are being transcoded but on which we don't want to wait for transcoding
280 state: VideoState.PUBLISHED
284 state: VideoState.TO_TRANSCODE,
285 waitTranscoding: false
290 whereAnd.push(publishWhere)
292 // List internal videos if the user is logged in
294 const privacyWhere = {
297 privacy: VideoPrivacy.INTERNAL
300 privacy: VideoPrivacy.PUBLIC
305 whereAnd.push(privacyWhere)
306 } else { // Or only public videos
307 const privacyWhere = { privacy: VideoPrivacy.PUBLIC }
308 whereAnd.push(privacyWhere)
312 if (options.videoPlaylistId) {
315 model: VideoPlaylistElementModel.unscoped(),
318 videoPlaylistId: options.videoPlaylistId
322 query.subQuery = false
325 if (options.filter && (options.filter === 'local' || options.filter === 'all-local')) {
331 if (options.accountId || options.videoChannelId) {
332 const videoChannelInclude: IncludeOptions = {
334 model: VideoChannelModel.unscoped(),
338 if (options.videoChannelId) {
339 videoChannelInclude.where = {
340 id: options.videoChannelId
344 if (options.accountId) {
345 const accountInclude: IncludeOptions = {
347 model: AccountModel.unscoped(),
351 accountInclude.where = { id: options.accountId }
352 videoChannelInclude.include = [ accountInclude ]
355 query.include.push(videoChannelInclude)
358 if (options.followerActorId) {
359 let localVideosReq: WhereOptions = {}
360 if (options.includeLocalVideos === true) {
361 localVideosReq = { remote: false }
364 // Force actorId to be a number to avoid SQL injections
365 const actorIdNumber = parseInt(options.followerActorId.toString(), 10)
370 [Op.in]: Sequelize.literal(
372 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
373 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
374 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
381 [Op.in]: Sequelize.literal(
383 'SELECT "video"."id" AS "id" FROM "video" ' +
384 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
385 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
386 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
387 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
388 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
398 if (options.withFiles === true) {
401 [Op.in]: Sequelize.literal(
402 '(SELECT "videoId" FROM "videoFile")'
408 // FIXME: issues with sequelize count when making a join on n:m relation, so we just make a IN()
409 if (options.tagsAllOf || options.tagsOneOf) {
410 if (options.tagsOneOf) {
411 const tagsOneOfLower = options.tagsOneOf.map(t => t.toLowerCase())
415 [Op.in]: Sequelize.literal(
417 'SELECT "videoId" FROM "videoTag" ' +
418 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
419 'WHERE lower("tag"."name") IN (' + createSafeIn(VideoModel, tagsOneOfLower) + ')' +
426 if (options.tagsAllOf) {
427 const tagsAllOfLower = options.tagsAllOf.map(t => t.toLowerCase())
431 [Op.in]: Sequelize.literal(
433 'SELECT "videoId" FROM "videoTag" ' +
434 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
435 'WHERE lower("tag"."name") IN (' + createSafeIn(VideoModel, tagsAllOfLower) + ')' +
436 'GROUP BY "videoTag"."videoId" HAVING COUNT(*) = ' + tagsAllOfLower.length +
444 if (options.nsfw === true || options.nsfw === false) {
445 whereAnd.push({ nsfw: options.nsfw })
448 if (options.categoryOneOf) {
451 [Op.or]: options.categoryOneOf
456 if (options.licenceOneOf) {
459 [Op.or]: options.licenceOneOf
464 if (options.languageOneOf) {
465 let videoLanguages = options.languageOneOf
466 if (options.languageOneOf.find(l => l === '_unknown')) {
467 videoLanguages = videoLanguages.concat([ null ])
474 [Op.or]: videoLanguages
479 [Op.in]: Sequelize.literal(
481 'SELECT "videoId" FROM "videoCaption" ' +
482 'WHERE "language" IN (' + createSafeIn(VideoModel, options.languageOneOf) + ') ' +
491 if (options.trendingDays) {
492 query.include.push(VideoModel.buildTrendingQuery(options.trendingDays))
494 query.subQuery = false
497 if (options.historyOfUser) {
499 model: UserVideoHistoryModel,
502 userId: options.historyOfUser.id
506 // Even if the relation is n:m, we know that a user only have 0..1 video history
507 // So we won't have multiple rows for the same video
508 // Without this, we would not be able to sort on "updatedAt" column of UserVideoHistoryModel
509 query.subQuery = false
518 [ScopeNames.WITH_THUMBNAILS]: {
521 model: ThumbnailModel,
526 [ScopeNames.WITH_USER_ID]: {
529 attributes: [ 'accountId' ],
530 model: VideoChannelModel.unscoped(),
534 attributes: [ 'userId' ],
535 model: AccountModel.unscoped(),
542 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
545 model: VideoChannelModel.unscoped(),
550 exclude: [ 'privateKey', 'publicKey' ]
552 model: ActorModel.unscoped(),
556 attributes: [ 'host' ],
557 model: ServerModel.unscoped(),
561 model: AvatarModel.unscoped(),
567 model: AccountModel.unscoped(),
571 model: ActorModel.unscoped(),
573 exclude: [ 'privateKey', 'publicKey' ]
578 attributes: [ 'host' ],
579 model: ServerModel.unscoped(),
583 model: AvatarModel.unscoped(),
594 [ScopeNames.WITH_TAGS]: {
595 include: [ TagModel ]
597 [ScopeNames.WITH_BLACKLISTED]: {
600 attributes: [ 'id', 'reason', 'unfederated' ],
601 model: VideoBlacklistModel,
606 [ScopeNames.WITH_WEBTORRENT_FILES]: (withRedundancies = false) => {
607 let subInclude: any[] = []
609 if (withRedundancies === true) {
612 attributes: [ 'fileUrl' ],
613 model: VideoRedundancyModel.unscoped(),
622 model: VideoFileModel.unscoped(),
623 separate: true, // We may have multiple files, having multiple redundancies so let's separate this join
630 [ScopeNames.WITH_STREAMING_PLAYLISTS]: (withRedundancies = false) => {
631 const subInclude: IncludeOptions[] = [
633 model: VideoFileModel.unscoped(),
638 if (withRedundancies === true) {
640 attributes: [ 'fileUrl' ],
641 model: VideoRedundancyModel.unscoped(),
649 model: VideoStreamingPlaylistModel.unscoped(),
650 separate: true, // We may have multiple streaming playlists, having multiple redundancies so let's separate this join
657 [ScopeNames.WITH_SCHEDULED_UPDATE]: {
660 model: ScheduleVideoUpdateModel.unscoped(),
665 [ScopeNames.WITH_USER_HISTORY]: (userId: number) => {
669 attributes: [ 'currentTime' ],
670 model: UserVideoHistoryModel.unscoped(),
683 buildTrigramSearchIndex('video_name_trigram', 'name'),
685 { fields: [ 'createdAt' ] },
688 { name: 'publishedAt', order: 'DESC' },
689 { name: 'id', order: 'ASC' }
692 { fields: [ 'duration' ] },
693 { fields: [ 'views' ] },
694 { fields: [ 'channelId' ] },
696 fields: [ 'originallyPublishedAt' ],
698 originallyPublishedAt: {
704 fields: [ 'category' ], // We don't care videos with an unknown category
712 fields: [ 'licence' ], // We don't care videos with an unknown licence
720 fields: [ 'language' ], // We don't care videos with an unknown language
728 fields: [ 'nsfw' ], // Most of the videos are not NSFW
734 fields: [ 'remote' ], // Only index local videos
749 export class VideoModel extends Model<VideoModel> {
752 @Default(DataType.UUIDV4)
754 @Column(DataType.UUID)
758 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
764 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category', true))
770 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence', true))
776 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language', true))
777 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
781 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
786 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
792 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description', true))
793 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
798 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support', true))
799 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
803 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
833 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
834 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
839 commentsEnabled: boolean
843 downloadEnabled: boolean
847 waitTranscoding: boolean
851 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
862 @Default(DataType.NOW)
869 originallyPublishedAt: Date
871 @ForeignKey(() => VideoChannelModel)
875 @BelongsTo(() => VideoChannelModel, {
881 VideoChannel: VideoChannelModel
883 @BelongsToMany(() => TagModel, {
884 foreignKey: 'videoId',
885 through: () => VideoTagModel,
890 @HasMany(() => ThumbnailModel, {
898 Thumbnails: ThumbnailModel[]
900 @HasMany(() => VideoPlaylistElementModel, {
907 VideoPlaylistElements: VideoPlaylistElementModel[]
909 @HasMany(() => VideoAbuseModel, {
916 VideoAbuses: VideoAbuseModel[]
918 @HasMany(() => VideoFileModel, {
926 VideoFiles: VideoFileModel[]
928 @HasMany(() => VideoStreamingPlaylistModel, {
936 VideoStreamingPlaylists: VideoStreamingPlaylistModel[]
938 @HasMany(() => VideoShareModel, {
945 VideoShares: VideoShareModel[]
947 @HasMany(() => AccountVideoRateModel, {
954 AccountVideoRates: AccountVideoRateModel[]
956 @HasMany(() => VideoCommentModel, {
964 VideoComments: VideoCommentModel[]
966 @HasMany(() => VideoViewModel, {
973 VideoViews: VideoViewModel[]
975 @HasMany(() => UserVideoHistoryModel, {
982 UserVideoHistories: UserVideoHistoryModel[]
984 @HasOne(() => ScheduleVideoUpdateModel, {
991 ScheduleVideoUpdate: ScheduleVideoUpdateModel
993 @HasOne(() => VideoBlacklistModel, {
1000 VideoBlacklist: VideoBlacklistModel
1002 @HasOne(() => VideoImportModel, {
1007 onDelete: 'set null'
1009 VideoImport: VideoImportModel
1011 @HasMany(() => VideoCaptionModel, {
1016 onDelete: 'cascade',
1018 ['separate' as any]: true
1020 VideoCaptions: VideoCaptionModel[]
1023 static async sendDelete (instance: MVideoAccountLight, options) {
1024 if (instance.isOwned()) {
1025 if (!instance.VideoChannel) {
1026 instance.VideoChannel = await instance.$get('VideoChannel', {
1031 transaction: options.transaction
1032 }) as MChannelAccountDefault
1035 return sendDeleteVideo(instance, options.transaction)
1042 static async removeFiles (instance: VideoModel) {
1043 const tasks: Promise<any>[] = []
1045 logger.info('Removing files of video %s.', instance.url)
1047 if (instance.isOwned()) {
1048 if (!Array.isArray(instance.VideoFiles)) {
1049 instance.VideoFiles = await instance.$get('VideoFiles')
1052 // Remove physical files and torrents
1053 instance.VideoFiles.forEach(file => {
1054 tasks.push(instance.removeFile(file))
1055 tasks.push(instance.removeTorrent(file))
1058 // Remove playlists file
1059 if (!Array.isArray(instance.VideoStreamingPlaylists)) {
1060 instance.VideoStreamingPlaylists = await instance.$get('VideoStreamingPlaylists')
1063 for (const p of instance.VideoStreamingPlaylists) {
1064 tasks.push(instance.removeStreamingPlaylistFiles(p))
1068 // Do not wait video deletion because we could be in a transaction
1071 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
1077 static listLocal (): Bluebird<MVideoWithAllFiles[]> {
1084 return VideoModel.scope([
1085 ScopeNames.WITH_WEBTORRENT_FILES,
1086 ScopeNames.WITH_STREAMING_PLAYLISTS,
1087 ScopeNames.WITH_THUMBNAILS
1091 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
1092 function getRawQuery (select: string) {
1093 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
1094 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
1095 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
1096 'WHERE "Account"."actorId" = ' + actorId
1097 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
1098 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
1099 'WHERE "VideoShare"."actorId" = ' + actorId
1101 return `(${queryVideo}) UNION (${queryVideoShare})`
1104 const rawQuery = getRawQuery('"Video"."id"')
1105 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
1111 order: getVideoSort('createdAt', [ 'Tags', 'name', 'ASC' ] as any), // FIXME: sequelize typings
1114 [Op.in]: Sequelize.literal('(' + rawQuery + ')')
1117 { privacy: VideoPrivacy.PUBLIC },
1118 { privacy: VideoPrivacy.UNLISTED }
1123 attributes: [ 'language', 'fileUrl' ],
1124 model: VideoCaptionModel.unscoped(),
1128 attributes: [ 'id', 'url' ],
1129 model: VideoShareModel.unscoped(),
1131 // We only want videos shared by this actor
1146 attributes: [ 'id', 'url' ],
1147 model: ActorModel.unscoped()
1152 model: VideoChannelModel.unscoped(),
1156 attributes: [ 'name' ],
1157 model: AccountModel.unscoped(),
1161 attributes: [ 'id', 'url', 'followersUrl' ],
1162 model: ActorModel.unscoped(),
1168 attributes: [ 'id', 'url', 'followersUrl' ],
1169 model: ActorModel.unscoped(),
1179 return Bluebird.all([
1180 VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findAll(query),
1181 VideoModel.sequelize.query<{ total: string }>(rawCountQuery, { type: QueryTypes.SELECT })
1182 ]).then(([ rows, totals ]) => {
1183 // totals: totalVideos + totalVideoShares
1185 let totalVideoShares = 0
1186 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
1187 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
1189 const total = totalVideos + totalVideoShares
1197 static listUserVideosForApi (
1204 function buildBaseQuery (): FindOptions {
1208 order: getVideoSort(sort),
1211 model: VideoChannelModel,
1215 model: AccountModel,
1227 baseQuery = Object.assign(baseQuery, {
1230 [Op.iLike]: '%' + search + '%'
1239 const countQuery = buildBaseQuery()
1240 const findQuery = buildBaseQuery()
1242 const findScopes: (string | ScopeOptions)[] = [
1243 ScopeNames.WITH_SCHEDULED_UPDATE,
1244 ScopeNames.WITH_BLACKLISTED,
1245 ScopeNames.WITH_THUMBNAILS
1248 return Promise.all([
1249 VideoModel.count(countQuery),
1250 VideoModel.scope(findScopes).findAll<MVideoForUser>(findQuery)
1251 ]).then(([ count, rows ]) => {
1259 static async listForApi (options: {
1264 includeLocalVideos: boolean
1266 categoryOneOf?: number[]
1267 licenceOneOf?: number[]
1268 languageOneOf?: string[]
1269 tagsOneOf?: string[]
1270 tagsAllOf?: string[]
1271 filter?: VideoFilter
1273 videoChannelId?: number
1274 followerActorId?: number
1275 videoPlaylistId?: number
1276 trendingDays?: number
1277 user?: MUserAccountId
1278 historyOfUser?: MUserId
1279 countVideos?: boolean
1281 if (options.filter && options.filter === 'all-local' && !options.user.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1282 throw new Error('Try to filter all-local but no user has not the see all videos right')
1285 const query: FindOptions & { where?: null } = {
1286 offset: options.start,
1287 limit: options.count,
1288 order: getVideoSort(options.sort)
1291 let trendingDays: number
1292 if (options.sort.endsWith('trending')) {
1293 trendingDays = CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1295 query.group = 'VideoModel.id'
1298 const serverActor = await getServerActor()
1300 // followerActorId === null has a meaning, so just check undefined
1301 const followerActorId = options.followerActorId !== undefined ? options.followerActorId : serverActor.id
1303 const queryOptions = {
1305 serverAccountId: serverActor.Account.id,
1307 categoryOneOf: options.categoryOneOf,
1308 licenceOneOf: options.licenceOneOf,
1309 languageOneOf: options.languageOneOf,
1310 tagsOneOf: options.tagsOneOf,
1311 tagsAllOf: options.tagsAllOf,
1312 filter: options.filter,
1313 withFiles: options.withFiles,
1314 accountId: options.accountId,
1315 videoChannelId: options.videoChannelId,
1316 videoPlaylistId: options.videoPlaylistId,
1317 includeLocalVideos: options.includeLocalVideos,
1319 historyOfUser: options.historyOfUser,
1323 return VideoModel.getAvailableForApi(query, queryOptions, options.countVideos)
1326 static async searchAndPopulateAccountAndServer (options: {
1327 includeLocalVideos: boolean
1332 startDate?: string // ISO 8601
1333 endDate?: string // ISO 8601
1334 originallyPublishedStartDate?: string
1335 originallyPublishedEndDate?: string
1337 categoryOneOf?: number[]
1338 licenceOneOf?: number[]
1339 languageOneOf?: string[]
1340 tagsOneOf?: string[]
1341 tagsAllOf?: string[]
1342 durationMin?: number // seconds
1343 durationMax?: number // seconds
1344 user?: MUserAccountId
1345 filter?: VideoFilter
1349 if (options.startDate || options.endDate) {
1350 const publishedAtRange = {}
1352 if (options.startDate) publishedAtRange[Op.gte] = options.startDate
1353 if (options.endDate) publishedAtRange[Op.lte] = options.endDate
1355 whereAnd.push({ publishedAt: publishedAtRange })
1358 if (options.originallyPublishedStartDate || options.originallyPublishedEndDate) {
1359 const originallyPublishedAtRange = {}
1361 if (options.originallyPublishedStartDate) originallyPublishedAtRange[Op.gte] = options.originallyPublishedStartDate
1362 if (options.originallyPublishedEndDate) originallyPublishedAtRange[Op.lte] = options.originallyPublishedEndDate
1364 whereAnd.push({ originallyPublishedAt: originallyPublishedAtRange })
1367 if (options.durationMin || options.durationMax) {
1368 const durationRange = {}
1370 if (options.durationMin) durationRange[Op.gte] = options.durationMin
1371 if (options.durationMax) durationRange[Op.lte] = options.durationMax
1373 whereAnd.push({ duration: durationRange })
1376 const attributesInclude = []
1377 const escapedSearch = VideoModel.sequelize.escape(options.search)
1378 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
1379 if (options.search) {
1380 const trigramSearch = {
1382 [Op.in]: Sequelize.literal(
1384 'SELECT "video"."id" FROM "video" ' +
1386 'lower(immutable_unaccent("video"."name")) % lower(immutable_unaccent(' + escapedSearch + ')) OR ' +
1387 'lower(immutable_unaccent("video"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))' +
1389 'SELECT "video"."id" FROM "video" LEFT JOIN "videoTag" ON "videoTag"."videoId" = "video"."id" ' +
1390 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
1391 'WHERE lower("tag"."name") = lower(' + escapedSearch + ')' +
1397 if (validator.isUUID(options.search)) {
1402 uuid: options.search
1407 whereAnd.push(trigramSearch)
1410 attributesInclude.push(createSimilarityAttribute('VideoModel.name', options.search))
1413 // Cannot search on similarity if we don't have a search
1414 if (!options.search) {
1415 attributesInclude.push(
1416 Sequelize.literal('0 as similarity')
1422 include: attributesInclude
1424 offset: options.start,
1425 limit: options.count,
1426 order: getVideoSort(options.sort)
1429 const serverActor = await getServerActor()
1430 const queryOptions = {
1431 followerActorId: serverActor.id,
1432 serverAccountId: serverActor.Account.id,
1433 includeLocalVideos: options.includeLocalVideos,
1435 categoryOneOf: options.categoryOneOf,
1436 licenceOneOf: options.licenceOneOf,
1437 languageOneOf: options.languageOneOf,
1438 tagsOneOf: options.tagsOneOf,
1439 tagsAllOf: options.tagsAllOf,
1441 filter: options.filter,
1445 return VideoModel.getAvailableForApi(query, queryOptions)
1448 static load (id: number | string, t?: Transaction): Bluebird<MVideoThumbnail> {
1449 const where = buildWhereIdOrUUID(id)
1455 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1458 static loadWithBlacklist (id: number | string, t?: Transaction): Bluebird<MVideoThumbnailBlacklist> {
1459 const where = buildWhereIdOrUUID(id)
1465 return VideoModel.scope([
1466 ScopeNames.WITH_THUMBNAILS,
1467 ScopeNames.WITH_BLACKLISTED
1471 static loadWithRights (id: number | string, t?: Transaction): Bluebird<MVideoWithRights> {
1472 const where = buildWhereIdOrUUID(id)
1478 return VideoModel.scope([
1479 ScopeNames.WITH_BLACKLISTED,
1480 ScopeNames.WITH_USER_ID,
1481 ScopeNames.WITH_THUMBNAILS
1485 static loadOnlyId (id: number | string, t?: Transaction): Bluebird<MVideoIdThumbnail> {
1486 const where = buildWhereIdOrUUID(id)
1489 attributes: [ 'id' ],
1494 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1497 static loadWithFiles (id: number | string, t?: Transaction, logging?: boolean): Bluebird<MVideoWithAllFiles> {
1498 const where = buildWhereIdOrUUID(id)
1506 return VideoModel.scope([
1507 ScopeNames.WITH_WEBTORRENT_FILES,
1508 ScopeNames.WITH_STREAMING_PLAYLISTS,
1509 ScopeNames.WITH_THUMBNAILS
1513 static loadByUUID (uuid: string): Bluebird<MVideoThumbnail> {
1520 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1523 static loadByUrl (url: string, transaction?: Transaction): Bluebird<MVideoThumbnail> {
1524 const query: FindOptions = {
1531 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(query)
1534 static loadByUrlAndPopulateAccount (url: string, transaction?: Transaction): Bluebird<MVideoAccountLightBlacklistAllFiles> {
1535 const query: FindOptions = {
1542 return VideoModel.scope([
1543 ScopeNames.WITH_ACCOUNT_DETAILS,
1544 ScopeNames.WITH_WEBTORRENT_FILES,
1545 ScopeNames.WITH_STREAMING_PLAYLISTS,
1546 ScopeNames.WITH_THUMBNAILS,
1547 ScopeNames.WITH_BLACKLISTED
1551 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Transaction, userId?: number): Bluebird<MVideoFullLight> {
1552 const where = buildWhereIdOrUUID(id)
1555 order: [ [ 'Tags', 'name', 'ASC' ] ] as any,
1560 const scopes: (string | ScopeOptions)[] = [
1561 ScopeNames.WITH_TAGS,
1562 ScopeNames.WITH_BLACKLISTED,
1563 ScopeNames.WITH_ACCOUNT_DETAILS,
1564 ScopeNames.WITH_SCHEDULED_UPDATE,
1565 ScopeNames.WITH_WEBTORRENT_FILES,
1566 ScopeNames.WITH_STREAMING_PLAYLISTS,
1567 ScopeNames.WITH_THUMBNAILS
1571 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1579 static loadForGetAPI (parameters: {
1583 }): Bluebird<MVideoDetails> {
1584 const { id, t, userId } = parameters
1585 const where = buildWhereIdOrUUID(id)
1588 order: [ [ 'Tags', 'name', 'ASC' ] ] as any, // FIXME: sequelize typings
1593 const scopes: (string | ScopeOptions)[] = [
1594 ScopeNames.WITH_TAGS,
1595 ScopeNames.WITH_BLACKLISTED,
1596 ScopeNames.WITH_ACCOUNT_DETAILS,
1597 ScopeNames.WITH_SCHEDULED_UPDATE,
1598 ScopeNames.WITH_THUMBNAILS,
1599 { method: [ ScopeNames.WITH_WEBTORRENT_FILES, true ] },
1600 { method: [ ScopeNames.WITH_STREAMING_PLAYLISTS, true ] }
1604 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1612 static async getStats () {
1613 const totalLocalVideos = await VideoModel.count({
1618 const totalVideos = await VideoModel.count()
1620 let totalLocalVideoViews = await VideoModel.sum('views', {
1625 // Sequelize could return null...
1626 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1630 totalLocalVideoViews,
1635 static incrementViews (id: number, views: number) {
1636 return VideoModel.increment('views', {
1644 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1645 // Instances only share videos
1646 const query = 'SELECT 1 FROM "videoShare" ' +
1647 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1648 'WHERE "actorFollow"."actorId" = $followerActorId AND "videoShare"."videoId" = $videoId ' +
1652 type: QueryTypes.SELECT as QueryTypes.SELECT,
1653 bind: { followerActorId, videoId },
1657 return VideoModel.sequelize.query(query, options)
1658 .then(results => results.length === 1)
1661 static bulkUpdateSupportField (videoChannel: MChannel, t: Transaction) {
1664 channelId: videoChannel.id
1669 return VideoModel.update({ support: videoChannel.support }, options)
1672 static getAllIdsFromChannel (videoChannel: MChannelId): Bluebird<number[]> {
1674 attributes: [ 'id' ],
1676 channelId: videoChannel.id
1680 return VideoModel.findAll(query)
1681 .then(videos => videos.map(v => v.id))
1684 // threshold corresponds to how many video the field should have to be returned
1685 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1686 const serverActor = await getServerActor()
1687 const followerActorId = serverActor.id
1689 const scopeOptions: AvailableForListIDsOptions = {
1690 serverAccountId: serverActor.Account.id,
1692 includeLocalVideos: true,
1693 attributesType: 'none' // Don't break aggregation
1696 const query: FindOptions = {
1697 attributes: [ field ],
1700 having: Sequelize.where(
1701 Sequelize.fn('COUNT', Sequelize.col(field)), { [Op.gte]: threshold }
1703 order: [ (this.sequelize as any).random() ]
1706 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST_IDS, scopeOptions ] })
1708 .then(rows => rows.map(r => r[field]))
1711 static buildTrendingQuery (trendingDays: number) {
1715 model: VideoViewModel,
1719 [Op.gte]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1725 private static async getAvailableForApi (
1726 query: FindOptions & { where?: null }, // Forbid where field in query
1727 options: AvailableForListIDsOptions,
1730 const idsScope: ScopeOptions = {
1732 ScopeNames.AVAILABLE_FOR_LIST_IDS, options
1736 // Remove trending sort on count, because it uses a group by
1737 const countOptions = Object.assign({}, options, { trendingDays: undefined })
1738 const countQuery: CountOptions = Object.assign({}, query, { attributes: undefined, group: undefined })
1739 const countScope: ScopeOptions = {
1741 ScopeNames.AVAILABLE_FOR_LIST_IDS, countOptions
1745 const [ count, rows ] = await Promise.all([
1747 ? VideoModel.scope(countScope).count(countQuery)
1748 : Promise.resolve<number>(undefined),
1750 VideoModel.scope(idsScope)
1751 .findAll(Object.assign({}, query, { raw: true }))
1752 .then(rows => rows.map(r => r.id))
1753 .then(ids => VideoModel.loadCompleteVideosForApi(ids, query, options))
1762 private static loadCompleteVideosForApi (ids: number[], query: FindOptions, options: AvailableForListIDsOptions) {
1763 if (ids.length === 0) return []
1765 const secondQuery: FindOptions = {
1768 attributes: query.attributes,
1769 order: [ // Keep original order
1771 ids.map(id => `"VideoModel".id = ${id} DESC`).join(', ')
1776 const apiScope: (string | ScopeOptions)[] = []
1779 apiScope.push({ method: [ ScopeNames.WITH_USER_HISTORY, options.user.id ] })
1784 ScopeNames.FOR_API, {
1786 withFiles: options.withFiles,
1787 videoPlaylistId: options.videoPlaylistId
1792 return VideoModel.scope(apiScope).findAll(secondQuery)
1795 private static isPrivacyForFederation (privacy: VideoPrivacy) {
1796 const castedPrivacy = parseInt(privacy + '', 10)
1798 return castedPrivacy === VideoPrivacy.PUBLIC || castedPrivacy === VideoPrivacy.UNLISTED
1801 static getCategoryLabel (id: number) {
1802 return VIDEO_CATEGORIES[id] || 'Misc'
1805 static getLicenceLabel (id: number) {
1806 return VIDEO_LICENCES[id] || 'Unknown'
1809 static getLanguageLabel (id: string) {
1810 return VIDEO_LANGUAGES[id] || 'Unknown'
1813 static getPrivacyLabel (id: number) {
1814 return VIDEO_PRIVACIES[id] || 'Unknown'
1817 static getStateLabel (id: number) {
1818 return VIDEO_STATES[id] || 'Unknown'
1822 return !!this.VideoBlacklist
1826 return (this.VideoChannel.Account.Actor.Server && this.VideoChannel.Account.Actor.Server.isBlocked()) ||
1827 this.VideoChannel.Account.isBlocked()
1830 getQualityFileBy<T extends MVideoWithFile> (this: T, fun: (files: MVideoFile[], it: (file: MVideoFile) => number) => MVideoFile) {
1831 if (Array.isArray(this.VideoFiles) && this.VideoFiles.length !== 0) {
1832 const file = fun(this.VideoFiles, file => file.resolution)
1834 return Object.assign(file, { Video: this })
1837 // No webtorrent files, try with streaming playlist files
1838 if (Array.isArray(this.VideoStreamingPlaylists) && this.VideoStreamingPlaylists.length !== 0) {
1839 const streamingPlaylistWithVideo = Object.assign(this.VideoStreamingPlaylists[0], { Video: this })
1841 const file = fun(streamingPlaylistWithVideo.VideoFiles, file => file.resolution)
1842 return Object.assign(file, { VideoStreamingPlaylist: streamingPlaylistWithVideo })
1848 getMaxQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1849 return this.getQualityFileBy(maxBy)
1852 getMinQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1853 return this.getQualityFileBy(minBy)
1856 getWebTorrentFile<T extends MVideoWithFile> (this: T, resolution: number): MVideoFileVideo {
1857 if (Array.isArray(this.VideoFiles) === false) return undefined
1859 const file = this.VideoFiles.find(f => f.resolution === resolution)
1860 if (!file) return undefined
1862 return Object.assign(file, { Video: this })
1865 async addAndSaveThumbnail (thumbnail: MThumbnail, transaction: Transaction) {
1866 thumbnail.videoId = this.id
1868 const savedThumbnail = await thumbnail.save({ transaction })
1870 if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = []
1872 // Already have this thumbnail, skip
1873 if (this.Thumbnails.find(t => t.id === savedThumbnail.id)) return
1875 this.Thumbnails.push(savedThumbnail)
1878 generateThumbnailName () {
1879 return this.uuid + '.jpg'
1883 if (Array.isArray(this.Thumbnails) === false) return undefined
1885 return this.Thumbnails.find(t => t.type === ThumbnailType.MINIATURE)
1888 generatePreviewName () {
1889 return this.uuid + '.jpg'
1893 if (Array.isArray(this.Thumbnails) === false) return undefined
1895 return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW)
1899 return this.remote === false
1902 getWatchStaticPath () {
1903 return '/videos/watch/' + this.uuid
1906 getEmbedStaticPath () {
1907 return '/videos/embed/' + this.uuid
1910 getMiniatureStaticPath () {
1911 const thumbnail = this.getMiniature()
1912 if (!thumbnail) return null
1914 return join(STATIC_PATHS.THUMBNAILS, thumbnail.filename)
1917 getPreviewStaticPath () {
1918 const preview = this.getPreview()
1919 if (!preview) return null
1921 // We use a local cache, so specify our cache endpoint instead of potential remote URL
1922 return join(LAZY_STATIC_PATHS.PREVIEWS, preview.filename)
1925 toFormattedJSON (this: MVideoFormattable, options?: VideoFormattingJSONOptions): Video {
1926 return videoModelToFormattedJSON(this, options)
1929 toFormattedDetailsJSON (this: MVideoFormattableDetails): VideoDetails {
1930 return videoModelToFormattedDetailsJSON(this)
1933 getFormattedVideoFilesJSON (): VideoFile[] {
1934 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1935 return videoFilesModelToFormattedJSON(this, baseUrlHttp, baseUrlWs, this.VideoFiles)
1938 toActivityPubObject (this: MVideoAP): VideoTorrentObject {
1939 return videoModelToActivityPubObject(this)
1942 getTruncatedDescription () {
1943 if (!this.description) return null
1945 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1946 return peertubeTruncate(this.description, { length: maxLength })
1949 getMaxQualityResolution () {
1950 const file = this.getMaxQualityFile()
1951 const videoOrPlaylist = file.getVideoOrStreamingPlaylist()
1952 const originalFilePath = getVideoFilePath(videoOrPlaylist, file)
1954 return getVideoFileResolution(originalFilePath)
1957 getDescriptionAPIPath () {
1958 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1961 getHLSPlaylist (): MStreamingPlaylistFilesVideo {
1962 if (!this.VideoStreamingPlaylists) return undefined
1964 const playlist = this.VideoStreamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
1965 playlist.Video = this
1970 setHLSPlaylist (playlist: MStreamingPlaylist) {
1971 const toAdd = [ playlist ] as [ VideoStreamingPlaylistModel ]
1973 if (Array.isArray(this.VideoStreamingPlaylists) === false || this.VideoStreamingPlaylists.length === 0) {
1974 this.VideoStreamingPlaylists = toAdd
1978 this.VideoStreamingPlaylists = this.VideoStreamingPlaylists
1979 .filter(s => s.type !== VideoStreamingPlaylistType.HLS)
1983 removeFile (videoFile: MVideoFile, isRedundancy = false) {
1984 const filePath = getVideoFilePath(this, videoFile, isRedundancy)
1985 return remove(filePath)
1986 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1989 removeTorrent (videoFile: MVideoFile) {
1990 const torrentPath = getTorrentFilePath(this, videoFile)
1991 return remove(torrentPath)
1992 .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err }))
1995 async removeStreamingPlaylistFiles (streamingPlaylist: MStreamingPlaylist, isRedundancy = false) {
1996 const directoryPath = getHLSDirectory(this, isRedundancy)
1998 await remove(directoryPath)
2000 if (isRedundancy !== true) {
2001 const streamingPlaylistWithFiles = streamingPlaylist as MStreamingPlaylistFilesVideo
2002 streamingPlaylistWithFiles.Video = this
2004 if (!Array.isArray(streamingPlaylistWithFiles.VideoFiles)) {
2005 streamingPlaylistWithFiles.VideoFiles = await streamingPlaylistWithFiles.$get('VideoFiles')
2008 // Remove physical files and torrents
2010 streamingPlaylistWithFiles.VideoFiles.map(file => streamingPlaylistWithFiles.removeTorrent(file))
2016 if (this.isOwned()) return false
2018 return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)
2021 hasPrivacyForFederation () {
2022 return VideoModel.isPrivacyForFederation(this.privacy)
2025 isNewVideo (newPrivacy: VideoPrivacy) {
2026 return this.hasPrivacyForFederation() === false && VideoModel.isPrivacyForFederation(newPrivacy) === true
2030 this.changed('updatedAt', true)
2036 return this.privacy === VideoPrivacy.PRIVATE || this.privacy === VideoPrivacy.INTERNAL || !!this.VideoBlacklist
2039 setPrivacy (newPrivacy: VideoPrivacy) {
2040 if (this.privacy === VideoPrivacy.PRIVATE && newPrivacy !== VideoPrivacy.PRIVATE) {
2041 this.publishedAt = new Date()
2044 this.privacy = newPrivacy
2048 return this.privacy === VideoPrivacy.PRIVATE ||
2049 this.privacy === VideoPrivacy.UNLISTED ||
2050 this.privacy === VideoPrivacy.INTERNAL
2053 async publishIfNeededAndSave (t: Transaction) {
2054 if (this.state !== VideoState.PUBLISHED) {
2055 this.state = VideoState.PUBLISHED
2056 this.publishedAt = new Date()
2057 await this.save({ transaction: t })
2066 if (this.isOwned()) {
2068 baseUrlHttp: WEBSERVER.URL,
2069 baseUrlWs: WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT
2074 baseUrlHttp: REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host,
2075 baseUrlWs: REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
2079 getTrackerUrls (baseUrlHttp: string, baseUrlWs: string) {
2080 return [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
2083 getTorrentUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2084 return baseUrlHttp + STATIC_PATHS.TORRENTS + getTorrentFileName(this, videoFile)
2087 getTorrentDownloadUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2088 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + getTorrentFileName(this, videoFile)
2091 getVideoFileUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2092 return baseUrlHttp + STATIC_PATHS.WEBSEED + getVideoFilename(this, videoFile)
2095 getVideoRedundancyUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2096 return baseUrlHttp + STATIC_PATHS.REDUNDANCY + getVideoFilename(this, videoFile)
2099 getVideoFileDownloadUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2100 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + getVideoFilename(this, videoFile)
2103 getBandwidthBits (videoFile: MVideoFile) {
2104 return Math.ceil((videoFile.size * 8) / this.duration)