1 import * as Bluebird from 'bluebird'
2 import { maxBy } from 'lodash'
3 import * as magnetUtil from 'magnet-uri'
4 import * as parseTorrent from 'parse-torrent'
5 import { join } from 'path'
38 } from 'sequelize-typescript'
39 import { UserRight, VideoPrivacy, VideoState } from '../../../shared'
40 import { VideoTorrentObject } from '../../../shared/models/activitypub/objects'
41 import { Video, VideoDetails, VideoFile } from '../../../shared/models/videos'
42 import { VideoFilter } from '../../../shared/models/videos/video-query.type'
43 import { createTorrentPromise, peertubeTruncate } from '../../helpers/core-utils'
44 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
45 import { isArray, isBooleanValid } from '../../helpers/custom-validators/misc'
48 isVideoDescriptionValid,
56 } from '../../helpers/custom-validators/videos'
57 import { getVideoFileResolution } from '../../helpers/ffmpeg-utils'
58 import { logger } from '../../helpers/logger'
59 import { getServerActor } from '../../helpers/utils'
64 HLS_REDUNDANCY_DIRECTORY,
65 HLS_STREAMING_PLAYLIST_DIRECTORY,
67 STATIC_DOWNLOAD_PATHS,
75 } from '../../initializers/constants'
76 import { sendDeleteVideo } from '../../lib/activitypub/send'
77 import { AccountModel } from '../account/account'
78 import { AccountVideoRateModel } from '../account/account-video-rate'
79 import { ActorModel } from '../activitypub/actor'
80 import { AvatarModel } from '../avatar/avatar'
81 import { ServerModel } from '../server/server'
83 buildBlockedAccountSQL,
84 buildTrigramSearchIndex,
86 createSimilarityAttribute,
91 import { TagModel } from './tag'
92 import { VideoAbuseModel } from './video-abuse'
93 import { ScopeNames as VideoChannelScopeNames, VideoChannelModel } from './video-channel'
94 import { VideoCommentModel } from './video-comment'
95 import { VideoFileModel } from './video-file'
96 import { VideoShareModel } from './video-share'
97 import { VideoTagModel } from './video-tag'
98 import { ScheduleVideoUpdateModel } from './schedule-video-update'
99 import { VideoCaptionModel } from './video-caption'
100 import { VideoBlacklistModel } from './video-blacklist'
101 import { remove, writeFile } from 'fs-extra'
102 import { VideoViewModel } from './video-views'
103 import { VideoRedundancyModel } from '../redundancy/video-redundancy'
105 videoFilesModelToFormattedJSON,
106 VideoFormattingJSONOptions,
107 videoModelToActivityPubObject,
108 videoModelToFormattedDetailsJSON,
109 videoModelToFormattedJSON
110 } from './video-format-utils'
111 import { UserVideoHistoryModel } from '../account/user-video-history'
112 import { UserModel } from '../account/user'
113 import { VideoImportModel } from './video-import'
114 import { VideoStreamingPlaylistModel } from './video-streaming-playlist'
115 import { VideoPlaylistElementModel } from './video-playlist-element'
116 import { CONFIG } from '../../initializers/config'
117 import { ThumbnailModel } from './thumbnail'
118 import { ThumbnailType } from '../../../shared/models/videos/thumbnail.type'
120 // FIXME: Define indexes here because there is an issue with TS and Sequelize.literal when called directly in the annotation
121 const indexes: (ModelIndexesOptions & { where?: WhereOptions })[] = [
122 buildTrigramSearchIndex('video_name_trigram', 'name'),
124 { fields: [ 'createdAt' ] },
125 { fields: [ 'publishedAt' ] },
126 { fields: [ 'duration' ] },
127 { fields: [ 'views' ] },
128 { fields: [ 'channelId' ] },
130 fields: [ 'originallyPublishedAt' ],
132 originallyPublishedAt: {
138 fields: [ 'category' ], // We don't care videos with an unknown category
146 fields: [ 'licence' ], // We don't care videos with an unknown licence
154 fields: [ 'language' ], // We don't care videos with an unknown language
162 fields: [ 'nsfw' ], // Most of the videos are not NSFW
168 fields: [ 'remote' ], // Only index local videos
183 export enum ScopeNames {
184 AVAILABLE_FOR_LIST_IDS = 'AVAILABLE_FOR_LIST_IDS',
186 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
187 WITH_TAGS = 'WITH_TAGS',
188 WITH_FILES = 'WITH_FILES',
189 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
190 WITH_BLACKLISTED = 'WITH_BLACKLISTED',
191 WITH_USER_HISTORY = 'WITH_USER_HISTORY',
192 WITH_STREAMING_PLAYLISTS = 'WITH_STREAMING_PLAYLISTS',
193 WITH_USER_ID = 'WITH_USER_ID',
194 WITH_THUMBNAILS = 'WITH_THUMBNAILS'
197 type ForAPIOptions = {
200 videoPlaylistId?: number
205 type AvailableForListIDsOptions = {
206 serverAccountId: number
207 followerActorId: number
208 includeLocalVideos: boolean
213 categoryOneOf?: number[]
215 licenceOneOf?: number[]
216 languageOneOf?: string[]
223 videoChannelId?: number
225 videoPlaylistId?: number
227 trendingDays?: number
229 historyOfUser?: UserModel
233 [ ScopeNames.FOR_API ]: (options: ForAPIOptions) => {
234 const query: FindOptions = {
237 [ Op.in ]: options.ids // FIXME: sequelize ANY seems broken
242 model: VideoChannelModel.scope({ method: [ VideoChannelScopeNames.SUMMARY, true ] }),
246 attributes: [ 'type', 'filename' ],
247 model: ThumbnailModel,
253 if (options.withFiles === true) {
255 model: VideoFileModel.unscoped(),
260 if (options.videoPlaylistId) {
262 model: VideoPlaylistElementModel.unscoped(),
265 videoPlaylistId: options.videoPlaylistId
272 [ ScopeNames.AVAILABLE_FOR_LIST_IDS ]: (options: AvailableForListIDsOptions) => {
273 const attributes = options.withoutId === true ? [] : [ 'id' ]
275 const query: FindOptions = {
282 [ Op.notIn ]: Sequelize.literal(
283 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
289 [ Op.notIn ]: Sequelize.literal(
291 'SELECT id FROM "videoChannel" WHERE "accountId" IN (' +
292 buildBlockedAccountSQL(options.serverAccountId, options.user ? options.user.Account.id : undefined) +
301 // Only list public/published videos
302 if (!options.filter || options.filter !== 'all-local') {
303 const privacyWhere = {
304 // Always list public videos
305 privacy: VideoPrivacy.PUBLIC,
306 // Always list published videos, or videos that are being transcoded but on which we don't want to wait for transcoding
309 state: VideoState.PUBLISHED
313 state: VideoState.TO_TRANSCODE,
314 waitTranscoding: false
320 Object.assign(query.where, privacyWhere)
323 if (options.videoPlaylistId) {
326 model: VideoPlaylistElementModel.unscoped(),
329 videoPlaylistId: options.videoPlaylistId
333 query.subQuery = false
336 if (options.filter || 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.filter || options.accountId) {
350 const accountInclude: IncludeOptions = {
352 model: AccountModel.unscoped(),
356 if (options.filter) {
357 accountInclude.include = [
360 model: ActorModel.unscoped(),
362 where: VideoModel.buildActorWhereWithFilter(options.filter)
367 if (options.accountId) {
368 accountInclude.where = { id: options.accountId }
371 videoChannelInclude.include = [ accountInclude ]
374 query.include.push(videoChannelInclude)
377 if (options.followerActorId) {
378 let localVideosReq = ''
379 if (options.includeLocalVideos === true) {
380 localVideosReq = ' UNION ALL ' +
381 'SELECT "video"."id" AS "id" FROM "video" ' +
382 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
383 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
384 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
385 'WHERE "actor"."serverId" IS NULL'
388 // Force actorId to be a number to avoid SQL injections
389 const actorIdNumber = parseInt(options.followerActorId.toString(), 10)
390 query.where[ 'id' ][ Op.and ].push({
391 [ Op.in ]: Sequelize.literal(
393 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
394 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
395 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
397 'SELECT "video"."id" AS "id" FROM "video" ' +
398 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
399 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
400 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
401 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
402 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
409 if (options.withFiles === true) {
410 query.where[ 'id' ][ Op.and ].push({
411 [ Op.in ]: Sequelize.literal(
412 '(SELECT "videoId" FROM "videoFile")'
417 // FIXME: issues with sequelize count when making a join on n:m relation, so we just make a IN()
418 if (options.tagsAllOf || options.tagsOneOf) {
419 const createTagsIn = (tags: string[]) => {
420 return tags.map(t => VideoModel.sequelize.escape(t))
424 if (options.tagsOneOf) {
425 query.where[ 'id' ][ Op.and ].push({
426 [ Op.in ]: Sequelize.literal(
428 'SELECT "videoId" FROM "videoTag" ' +
429 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
430 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsOneOf) + ')' +
436 if (options.tagsAllOf) {
437 query.where[ 'id' ][ Op.and ].push({
438 [ Op.in ]: Sequelize.literal(
440 'SELECT "videoId" FROM "videoTag" ' +
441 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
442 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsAllOf) + ')' +
443 'GROUP BY "videoTag"."videoId" HAVING COUNT(*) = ' + options.tagsAllOf.length +
450 if (options.nsfw === true || options.nsfw === false) {
451 query.where[ 'nsfw' ] = options.nsfw
454 if (options.categoryOneOf) {
455 query.where[ 'category' ] = {
456 [ Op.or ]: options.categoryOneOf
460 if (options.licenceOneOf) {
461 query.where[ 'licence' ] = {
462 [ Op.or ]: options.licenceOneOf
466 if (options.languageOneOf) {
467 query.where[ 'language' ] = {
468 [ Op.or ]: options.languageOneOf
472 if (options.trendingDays) {
473 query.include.push(VideoModel.buildTrendingQuery(options.trendingDays))
475 query.subQuery = false
478 if (options.historyOfUser) {
480 model: UserVideoHistoryModel,
483 userId: options.historyOfUser.id
487 // Even if the relation is n:m, we know that a user only have 0..1 video history
488 // So we won't have multiple rows for the same video
489 // Without this, we would not be able to sort on "updatedAt" column of UserVideoHistoryModel
490 query.subQuery = false
495 [ ScopeNames.WITH_THUMBNAILS ]: {
498 model: ThumbnailModel,
503 [ ScopeNames.WITH_USER_ID ]: {
506 attributes: [ 'accountId' ],
507 model: VideoChannelModel.unscoped(),
511 attributes: [ 'userId' ],
512 model: AccountModel.unscoped(),
519 [ ScopeNames.WITH_ACCOUNT_DETAILS ]: {
522 model: VideoChannelModel.unscoped(),
527 exclude: [ 'privateKey', 'publicKey' ]
529 model: ActorModel.unscoped(),
533 attributes: [ 'host' ],
534 model: ServerModel.unscoped(),
538 model: AvatarModel.unscoped(),
544 model: AccountModel.unscoped(),
548 model: ActorModel.unscoped(),
550 exclude: [ 'privateKey', 'publicKey' ]
555 attributes: [ 'host' ],
556 model: ServerModel.unscoped(),
560 model: AvatarModel.unscoped(),
571 [ ScopeNames.WITH_TAGS ]: {
572 include: [ TagModel ]
574 [ ScopeNames.WITH_BLACKLISTED ]: {
577 attributes: [ 'id', 'reason' ],
578 model: VideoBlacklistModel,
583 [ ScopeNames.WITH_FILES ]: (withRedundancies = false) => {
584 let subInclude: any[] = []
586 if (withRedundancies === true) {
589 attributes: [ 'fileUrl' ],
590 model: VideoRedundancyModel.unscoped(),
599 model: VideoFileModel.unscoped(),
600 separate: true, // We may have multiple files, having multiple redundancies so let's separate this join
607 [ ScopeNames.WITH_STREAMING_PLAYLISTS ]: (withRedundancies = false) => {
608 let subInclude: any[] = []
610 if (withRedundancies === true) {
613 attributes: [ 'fileUrl' ],
614 model: VideoRedundancyModel.unscoped(),
623 model: VideoStreamingPlaylistModel.unscoped(),
624 separate: true, // We may have multiple streaming playlists, having multiple redundancies so let's separate this join
631 [ ScopeNames.WITH_SCHEDULED_UPDATE ]: {
634 model: ScheduleVideoUpdateModel.unscoped(),
639 [ ScopeNames.WITH_USER_HISTORY ]: (userId: number) => {
643 attributes: [ 'currentTime' ],
644 model: UserVideoHistoryModel.unscoped(),
658 export class VideoModel extends Model<VideoModel> {
661 @Default(DataType.UUIDV4)
663 @Column(DataType.UUID)
667 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
673 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category', true))
679 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence', true))
685 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language', true))
686 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
690 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
695 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
701 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description', true))
702 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
707 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support', true))
708 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
712 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
742 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
743 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
748 commentsEnabled: boolean
752 downloadEnabled: boolean
756 waitTranscoding: boolean
760 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
771 @Default(DataType.NOW)
778 originallyPublishedAt: Date
780 @ForeignKey(() => VideoChannelModel)
784 @BelongsTo(() => VideoChannelModel, {
790 VideoChannel: VideoChannelModel
792 @BelongsToMany(() => TagModel, {
793 foreignKey: 'videoId',
794 through: () => VideoTagModel,
799 @HasMany(() => ThumbnailModel, {
807 Thumbnails: ThumbnailModel[]
809 @HasMany(() => VideoPlaylistElementModel, {
816 VideoPlaylistElements: VideoPlaylistElementModel[]
818 @HasMany(() => VideoAbuseModel, {
825 VideoAbuses: VideoAbuseModel[]
827 @HasMany(() => VideoFileModel, {
835 VideoFiles: VideoFileModel[]
837 @HasMany(() => VideoStreamingPlaylistModel, {
845 VideoStreamingPlaylists: VideoStreamingPlaylistModel[]
847 @HasMany(() => VideoShareModel, {
854 VideoShares: VideoShareModel[]
856 @HasMany(() => AccountVideoRateModel, {
863 AccountVideoRates: AccountVideoRateModel[]
865 @HasMany(() => VideoCommentModel, {
873 VideoComments: VideoCommentModel[]
875 @HasMany(() => VideoViewModel, {
882 VideoViews: VideoViewModel[]
884 @HasMany(() => UserVideoHistoryModel, {
891 UserVideoHistories: UserVideoHistoryModel[]
893 @HasOne(() => ScheduleVideoUpdateModel, {
900 ScheduleVideoUpdate: ScheduleVideoUpdateModel
902 @HasOne(() => VideoBlacklistModel, {
909 VideoBlacklist: VideoBlacklistModel
911 @HasOne(() => VideoImportModel, {
918 VideoImport: VideoImportModel
920 @HasMany(() => VideoCaptionModel, {
927 [ 'separate' as any ]: true
929 VideoCaptions: VideoCaptionModel[]
932 static async sendDelete (instance: VideoModel, options) {
933 if (instance.isOwned()) {
934 if (!instance.VideoChannel) {
935 instance.VideoChannel = await instance.$get('VideoChannel', {
939 include: [ ActorModel ]
942 transaction: options.transaction
943 }) as VideoChannelModel
946 return sendDeleteVideo(instance, options.transaction)
953 static async removeFiles (instance: VideoModel) {
954 const tasks: Promise<any>[] = []
956 logger.info('Removing files of video %s.', instance.url)
958 if (instance.isOwned()) {
959 if (!Array.isArray(instance.VideoFiles)) {
960 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
963 // Remove physical files and torrents
964 instance.VideoFiles.forEach(file => {
965 tasks.push(instance.removeFile(file))
966 tasks.push(instance.removeTorrent(file))
969 // Remove playlists file
970 tasks.push(instance.removeStreamingPlaylist())
973 // Do not wait video deletion because we could be in a transaction
976 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
982 static listLocal () {
989 return VideoModel.scope([
990 ScopeNames.WITH_FILES,
991 ScopeNames.WITH_STREAMING_PLAYLISTS,
992 ScopeNames.WITH_THUMBNAILS
996 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
997 function getRawQuery (select: string) {
998 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
999 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
1000 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
1001 'WHERE "Account"."actorId" = ' + actorId
1002 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
1003 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
1004 'WHERE "VideoShare"."actorId" = ' + actorId
1006 return `(${queryVideo}) UNION (${queryVideoShare})`
1009 const rawQuery = getRawQuery('"Video"."id"')
1010 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
1016 order: getVideoSort('createdAt', [ 'Tags', 'name', 'ASC' ] as any), // FIXME: sequelize typings
1019 [ Op.in ]: Sequelize.literal('(' + rawQuery + ')')
1022 { privacy: VideoPrivacy.PUBLIC },
1023 { privacy: VideoPrivacy.UNLISTED }
1028 attributes: [ 'language' ],
1029 model: VideoCaptionModel.unscoped(),
1033 attributes: [ 'id', 'url' ],
1034 model: VideoShareModel.unscoped(),
1036 // We only want videos shared by this actor
1051 attributes: [ 'id', 'url' ],
1052 model: ActorModel.unscoped()
1057 model: VideoChannelModel.unscoped(),
1061 attributes: [ 'name' ],
1062 model: AccountModel.unscoped(),
1066 attributes: [ 'id', 'url', 'followersUrl' ],
1067 model: ActorModel.unscoped(),
1073 attributes: [ 'id', 'url', 'followersUrl' ],
1074 model: ActorModel.unscoped(),
1084 return Bluebird.all([
1085 VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findAll(query),
1086 VideoModel.sequelize.query<{ total: string }>(rawCountQuery, { type: QueryTypes.SELECT })
1087 ]).then(([ rows, totals ]) => {
1088 // totals: totalVideos + totalVideoShares
1090 let totalVideoShares = 0
1091 if (totals[ 0 ]) totalVideos = parseInt(totals[ 0 ].total, 10)
1092 if (totals[ 1 ]) totalVideoShares = parseInt(totals[ 1 ].total, 10)
1094 const total = totalVideos + totalVideoShares
1102 static listUserVideosForApi (accountId: number, start: number, count: number, sort: string, withFiles = false) {
1103 function buildBaseQuery (): FindOptions {
1107 order: getVideoSort(sort),
1110 model: VideoChannelModel,
1114 model: AccountModel,
1126 const countQuery = buildBaseQuery()
1127 const findQuery = buildBaseQuery()
1129 findQuery.include.push({
1130 model: ScheduleVideoUpdateModel,
1134 findQuery.include.push({
1135 model: VideoBlacklistModel,
1139 if (withFiles === true) {
1140 findQuery.include.push({
1141 model: VideoFileModel.unscoped(),
1146 return Promise.all([
1147 VideoModel.count(countQuery),
1148 VideoModel.findAll(findQuery)
1149 ]).then(([ count, rows ]) => {
1157 static async listForApi (options: {
1162 includeLocalVideos: boolean,
1164 categoryOneOf?: number[],
1165 licenceOneOf?: number[],
1166 languageOneOf?: string[],
1167 tagsOneOf?: string[],
1168 tagsAllOf?: string[],
1169 filter?: VideoFilter,
1171 videoChannelId?: number,
1172 followerActorId?: number
1173 videoPlaylistId?: number,
1174 trendingDays?: number,
1176 historyOfUser?: UserModel
1177 }, countVideos = true) {
1178 if (options.filter && options.filter === 'all-local' && !options.user.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1179 throw new Error('Try to filter all-local but no user has not the see all videos right')
1182 const query: FindOptions = {
1183 offset: options.start,
1184 limit: options.count,
1185 order: getVideoSort(options.sort)
1188 let trendingDays: number
1189 if (options.sort.endsWith('trending')) {
1190 trendingDays = CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1192 query.group = 'VideoModel.id'
1195 const serverActor = await getServerActor()
1197 // followerActorId === null has a meaning, so just check undefined
1198 const followerActorId = options.followerActorId !== undefined ? options.followerActorId : serverActor.id
1200 const queryOptions = {
1202 serverAccountId: serverActor.Account.id,
1204 categoryOneOf: options.categoryOneOf,
1205 licenceOneOf: options.licenceOneOf,
1206 languageOneOf: options.languageOneOf,
1207 tagsOneOf: options.tagsOneOf,
1208 tagsAllOf: options.tagsAllOf,
1209 filter: options.filter,
1210 withFiles: options.withFiles,
1211 accountId: options.accountId,
1212 videoChannelId: options.videoChannelId,
1213 videoPlaylistId: options.videoPlaylistId,
1214 includeLocalVideos: options.includeLocalVideos,
1216 historyOfUser: options.historyOfUser,
1220 return VideoModel.getAvailableForApi(query, queryOptions, countVideos)
1223 static async searchAndPopulateAccountAndServer (options: {
1224 includeLocalVideos: boolean
1229 startDate?: string // ISO 8601
1230 endDate?: string // ISO 8601
1231 originallyPublishedStartDate?: string
1232 originallyPublishedEndDate?: string
1234 categoryOneOf?: number[]
1235 licenceOneOf?: number[]
1236 languageOneOf?: string[]
1237 tagsOneOf?: string[]
1238 tagsAllOf?: string[]
1239 durationMin?: number // seconds
1240 durationMax?: number // seconds
1242 filter?: VideoFilter
1246 if (options.startDate || options.endDate) {
1247 const publishedAtRange = {}
1249 if (options.startDate) publishedAtRange[ Op.gte ] = options.startDate
1250 if (options.endDate) publishedAtRange[ Op.lte ] = options.endDate
1252 whereAnd.push({ publishedAt: publishedAtRange })
1255 if (options.originallyPublishedStartDate || options.originallyPublishedEndDate) {
1256 const originallyPublishedAtRange = {}
1258 if (options.originallyPublishedStartDate) originallyPublishedAtRange[ Op.gte ] = options.originallyPublishedStartDate
1259 if (options.originallyPublishedEndDate) originallyPublishedAtRange[ Op.lte ] = options.originallyPublishedEndDate
1261 whereAnd.push({ originallyPublishedAt: originallyPublishedAtRange })
1264 if (options.durationMin || options.durationMax) {
1265 const durationRange = {}
1267 if (options.durationMin) durationRange[ Op.gte ] = options.durationMin
1268 if (options.durationMax) durationRange[ Op.lte ] = options.durationMax
1270 whereAnd.push({ duration: durationRange })
1273 const attributesInclude = []
1274 const escapedSearch = VideoModel.sequelize.escape(options.search)
1275 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
1276 if (options.search) {
1280 [ Op.in ]: Sequelize.literal(
1282 'SELECT "video"."id" FROM "video" ' +
1284 'lower(immutable_unaccent("video"."name")) % lower(immutable_unaccent(' + escapedSearch + ')) OR ' +
1285 'lower(immutable_unaccent("video"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))' +
1287 'SELECT "video"."id" FROM "video" LEFT JOIN "videoTag" ON "videoTag"."videoId" = "video"."id" ' +
1288 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
1289 'WHERE "tag"."name" = ' + escapedSearch +
1296 attributesInclude.push(createSimilarityAttribute('VideoModel.name', options.search))
1299 // Cannot search on similarity if we don't have a search
1300 if (!options.search) {
1301 attributesInclude.push(
1302 Sequelize.literal('0 as similarity')
1306 const query: FindOptions = {
1308 include: attributesInclude
1310 offset: options.start,
1311 limit: options.count,
1312 order: getVideoSort(options.sort),
1314 [ Op.and ]: whereAnd
1318 const serverActor = await getServerActor()
1319 const queryOptions = {
1320 followerActorId: serverActor.id,
1321 serverAccountId: serverActor.Account.id,
1322 includeLocalVideos: options.includeLocalVideos,
1324 categoryOneOf: options.categoryOneOf,
1325 licenceOneOf: options.licenceOneOf,
1326 languageOneOf: options.languageOneOf,
1327 tagsOneOf: options.tagsOneOf,
1328 tagsAllOf: options.tagsAllOf,
1330 filter: options.filter
1333 return VideoModel.getAvailableForApi(query, queryOptions)
1336 static load (id: number | string, t?: Transaction) {
1337 const where = buildWhereIdOrUUID(id)
1343 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1346 static loadWithRights (id: number | string, t?: Transaction) {
1347 const where = buildWhereIdOrUUID(id)
1353 return VideoModel.scope([
1354 ScopeNames.WITH_BLACKLISTED,
1355 ScopeNames.WITH_USER_ID,
1356 ScopeNames.WITH_THUMBNAILS
1360 static loadOnlyId (id: number | string, t?: Transaction) {
1361 const where = buildWhereIdOrUUID(id)
1364 attributes: [ 'id' ],
1369 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1372 static loadWithFiles (id: number, t?: Transaction, logging?: boolean) {
1373 return VideoModel.scope([
1374 ScopeNames.WITH_FILES,
1375 ScopeNames.WITH_STREAMING_PLAYLISTS,
1376 ScopeNames.WITH_THUMBNAILS
1377 ]).findByPk(id, { transaction: t, logging })
1380 static loadByUUIDWithFile (uuid: string) {
1387 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1390 static loadByUrl (url: string, transaction?: Transaction) {
1391 const query: FindOptions = {
1398 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(query)
1401 static loadByUrlAndPopulateAccount (url: string, transaction?: Transaction) {
1402 const query: FindOptions = {
1409 return VideoModel.scope([
1410 ScopeNames.WITH_ACCOUNT_DETAILS,
1411 ScopeNames.WITH_FILES,
1412 ScopeNames.WITH_STREAMING_PLAYLISTS,
1413 ScopeNames.WITH_THUMBNAILS
1417 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Transaction, userId?: number) {
1418 const where = buildWhereIdOrUUID(id)
1421 order: [ [ 'Tags', 'name', 'ASC' ] ] as any,
1426 const scopes: (string | ScopeOptions)[] = [
1427 ScopeNames.WITH_TAGS,
1428 ScopeNames.WITH_BLACKLISTED,
1429 ScopeNames.WITH_ACCOUNT_DETAILS,
1430 ScopeNames.WITH_SCHEDULED_UPDATE,
1431 ScopeNames.WITH_FILES,
1432 ScopeNames.WITH_STREAMING_PLAYLISTS,
1433 ScopeNames.WITH_THUMBNAILS
1437 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1445 static loadForGetAPI (id: number | string, t?: Transaction, userId?: number) {
1446 const where = buildWhereIdOrUUID(id)
1449 order: [ [ 'Tags', 'name', 'ASC' ] ] as any, // FIXME: sequelize typings
1454 const scopes: (string | ScopeOptions)[] = [
1455 ScopeNames.WITH_TAGS,
1456 ScopeNames.WITH_BLACKLISTED,
1457 ScopeNames.WITH_ACCOUNT_DETAILS,
1458 ScopeNames.WITH_SCHEDULED_UPDATE,
1459 ScopeNames.WITH_THUMBNAILS,
1460 { method: [ ScopeNames.WITH_FILES, true ] },
1461 { method: [ ScopeNames.WITH_STREAMING_PLAYLISTS, true ] }
1465 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1473 static async getStats () {
1474 const totalLocalVideos = await VideoModel.count({
1479 const totalVideos = await VideoModel.count()
1481 let totalLocalVideoViews = await VideoModel.sum('views', {
1486 // Sequelize could return null...
1487 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1491 totalLocalVideoViews,
1496 static incrementViews (id: number, views: number) {
1497 return VideoModel.increment('views', {
1505 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1506 // Instances only share videos
1507 const query = 'SELECT 1 FROM "videoShare" ' +
1508 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1509 'WHERE "actorFollow"."actorId" = $followerActorId AND "videoShare"."videoId" = $videoId ' +
1513 type: QueryTypes.SELECT,
1514 bind: { followerActorId, videoId },
1518 return VideoModel.sequelize.query(query, options)
1519 .then(results => results.length === 1)
1522 // threshold corresponds to how many video the field should have to be returned
1523 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1524 const serverActor = await getServerActor()
1525 const followerActorId = serverActor.id
1527 const scopeOptions: AvailableForListIDsOptions = {
1528 serverAccountId: serverActor.Account.id,
1530 includeLocalVideos: true,
1531 withoutId: true // Don't break aggregation
1534 const query: FindOptions = {
1535 attributes: [ field ],
1538 having: Sequelize.where(
1539 Sequelize.fn('COUNT', Sequelize.col(field)), { [ Op.gte ]: threshold }
1541 order: [ (this.sequelize as any).random() ]
1544 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST_IDS, scopeOptions ] })
1546 .then(rows => rows.map(r => r[ field ]))
1549 static buildTrendingQuery (trendingDays: number) {
1553 model: VideoViewModel,
1557 [ Op.gte ]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1563 private static buildActorWhereWithFilter (filter?: VideoFilter) {
1564 if (filter && (filter === 'local' || filter === 'all-local')) {
1573 private static async getAvailableForApi (
1575 options: AvailableForListIDsOptions,
1578 const idsScope: ScopeOptions = {
1580 ScopeNames.AVAILABLE_FOR_LIST_IDS, options
1584 // Remove trending sort on count, because it uses a group by
1585 const countOptions = Object.assign({}, options, { trendingDays: undefined })
1586 const countQuery: CountOptions = Object.assign({}, query, { attributes: undefined, group: undefined })
1587 const countScope: ScopeOptions = {
1589 ScopeNames.AVAILABLE_FOR_LIST_IDS, countOptions
1593 const [ count, rowsId ] = await Promise.all([
1594 countVideos ? VideoModel.scope(countScope).count(countQuery) : Promise.resolve<number>(undefined),
1595 VideoModel.scope(idsScope).findAll(query)
1597 const ids = rowsId.map(r => r.id)
1599 if (ids.length === 0) return { data: [], total: count }
1601 const secondQuery: FindOptions = {
1604 attributes: query.attributes,
1605 order: [ // Keep original order
1607 ids.map(id => `"VideoModel".id = ${id} DESC`).join(', ')
1612 const apiScope: (string | ScopeOptions)[] = []
1615 apiScope.push({ method: [ ScopeNames.WITH_USER_HISTORY, options.user.id ] })
1620 ScopeNames.FOR_API, {
1622 withFiles: options.withFiles,
1623 videoPlaylistId: options.videoPlaylistId
1628 const rows = await VideoModel.scope(apiScope).findAll(secondQuery)
1636 static getCategoryLabel (id: number) {
1637 return VIDEO_CATEGORIES[ id ] || 'Misc'
1640 static getLicenceLabel (id: number) {
1641 return VIDEO_LICENCES[ id ] || 'Unknown'
1644 static getLanguageLabel (id: string) {
1645 return VIDEO_LANGUAGES[ id ] || 'Unknown'
1648 static getPrivacyLabel (id: number) {
1649 return VIDEO_PRIVACIES[ id ] || 'Unknown'
1652 static getStateLabel (id: number) {
1653 return VIDEO_STATES[ id ] || 'Unknown'
1656 getOriginalFile () {
1657 if (Array.isArray(this.VideoFiles) === false) return undefined
1659 // The original file is the file that have the higher resolution
1660 return maxBy(this.VideoFiles, file => file.resolution)
1663 async addAndSaveThumbnail (thumbnail: ThumbnailModel, transaction: Transaction) {
1664 thumbnail.videoId = this.id
1666 const savedThumbnail = await thumbnail.save({ transaction })
1668 if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = []
1670 // Already have this thumbnail, skip
1671 if (this.Thumbnails.find(t => t.id === savedThumbnail.id)) return
1673 this.Thumbnails.push(savedThumbnail)
1676 getVideoFilename (videoFile: VideoFileModel) {
1677 return this.uuid + '-' + videoFile.resolution + videoFile.extname
1680 generateThumbnailName () {
1681 return this.uuid + '.jpg'
1685 if (Array.isArray(this.Thumbnails) === false) return undefined
1687 return this.Thumbnails.find(t => t.type === ThumbnailType.MINIATURE)
1690 generatePreviewName () {
1691 return this.uuid + '.jpg'
1695 if (Array.isArray(this.Thumbnails) === false) return undefined
1697 return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW)
1700 getTorrentFileName (videoFile: VideoFileModel) {
1701 const extension = '.torrent'
1702 return this.uuid + '-' + videoFile.resolution + extension
1706 return this.remote === false
1709 getTorrentFilePath (videoFile: VideoFileModel) {
1710 return join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1713 getVideoFilePath (videoFile: VideoFileModel) {
1714 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1717 async createTorrentAndSetInfoHash (videoFile: VideoFileModel) {
1719 // Keep the extname, it's used by the client to stream the file inside a web browser
1720 name: `${this.name} ${videoFile.resolution}p${videoFile.extname}`,
1721 createdBy: 'PeerTube',
1723 [ WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT + '/tracker/socket' ],
1724 [ WEBSERVER.URL + '/tracker/announce' ]
1726 urlList: [ WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile) ]
1729 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
1731 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1732 logger.info('Creating torrent %s.', filePath)
1734 await writeFile(filePath, torrent)
1736 const parsedTorrent = parseTorrent(torrent)
1737 videoFile.infoHash = parsedTorrent.infoHash
1740 getWatchStaticPath () {
1741 return '/videos/watch/' + this.uuid
1744 getEmbedStaticPath () {
1745 return '/videos/embed/' + this.uuid
1748 getMiniatureStaticPath () {
1749 const thumbnail = this.getMiniature()
1750 if (!thumbnail) return null
1752 return join(STATIC_PATHS.THUMBNAILS, thumbnail.filename)
1755 getPreviewStaticPath () {
1756 const preview = this.getPreview()
1757 if (!preview) return null
1759 // We use a local cache, so specify our cache endpoint instead of potential remote URL
1760 return join(STATIC_PATHS.PREVIEWS, preview.filename)
1763 toFormattedJSON (options?: VideoFormattingJSONOptions): Video {
1764 return videoModelToFormattedJSON(this, options)
1767 toFormattedDetailsJSON (): VideoDetails {
1768 return videoModelToFormattedDetailsJSON(this)
1771 getFormattedVideoFilesJSON (): VideoFile[] {
1772 return videoFilesModelToFormattedJSON(this, this.VideoFiles)
1775 toActivityPubObject (): VideoTorrentObject {
1776 return videoModelToActivityPubObject(this)
1779 getTruncatedDescription () {
1780 if (!this.description) return null
1782 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1783 return peertubeTruncate(this.description, maxLength)
1786 getOriginalFileResolution () {
1787 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1789 return getVideoFileResolution(originalFilePath)
1792 getDescriptionAPIPath () {
1793 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1796 removeFile (videoFile: VideoFileModel, isRedundancy = false) {
1797 const baseDir = isRedundancy ? CONFIG.STORAGE.REDUNDANCY_DIR : CONFIG.STORAGE.VIDEOS_DIR
1799 const filePath = join(baseDir, this.getVideoFilename(videoFile))
1800 return remove(filePath)
1801 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1804 removeTorrent (videoFile: VideoFileModel) {
1805 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1806 return remove(torrentPath)
1807 .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err }))
1810 removeStreamingPlaylist (isRedundancy = false) {
1811 const baseDir = isRedundancy ? HLS_REDUNDANCY_DIRECTORY : HLS_STREAMING_PLAYLIST_DIRECTORY
1813 const filePath = join(baseDir, this.uuid)
1814 return remove(filePath)
1815 .catch(err => logger.warn('Cannot delete playlist directory %s.', filePath, { err }))
1819 if (this.isOwned()) return false
1821 return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)
1825 this.changed('updatedAt', true)
1834 if (this.isOwned()) {
1835 baseUrlHttp = WEBSERVER.URL
1836 baseUrlWs = WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT
1838 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1839 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1842 return { baseUrlHttp, baseUrlWs }
1845 generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1846 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1847 const announce = this.getTrackerUrls(baseUrlHttp, baseUrlWs)
1848 let urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1850 const redundancies = videoFile.RedundancyVideos
1851 if (isArray(redundancies)) urlList = urlList.concat(redundancies.map(r => r.fileUrl))
1853 const magnetHash = {
1857 infoHash: videoFile.infoHash,
1861 return magnetUtil.encode(magnetHash)
1864 getTrackerUrls (baseUrlHttp: string, baseUrlWs: string) {
1865 return [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1868 getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1869 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1872 getTorrentDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1873 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1876 getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1877 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1880 getVideoRedundancyUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1881 return baseUrlHttp + STATIC_PATHS.REDUNDANCY + this.getVideoFilename(videoFile)
1884 getVideoFileDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1885 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + this.getVideoFilename(videoFile)
1888 getBandwidthBits (videoFile: VideoFileModel) {
1889 return Math.ceil((videoFile.size * 8) / this.duration)