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,
123 MVideoIdThumbnail, MVideoImmutable,
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'
135 import { ModelCache } from '@server/models/model-cache'
137 export enum ScopeNames {
138 AVAILABLE_FOR_LIST_IDS = 'AVAILABLE_FOR_LIST_IDS',
140 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
141 WITH_TAGS = 'WITH_TAGS',
142 WITH_WEBTORRENT_FILES = 'WITH_WEBTORRENT_FILES',
143 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
144 WITH_BLACKLISTED = 'WITH_BLACKLISTED',
145 WITH_USER_HISTORY = 'WITH_USER_HISTORY',
146 WITH_STREAMING_PLAYLISTS = 'WITH_STREAMING_PLAYLISTS',
147 WITH_USER_ID = 'WITH_USER_ID',
148 WITH_IMMUTABLE_ATTRIBUTES = 'WITH_IMMUTABLE_ATTRIBUTES',
149 WITH_THUMBNAILS = 'WITH_THUMBNAILS'
152 export type ForAPIOptions = {
155 videoPlaylistId?: number
159 withAccountBlockerIds?: number[]
162 export type AvailableForListIDsOptions = {
163 serverAccountId: number
164 followerActorId: number
165 includeLocalVideos: boolean
167 attributesType?: 'none' | 'id' | 'all'
170 categoryOneOf?: number[]
172 licenceOneOf?: number[]
173 languageOneOf?: string[]
180 videoChannelId?: number
182 videoPlaylistId?: number
184 trendingDays?: number
185 user?: MUserAccountId
186 historyOfUser?: MUserId
188 baseWhere?: WhereOptions[]
192 [ScopeNames.WITH_IMMUTABLE_ATTRIBUTES]: {
193 attributes: [ 'id', 'url', 'uuid', 'remote' ]
195 [ScopeNames.FOR_API]: (options: ForAPIOptions) => {
196 const query: FindOptions = {
199 model: VideoChannelModel.scope({
201 VideoChannelScopeNames.SUMMARY, {
203 withAccountBlockerIds: options.withAccountBlockerIds
210 attributes: [ 'type', 'filename' ],
211 model: ThumbnailModel,
225 if (options.withFiles === true) {
227 model: VideoFileModel.unscoped(),
232 if (options.videoPlaylistId) {
234 model: VideoPlaylistElementModel.unscoped(),
237 videoPlaylistId: options.videoPlaylistId
244 [ScopeNames.AVAILABLE_FOR_LIST_IDS]: (options: AvailableForListIDsOptions) => {
245 const whereAnd = options.baseWhere ? [].concat(options.baseWhere) : []
247 const query: FindOptions = {
252 const attributesType = options.attributesType || 'id'
254 if (attributesType === 'id') query.attributes = [ 'id' ]
255 else if (attributesType === 'none') query.attributes = []
259 [Op.notIn]: Sequelize.literal(
260 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
265 if (options.serverAccountId) {
268 [Op.notIn]: Sequelize.literal(
270 'SELECT id FROM "videoChannel" WHERE "accountId" IN (' +
271 buildBlockedAccountSQL(options.serverAccountId, options.user ? options.user.Account.id : undefined) +
279 // Only list public/published videos
280 if (!options.filter || options.filter !== 'all-local') {
281 const publishWhere = {
282 // Always list published videos, or videos that are being transcoded but on which we don't want to wait for transcoding
285 state: VideoState.PUBLISHED
289 state: VideoState.TO_TRANSCODE,
290 waitTranscoding: false
295 whereAnd.push(publishWhere)
297 // List internal videos if the user is logged in
299 const privacyWhere = {
302 privacy: VideoPrivacy.INTERNAL
305 privacy: VideoPrivacy.PUBLIC
310 whereAnd.push(privacyWhere)
311 } else { // Or only public videos
312 const privacyWhere = { privacy: VideoPrivacy.PUBLIC }
313 whereAnd.push(privacyWhere)
317 if (options.videoPlaylistId) {
320 model: VideoPlaylistElementModel.unscoped(),
323 videoPlaylistId: options.videoPlaylistId
327 query.subQuery = false
330 if (options.filter && (options.filter === 'local' || options.filter === 'all-local')) {
336 if (options.accountId || options.videoChannelId) {
337 const videoChannelInclude: IncludeOptions = {
339 model: VideoChannelModel.unscoped(),
343 if (options.videoChannelId) {
344 videoChannelInclude.where = {
345 id: options.videoChannelId
349 if (options.accountId) {
350 const accountInclude: IncludeOptions = {
352 model: AccountModel.unscoped(),
356 accountInclude.where = { id: options.accountId }
357 videoChannelInclude.include = [ accountInclude ]
360 query.include.push(videoChannelInclude)
363 if (options.followerActorId) {
364 let localVideosReq: WhereOptions = {}
365 if (options.includeLocalVideos === true) {
366 localVideosReq = { remote: false }
369 // Force actorId to be a number to avoid SQL injections
370 const actorIdNumber = parseInt(options.followerActorId.toString(), 10)
375 [Op.in]: Sequelize.literal(
377 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
378 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
379 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
386 [Op.in]: Sequelize.literal(
388 'SELECT "video"."id" AS "id" FROM "video" ' +
389 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
390 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
391 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
392 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
393 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
403 if (options.withFiles === true) {
406 [Op.in]: Sequelize.literal(
407 '(SELECT "videoId" FROM "videoFile")'
413 // FIXME: issues with sequelize count when making a join on n:m relation, so we just make a IN()
414 if (options.tagsAllOf || options.tagsOneOf) {
415 if (options.tagsOneOf) {
416 const tagsOneOfLower = options.tagsOneOf.map(t => t.toLowerCase())
420 [Op.in]: Sequelize.literal(
422 'SELECT "videoId" FROM "videoTag" ' +
423 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
424 'WHERE lower("tag"."name") IN (' + createSafeIn(VideoModel, tagsOneOfLower) + ')' +
431 if (options.tagsAllOf) {
432 const tagsAllOfLower = options.tagsAllOf.map(t => t.toLowerCase())
436 [Op.in]: Sequelize.literal(
438 'SELECT "videoId" FROM "videoTag" ' +
439 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
440 'WHERE lower("tag"."name") IN (' + createSafeIn(VideoModel, tagsAllOfLower) + ')' +
441 'GROUP BY "videoTag"."videoId" HAVING COUNT(*) = ' + tagsAllOfLower.length +
449 if (options.nsfw === true || options.nsfw === false) {
450 whereAnd.push({ nsfw: options.nsfw })
453 if (options.categoryOneOf) {
456 [Op.or]: options.categoryOneOf
461 if (options.licenceOneOf) {
464 [Op.or]: options.licenceOneOf
469 if (options.languageOneOf) {
470 let videoLanguages = options.languageOneOf
471 if (options.languageOneOf.find(l => l === '_unknown')) {
472 videoLanguages = videoLanguages.concat([ null ])
479 [Op.or]: videoLanguages
484 [Op.in]: Sequelize.literal(
486 'SELECT "videoId" FROM "videoCaption" ' +
487 'WHERE "language" IN (' + createSafeIn(VideoModel, options.languageOneOf) + ') ' +
496 if (options.trendingDays) {
497 query.include.push(VideoModel.buildTrendingQuery(options.trendingDays))
499 query.subQuery = false
502 if (options.historyOfUser) {
504 model: UserVideoHistoryModel,
507 userId: options.historyOfUser.id
511 // Even if the relation is n:m, we know that a user only have 0..1 video history
512 // So we won't have multiple rows for the same video
513 // Without this, we would not be able to sort on "updatedAt" column of UserVideoHistoryModel
514 query.subQuery = false
523 [ScopeNames.WITH_THUMBNAILS]: {
526 model: ThumbnailModel,
531 [ScopeNames.WITH_USER_ID]: {
534 attributes: [ 'accountId' ],
535 model: VideoChannelModel.unscoped(),
539 attributes: [ 'userId' ],
540 model: AccountModel.unscoped(),
547 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
550 model: VideoChannelModel.unscoped(),
555 exclude: [ 'privateKey', 'publicKey' ]
557 model: ActorModel.unscoped(),
561 attributes: [ 'host' ],
562 model: ServerModel.unscoped(),
566 model: AvatarModel.unscoped(),
572 model: AccountModel.unscoped(),
576 model: ActorModel.unscoped(),
578 exclude: [ 'privateKey', 'publicKey' ]
583 attributes: [ 'host' ],
584 model: ServerModel.unscoped(),
588 model: AvatarModel.unscoped(),
599 [ScopeNames.WITH_TAGS]: {
600 include: [ TagModel ]
602 [ScopeNames.WITH_BLACKLISTED]: {
605 attributes: [ 'id', 'reason', 'unfederated' ],
606 model: VideoBlacklistModel,
611 [ScopeNames.WITH_WEBTORRENT_FILES]: (withRedundancies = false) => {
612 let subInclude: any[] = []
614 if (withRedundancies === true) {
617 attributes: [ 'fileUrl' ],
618 model: VideoRedundancyModel.unscoped(),
627 model: VideoFileModel.unscoped(),
628 separate: true, // We may have multiple files, having multiple redundancies so let's separate this join
635 [ScopeNames.WITH_STREAMING_PLAYLISTS]: (withRedundancies = false) => {
636 const subInclude: IncludeOptions[] = [
638 model: VideoFileModel.unscoped(),
643 if (withRedundancies === true) {
645 attributes: [ 'fileUrl' ],
646 model: VideoRedundancyModel.unscoped(),
654 model: VideoStreamingPlaylistModel.unscoped(),
655 separate: true, // We may have multiple streaming playlists, having multiple redundancies so let's separate this join
662 [ScopeNames.WITH_SCHEDULED_UPDATE]: {
665 model: ScheduleVideoUpdateModel.unscoped(),
670 [ScopeNames.WITH_USER_HISTORY]: (userId: number) => {
674 attributes: [ 'currentTime' ],
675 model: UserVideoHistoryModel.unscoped(),
688 buildTrigramSearchIndex('video_name_trigram', 'name'),
690 { fields: [ 'createdAt' ] },
693 { name: 'publishedAt', order: 'DESC' },
694 { name: 'id', order: 'ASC' }
697 { fields: [ 'duration' ] },
698 { fields: [ 'views' ] },
699 { fields: [ 'channelId' ] },
701 fields: [ 'originallyPublishedAt' ],
703 originallyPublishedAt: {
709 fields: [ 'category' ], // We don't care videos with an unknown category
717 fields: [ 'licence' ], // We don't care videos with an unknown licence
725 fields: [ 'language' ], // We don't care videos with an unknown language
733 fields: [ 'nsfw' ], // Most of the videos are not NSFW
739 fields: [ 'remote' ], // Only index local videos
754 export class VideoModel extends Model<VideoModel> {
757 @Default(DataType.UUIDV4)
759 @Column(DataType.UUID)
763 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
769 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category', true))
775 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence', true))
781 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language', true))
782 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
786 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
791 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
797 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description', true))
798 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
803 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support', true))
804 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
808 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
838 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
839 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
844 commentsEnabled: boolean
848 downloadEnabled: boolean
852 waitTranscoding: boolean
856 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
867 @Default(DataType.NOW)
874 originallyPublishedAt: Date
876 @ForeignKey(() => VideoChannelModel)
880 @BelongsTo(() => VideoChannelModel, {
886 VideoChannel: VideoChannelModel
888 @BelongsToMany(() => TagModel, {
889 foreignKey: 'videoId',
890 through: () => VideoTagModel,
895 @HasMany(() => ThumbnailModel, {
903 Thumbnails: ThumbnailModel[]
905 @HasMany(() => VideoPlaylistElementModel, {
912 VideoPlaylistElements: VideoPlaylistElementModel[]
914 @HasMany(() => VideoAbuseModel, {
921 VideoAbuses: VideoAbuseModel[]
923 @HasMany(() => VideoFileModel, {
931 VideoFiles: VideoFileModel[]
933 @HasMany(() => VideoStreamingPlaylistModel, {
941 VideoStreamingPlaylists: VideoStreamingPlaylistModel[]
943 @HasMany(() => VideoShareModel, {
950 VideoShares: VideoShareModel[]
952 @HasMany(() => AccountVideoRateModel, {
959 AccountVideoRates: AccountVideoRateModel[]
961 @HasMany(() => VideoCommentModel, {
969 VideoComments: VideoCommentModel[]
971 @HasMany(() => VideoViewModel, {
978 VideoViews: VideoViewModel[]
980 @HasMany(() => UserVideoHistoryModel, {
987 UserVideoHistories: UserVideoHistoryModel[]
989 @HasOne(() => ScheduleVideoUpdateModel, {
996 ScheduleVideoUpdate: ScheduleVideoUpdateModel
998 @HasOne(() => VideoBlacklistModel, {
1005 VideoBlacklist: VideoBlacklistModel
1007 @HasOne(() => VideoImportModel, {
1012 onDelete: 'set null'
1014 VideoImport: VideoImportModel
1016 @HasMany(() => VideoCaptionModel, {
1021 onDelete: 'cascade',
1023 ['separate' as any]: true
1025 VideoCaptions: VideoCaptionModel[]
1028 static async sendDelete (instance: MVideoAccountLight, options) {
1029 if (instance.isOwned()) {
1030 if (!instance.VideoChannel) {
1031 instance.VideoChannel = await instance.$get('VideoChannel', {
1036 transaction: options.transaction
1037 }) as MChannelAccountDefault
1040 return sendDeleteVideo(instance, options.transaction)
1047 static async removeFiles (instance: VideoModel) {
1048 const tasks: Promise<any>[] = []
1050 logger.info('Removing files of video %s.', instance.url)
1052 if (instance.isOwned()) {
1053 if (!Array.isArray(instance.VideoFiles)) {
1054 instance.VideoFiles = await instance.$get('VideoFiles')
1057 // Remove physical files and torrents
1058 instance.VideoFiles.forEach(file => {
1059 tasks.push(instance.removeFile(file))
1060 tasks.push(instance.removeTorrent(file))
1063 // Remove playlists file
1064 if (!Array.isArray(instance.VideoStreamingPlaylists)) {
1065 instance.VideoStreamingPlaylists = await instance.$get('VideoStreamingPlaylists')
1068 for (const p of instance.VideoStreamingPlaylists) {
1069 tasks.push(instance.removeStreamingPlaylistFiles(p))
1073 // Do not wait video deletion because we could be in a transaction
1076 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
1083 static invalidateCache (instance: VideoModel) {
1084 ModelCache.Instance.invalidateCache('video', instance.id)
1087 static listLocal (): Bluebird<MVideoWithAllFiles[]> {
1094 return VideoModel.scope([
1095 ScopeNames.WITH_WEBTORRENT_FILES,
1096 ScopeNames.WITH_STREAMING_PLAYLISTS,
1097 ScopeNames.WITH_THUMBNAILS
1101 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
1102 function getRawQuery (select: string) {
1103 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
1104 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
1105 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
1106 'WHERE "Account"."actorId" = ' + actorId
1107 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
1108 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
1109 'WHERE "VideoShare"."actorId" = ' + actorId
1111 return `(${queryVideo}) UNION (${queryVideoShare})`
1114 const rawQuery = getRawQuery('"Video"."id"')
1115 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
1121 order: getVideoSort('createdAt', [ 'Tags', 'name', 'ASC' ] as any), // FIXME: sequelize typings
1124 [Op.in]: Sequelize.literal('(' + rawQuery + ')')
1127 { privacy: VideoPrivacy.PUBLIC },
1128 { privacy: VideoPrivacy.UNLISTED }
1133 attributes: [ 'language', 'fileUrl' ],
1134 model: VideoCaptionModel.unscoped(),
1138 attributes: [ 'id', 'url' ],
1139 model: VideoShareModel.unscoped(),
1141 // We only want videos shared by this actor
1156 attributes: [ 'id', 'url' ],
1157 model: ActorModel.unscoped()
1162 model: VideoChannelModel.unscoped(),
1166 attributes: [ 'name' ],
1167 model: AccountModel.unscoped(),
1171 attributes: [ 'id', 'url', 'followersUrl' ],
1172 model: ActorModel.unscoped(),
1178 attributes: [ 'id', 'url', 'followersUrl' ],
1179 model: ActorModel.unscoped(),
1189 return Bluebird.all([
1190 VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findAll(query),
1191 VideoModel.sequelize.query<{ total: string }>(rawCountQuery, { type: QueryTypes.SELECT })
1192 ]).then(([ rows, totals ]) => {
1193 // totals: totalVideos + totalVideoShares
1195 let totalVideoShares = 0
1196 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
1197 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
1199 const total = totalVideos + totalVideoShares
1207 static listUserVideosForApi (
1214 function buildBaseQuery (): FindOptions {
1218 order: getVideoSort(sort),
1221 model: VideoChannelModel,
1225 model: AccountModel,
1237 baseQuery = Object.assign(baseQuery, {
1240 [Op.iLike]: '%' + search + '%'
1249 const countQuery = buildBaseQuery()
1250 const findQuery = buildBaseQuery()
1252 const findScopes: (string | ScopeOptions)[] = [
1253 ScopeNames.WITH_SCHEDULED_UPDATE,
1254 ScopeNames.WITH_BLACKLISTED,
1255 ScopeNames.WITH_THUMBNAILS
1258 return Promise.all([
1259 VideoModel.count(countQuery),
1260 VideoModel.scope(findScopes).findAll<MVideoForUser>(findQuery)
1261 ]).then(([ count, rows ]) => {
1269 static async listForApi (options: {
1274 includeLocalVideos: boolean
1276 categoryOneOf?: number[]
1277 licenceOneOf?: number[]
1278 languageOneOf?: string[]
1279 tagsOneOf?: string[]
1280 tagsAllOf?: string[]
1281 filter?: VideoFilter
1283 videoChannelId?: number
1284 followerActorId?: number
1285 videoPlaylistId?: number
1286 trendingDays?: number
1287 user?: MUserAccountId
1288 historyOfUser?: MUserId
1289 countVideos?: boolean
1291 if (options.filter && options.filter === 'all-local' && !options.user.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1292 throw new Error('Try to filter all-local but no user has not the see all videos right')
1295 const query: FindOptions & { where?: null } = {
1296 offset: options.start,
1297 limit: options.count,
1298 order: getVideoSort(options.sort)
1301 let trendingDays: number
1302 if (options.sort.endsWith('trending')) {
1303 trendingDays = CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1305 query.group = 'VideoModel.id'
1308 const serverActor = await getServerActor()
1310 // followerActorId === null has a meaning, so just check undefined
1311 const followerActorId = options.followerActorId !== undefined ? options.followerActorId : serverActor.id
1313 const queryOptions = {
1315 serverAccountId: serverActor.Account.id,
1317 categoryOneOf: options.categoryOneOf,
1318 licenceOneOf: options.licenceOneOf,
1319 languageOneOf: options.languageOneOf,
1320 tagsOneOf: options.tagsOneOf,
1321 tagsAllOf: options.tagsAllOf,
1322 filter: options.filter,
1323 withFiles: options.withFiles,
1324 accountId: options.accountId,
1325 videoChannelId: options.videoChannelId,
1326 videoPlaylistId: options.videoPlaylistId,
1327 includeLocalVideos: options.includeLocalVideos,
1329 historyOfUser: options.historyOfUser,
1333 return VideoModel.getAvailableForApi(query, queryOptions, options.countVideos)
1336 static async searchAndPopulateAccountAndServer (options: {
1337 includeLocalVideos: boolean
1342 startDate?: string // ISO 8601
1343 endDate?: string // ISO 8601
1344 originallyPublishedStartDate?: string
1345 originallyPublishedEndDate?: string
1347 categoryOneOf?: number[]
1348 licenceOneOf?: number[]
1349 languageOneOf?: string[]
1350 tagsOneOf?: string[]
1351 tagsAllOf?: string[]
1352 durationMin?: number // seconds
1353 durationMax?: number // seconds
1354 user?: MUserAccountId
1355 filter?: VideoFilter
1359 if (options.startDate || options.endDate) {
1360 const publishedAtRange = {}
1362 if (options.startDate) publishedAtRange[Op.gte] = options.startDate
1363 if (options.endDate) publishedAtRange[Op.lte] = options.endDate
1365 whereAnd.push({ publishedAt: publishedAtRange })
1368 if (options.originallyPublishedStartDate || options.originallyPublishedEndDate) {
1369 const originallyPublishedAtRange = {}
1371 if (options.originallyPublishedStartDate) originallyPublishedAtRange[Op.gte] = options.originallyPublishedStartDate
1372 if (options.originallyPublishedEndDate) originallyPublishedAtRange[Op.lte] = options.originallyPublishedEndDate
1374 whereAnd.push({ originallyPublishedAt: originallyPublishedAtRange })
1377 if (options.durationMin || options.durationMax) {
1378 const durationRange = {}
1380 if (options.durationMin) durationRange[Op.gte] = options.durationMin
1381 if (options.durationMax) durationRange[Op.lte] = options.durationMax
1383 whereAnd.push({ duration: durationRange })
1386 const attributesInclude = []
1387 const escapedSearch = VideoModel.sequelize.escape(options.search)
1388 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
1389 if (options.search) {
1390 const trigramSearch = {
1392 [Op.in]: Sequelize.literal(
1394 'SELECT "video"."id" FROM "video" ' +
1396 'lower(immutable_unaccent("video"."name")) % lower(immutable_unaccent(' + escapedSearch + ')) OR ' +
1397 'lower(immutable_unaccent("video"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))' +
1399 'SELECT "video"."id" FROM "video" LEFT JOIN "videoTag" ON "videoTag"."videoId" = "video"."id" ' +
1400 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
1401 'WHERE lower("tag"."name") = lower(' + escapedSearch + ')' +
1407 if (validator.isUUID(options.search)) {
1412 uuid: options.search
1417 whereAnd.push(trigramSearch)
1420 attributesInclude.push(createSimilarityAttribute('VideoModel.name', options.search))
1423 // Cannot search on similarity if we don't have a search
1424 if (!options.search) {
1425 attributesInclude.push(
1426 Sequelize.literal('0 as similarity')
1432 include: attributesInclude
1434 offset: options.start,
1435 limit: options.count,
1436 order: getVideoSort(options.sort)
1439 const serverActor = await getServerActor()
1440 const queryOptions = {
1441 followerActorId: serverActor.id,
1442 serverAccountId: serverActor.Account.id,
1443 includeLocalVideos: options.includeLocalVideos,
1445 categoryOneOf: options.categoryOneOf,
1446 licenceOneOf: options.licenceOneOf,
1447 languageOneOf: options.languageOneOf,
1448 tagsOneOf: options.tagsOneOf,
1449 tagsAllOf: options.tagsAllOf,
1451 filter: options.filter,
1455 return VideoModel.getAvailableForApi(query, queryOptions)
1458 static load (id: number | string, t?: Transaction): Bluebird<MVideoThumbnail> {
1459 const where = buildWhereIdOrUUID(id)
1465 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1468 static loadWithBlacklist (id: number | string, t?: Transaction): Bluebird<MVideoThumbnailBlacklist> {
1469 const where = buildWhereIdOrUUID(id)
1475 return VideoModel.scope([
1476 ScopeNames.WITH_THUMBNAILS,
1477 ScopeNames.WITH_BLACKLISTED
1481 static loadImmutableAttributes (id: number | string, t?: Transaction): Bluebird<MVideoImmutable> {
1484 where: buildWhereIdOrUUID(id),
1488 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1491 return ModelCache.Instance.doCache({
1492 cacheType: 'load-video-immutable-id',
1499 static loadWithRights (id: number | string, t?: Transaction): Bluebird<MVideoWithRights> {
1500 const where = buildWhereIdOrUUID(id)
1506 return VideoModel.scope([
1507 ScopeNames.WITH_BLACKLISTED,
1508 ScopeNames.WITH_USER_ID,
1509 ScopeNames.WITH_THUMBNAILS
1513 static loadOnlyId (id: number | string, t?: Transaction): Bluebird<MVideoIdThumbnail> {
1514 const where = buildWhereIdOrUUID(id)
1517 attributes: [ 'id' ],
1522 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1525 static loadWithFiles (id: number | string, t?: Transaction, logging?: boolean): Bluebird<MVideoWithAllFiles> {
1526 const where = buildWhereIdOrUUID(id)
1534 return VideoModel.scope([
1535 ScopeNames.WITH_WEBTORRENT_FILES,
1536 ScopeNames.WITH_STREAMING_PLAYLISTS,
1537 ScopeNames.WITH_THUMBNAILS
1541 static loadByUUID (uuid: string): Bluebird<MVideoThumbnail> {
1548 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1551 static loadByUrl (url: string, transaction?: Transaction): Bluebird<MVideoThumbnail> {
1552 const query: FindOptions = {
1559 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(query)
1562 static loadByUrlImmutableAttributes (url: string, transaction?: Transaction): Bluebird<MVideoImmutable> {
1564 const query: FindOptions = {
1571 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1574 return ModelCache.Instance.doCache({
1575 cacheType: 'load-video-immutable-url',
1582 static loadByUrlAndPopulateAccount (url: string, transaction?: Transaction): Bluebird<MVideoAccountLightBlacklistAllFiles> {
1583 const query: FindOptions = {
1590 return VideoModel.scope([
1591 ScopeNames.WITH_ACCOUNT_DETAILS,
1592 ScopeNames.WITH_WEBTORRENT_FILES,
1593 ScopeNames.WITH_STREAMING_PLAYLISTS,
1594 ScopeNames.WITH_THUMBNAILS,
1595 ScopeNames.WITH_BLACKLISTED
1599 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Transaction, userId?: number): Bluebird<MVideoFullLight> {
1600 const where = buildWhereIdOrUUID(id)
1603 order: [ [ 'Tags', 'name', 'ASC' ] ] as any,
1608 const scopes: (string | ScopeOptions)[] = [
1609 ScopeNames.WITH_TAGS,
1610 ScopeNames.WITH_BLACKLISTED,
1611 ScopeNames.WITH_ACCOUNT_DETAILS,
1612 ScopeNames.WITH_SCHEDULED_UPDATE,
1613 ScopeNames.WITH_WEBTORRENT_FILES,
1614 ScopeNames.WITH_STREAMING_PLAYLISTS,
1615 ScopeNames.WITH_THUMBNAILS
1619 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1627 static loadForGetAPI (parameters: {
1631 }): Bluebird<MVideoDetails> {
1632 const { id, t, userId } = parameters
1633 const where = buildWhereIdOrUUID(id)
1636 order: [ [ 'Tags', 'name', 'ASC' ] ] as any, // FIXME: sequelize typings
1641 const scopes: (string | ScopeOptions)[] = [
1642 ScopeNames.WITH_TAGS,
1643 ScopeNames.WITH_BLACKLISTED,
1644 ScopeNames.WITH_ACCOUNT_DETAILS,
1645 ScopeNames.WITH_SCHEDULED_UPDATE,
1646 ScopeNames.WITH_THUMBNAILS,
1647 { method: [ ScopeNames.WITH_WEBTORRENT_FILES, true ] },
1648 { method: [ ScopeNames.WITH_STREAMING_PLAYLISTS, true ] }
1652 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1660 static async getStats () {
1661 const totalLocalVideos = await VideoModel.count({
1666 const totalVideos = await VideoModel.count()
1668 let totalLocalVideoViews = await VideoModel.sum('views', {
1673 // Sequelize could return null...
1674 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1678 totalLocalVideoViews,
1683 static incrementViews (id: number, views: number) {
1684 return VideoModel.increment('views', {
1692 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1693 // Instances only share videos
1694 const query = 'SELECT 1 FROM "videoShare" ' +
1695 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1696 'WHERE "actorFollow"."actorId" = $followerActorId AND "videoShare"."videoId" = $videoId ' +
1700 type: QueryTypes.SELECT as QueryTypes.SELECT,
1701 bind: { followerActorId, videoId },
1705 return VideoModel.sequelize.query(query, options)
1706 .then(results => results.length === 1)
1709 static bulkUpdateSupportField (videoChannel: MChannel, t: Transaction) {
1712 channelId: videoChannel.id
1717 return VideoModel.update({ support: videoChannel.support }, options)
1720 static getAllIdsFromChannel (videoChannel: MChannelId): Bluebird<number[]> {
1722 attributes: [ 'id' ],
1724 channelId: videoChannel.id
1728 return VideoModel.findAll(query)
1729 .then(videos => videos.map(v => v.id))
1732 // threshold corresponds to how many video the field should have to be returned
1733 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1734 const serverActor = await getServerActor()
1735 const followerActorId = serverActor.id
1737 const scopeOptions: AvailableForListIDsOptions = {
1738 serverAccountId: serverActor.Account.id,
1740 includeLocalVideos: true,
1741 attributesType: 'none' // Don't break aggregation
1744 const query: FindOptions = {
1745 attributes: [ field ],
1748 having: Sequelize.where(
1749 Sequelize.fn('COUNT', Sequelize.col(field)), { [Op.gte]: threshold }
1751 order: [ (this.sequelize as any).random() ]
1754 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST_IDS, scopeOptions ] })
1756 .then(rows => rows.map(r => r[field]))
1759 static buildTrendingQuery (trendingDays: number) {
1763 model: VideoViewModel,
1767 [Op.gte]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1773 private static async getAvailableForApi (
1774 query: FindOptions & { where?: null }, // Forbid where field in query
1775 options: AvailableForListIDsOptions,
1778 const idsScope: ScopeOptions = {
1780 ScopeNames.AVAILABLE_FOR_LIST_IDS, options
1784 // Remove trending sort on count, because it uses a group by
1785 const countOptions = Object.assign({}, options, { trendingDays: undefined })
1786 const countQuery: CountOptions = Object.assign({}, query, { attributes: undefined, group: undefined })
1787 const countScope: ScopeOptions = {
1789 ScopeNames.AVAILABLE_FOR_LIST_IDS, countOptions
1793 const [ count, rows ] = await Promise.all([
1795 ? VideoModel.scope(countScope).count(countQuery)
1796 : Promise.resolve<number>(undefined),
1798 VideoModel.scope(idsScope)
1799 .findAll(Object.assign({}, query, { raw: true }))
1800 .then(rows => rows.map(r => r.id))
1801 .then(ids => VideoModel.loadCompleteVideosForApi(ids, query, options))
1810 private static loadCompleteVideosForApi (ids: number[], query: FindOptions, options: AvailableForListIDsOptions) {
1811 if (ids.length === 0) return []
1813 const secondQuery: FindOptions = {
1816 attributes: query.attributes,
1817 order: [ // Keep original order
1819 ids.map(id => `"VideoModel".id = ${id} DESC`).join(', ')
1824 const apiScope: (string | ScopeOptions)[] = []
1827 apiScope.push({ method: [ ScopeNames.WITH_USER_HISTORY, options.user.id ] })
1832 ScopeNames.FOR_API, {
1834 withFiles: options.withFiles,
1835 videoPlaylistId: options.videoPlaylistId
1840 return VideoModel.scope(apiScope).findAll(secondQuery)
1843 private static isPrivacyForFederation (privacy: VideoPrivacy) {
1844 const castedPrivacy = parseInt(privacy + '', 10)
1846 return castedPrivacy === VideoPrivacy.PUBLIC || castedPrivacy === VideoPrivacy.UNLISTED
1849 static getCategoryLabel (id: number) {
1850 return VIDEO_CATEGORIES[id] || 'Misc'
1853 static getLicenceLabel (id: number) {
1854 return VIDEO_LICENCES[id] || 'Unknown'
1857 static getLanguageLabel (id: string) {
1858 return VIDEO_LANGUAGES[id] || 'Unknown'
1861 static getPrivacyLabel (id: number) {
1862 return VIDEO_PRIVACIES[id] || 'Unknown'
1865 static getStateLabel (id: number) {
1866 return VIDEO_STATES[id] || 'Unknown'
1870 return !!this.VideoBlacklist
1874 return (this.VideoChannel.Account.Actor.Server && this.VideoChannel.Account.Actor.Server.isBlocked()) ||
1875 this.VideoChannel.Account.isBlocked()
1878 getQualityFileBy<T extends MVideoWithFile> (this: T, fun: (files: MVideoFile[], it: (file: MVideoFile) => number) => MVideoFile) {
1879 if (Array.isArray(this.VideoFiles) && this.VideoFiles.length !== 0) {
1880 const file = fun(this.VideoFiles, file => file.resolution)
1882 return Object.assign(file, { Video: this })
1885 // No webtorrent files, try with streaming playlist files
1886 if (Array.isArray(this.VideoStreamingPlaylists) && this.VideoStreamingPlaylists.length !== 0) {
1887 const streamingPlaylistWithVideo = Object.assign(this.VideoStreamingPlaylists[0], { Video: this })
1889 const file = fun(streamingPlaylistWithVideo.VideoFiles, file => file.resolution)
1890 return Object.assign(file, { VideoStreamingPlaylist: streamingPlaylistWithVideo })
1896 getMaxQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1897 return this.getQualityFileBy(maxBy)
1900 getMinQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1901 return this.getQualityFileBy(minBy)
1904 getWebTorrentFile<T extends MVideoWithFile> (this: T, resolution: number): MVideoFileVideo {
1905 if (Array.isArray(this.VideoFiles) === false) return undefined
1907 const file = this.VideoFiles.find(f => f.resolution === resolution)
1908 if (!file) return undefined
1910 return Object.assign(file, { Video: this })
1913 async addAndSaveThumbnail (thumbnail: MThumbnail, transaction: Transaction) {
1914 thumbnail.videoId = this.id
1916 const savedThumbnail = await thumbnail.save({ transaction })
1918 if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = []
1920 // Already have this thumbnail, skip
1921 if (this.Thumbnails.find(t => t.id === savedThumbnail.id)) return
1923 this.Thumbnails.push(savedThumbnail)
1926 generateThumbnailName () {
1927 return this.uuid + '.jpg'
1931 if (Array.isArray(this.Thumbnails) === false) return undefined
1933 return this.Thumbnails.find(t => t.type === ThumbnailType.MINIATURE)
1936 generatePreviewName () {
1937 return this.uuid + '.jpg'
1941 return !!this.getPreview()
1945 if (Array.isArray(this.Thumbnails) === false) return undefined
1947 return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW)
1951 return this.remote === false
1954 getWatchStaticPath () {
1955 return '/videos/watch/' + this.uuid
1958 getEmbedStaticPath () {
1959 return '/videos/embed/' + this.uuid
1962 getMiniatureStaticPath () {
1963 const thumbnail = this.getMiniature()
1964 if (!thumbnail) return null
1966 return join(STATIC_PATHS.THUMBNAILS, thumbnail.filename)
1969 getPreviewStaticPath () {
1970 const preview = this.getPreview()
1971 if (!preview) return null
1973 // We use a local cache, so specify our cache endpoint instead of potential remote URL
1974 return join(LAZY_STATIC_PATHS.PREVIEWS, preview.filename)
1977 toFormattedJSON (this: MVideoFormattable, options?: VideoFormattingJSONOptions): Video {
1978 return videoModelToFormattedJSON(this, options)
1981 toFormattedDetailsJSON (this: MVideoFormattableDetails): VideoDetails {
1982 return videoModelToFormattedDetailsJSON(this)
1985 getFormattedVideoFilesJSON (): VideoFile[] {
1986 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1987 return videoFilesModelToFormattedJSON(this, baseUrlHttp, baseUrlWs, this.VideoFiles)
1990 toActivityPubObject (this: MVideoAP): VideoTorrentObject {
1991 return videoModelToActivityPubObject(this)
1994 getTruncatedDescription () {
1995 if (!this.description) return null
1997 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1998 return peertubeTruncate(this.description, { length: maxLength })
2001 getMaxQualityResolution () {
2002 const file = this.getMaxQualityFile()
2003 const videoOrPlaylist = file.getVideoOrStreamingPlaylist()
2004 const originalFilePath = getVideoFilePath(videoOrPlaylist, file)
2006 return getVideoFileResolution(originalFilePath)
2009 getDescriptionAPIPath () {
2010 return `/api/${API_VERSION}/videos/${this.uuid}/description`
2013 getHLSPlaylist (): MStreamingPlaylistFilesVideo {
2014 if (!this.VideoStreamingPlaylists) return undefined
2016 const playlist = this.VideoStreamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
2017 playlist.Video = this
2022 setHLSPlaylist (playlist: MStreamingPlaylist) {
2023 const toAdd = [ playlist ] as [ VideoStreamingPlaylistModel ]
2025 if (Array.isArray(this.VideoStreamingPlaylists) === false || this.VideoStreamingPlaylists.length === 0) {
2026 this.VideoStreamingPlaylists = toAdd
2030 this.VideoStreamingPlaylists = this.VideoStreamingPlaylists
2031 .filter(s => s.type !== VideoStreamingPlaylistType.HLS)
2035 removeFile (videoFile: MVideoFile, isRedundancy = false) {
2036 const filePath = getVideoFilePath(this, videoFile, isRedundancy)
2037 return remove(filePath)
2038 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
2041 removeTorrent (videoFile: MVideoFile) {
2042 const torrentPath = getTorrentFilePath(this, videoFile)
2043 return remove(torrentPath)
2044 .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err }))
2047 async removeStreamingPlaylistFiles (streamingPlaylist: MStreamingPlaylist, isRedundancy = false) {
2048 const directoryPath = getHLSDirectory(this, isRedundancy)
2050 await remove(directoryPath)
2052 if (isRedundancy !== true) {
2053 const streamingPlaylistWithFiles = streamingPlaylist as MStreamingPlaylistFilesVideo
2054 streamingPlaylistWithFiles.Video = this
2056 if (!Array.isArray(streamingPlaylistWithFiles.VideoFiles)) {
2057 streamingPlaylistWithFiles.VideoFiles = await streamingPlaylistWithFiles.$get('VideoFiles')
2060 // Remove physical files and torrents
2062 streamingPlaylistWithFiles.VideoFiles.map(file => streamingPlaylistWithFiles.removeTorrent(file))
2068 if (this.isOwned()) return false
2070 return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)
2073 hasPrivacyForFederation () {
2074 return VideoModel.isPrivacyForFederation(this.privacy)
2077 isNewVideo (newPrivacy: VideoPrivacy) {
2078 return this.hasPrivacyForFederation() === false && VideoModel.isPrivacyForFederation(newPrivacy) === true
2082 this.changed('updatedAt', true)
2088 return this.privacy === VideoPrivacy.PRIVATE || this.privacy === VideoPrivacy.INTERNAL || !!this.VideoBlacklist
2091 setPrivacy (newPrivacy: VideoPrivacy) {
2092 if (this.privacy === VideoPrivacy.PRIVATE && newPrivacy !== VideoPrivacy.PRIVATE) {
2093 this.publishedAt = new Date()
2096 this.privacy = newPrivacy
2100 return this.privacy === VideoPrivacy.PRIVATE ||
2101 this.privacy === VideoPrivacy.UNLISTED ||
2102 this.privacy === VideoPrivacy.INTERNAL
2105 async publishIfNeededAndSave (t: Transaction) {
2106 if (this.state !== VideoState.PUBLISHED) {
2107 this.state = VideoState.PUBLISHED
2108 this.publishedAt = new Date()
2109 await this.save({ transaction: t })
2118 if (this.isOwned()) {
2120 baseUrlHttp: WEBSERVER.URL,
2121 baseUrlWs: WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT
2126 baseUrlHttp: REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host,
2127 baseUrlWs: REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
2131 getTrackerUrls (baseUrlHttp: string, baseUrlWs: string) {
2132 return [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
2135 getTorrentUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2136 return baseUrlHttp + STATIC_PATHS.TORRENTS + getTorrentFileName(this, videoFile)
2139 getTorrentDownloadUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2140 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + getTorrentFileName(this, videoFile)
2143 getVideoFileUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2144 return baseUrlHttp + STATIC_PATHS.WEBSEED + getVideoFilename(this, videoFile)
2147 getVideoRedundancyUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2148 return baseUrlHttp + STATIC_PATHS.REDUNDANCY + getVideoFilename(this, videoFile)
2151 getVideoFileDownloadUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2152 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + getVideoFilename(this, videoFile)
2155 getBandwidthBits (videoFile: MVideoFile) {
2156 return Math.ceil((videoFile.size * 8) / this.duration)