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
211 categoryOneOf?: number[]
213 licenceOneOf?: number[]
214 languageOneOf?: string[]
221 videoChannelId?: number
223 videoPlaylistId?: number
225 trendingDays?: number
227 historyOfUser?: UserModel
231 [ ScopeNames.FOR_API ]: (options: ForAPIOptions) => {
232 const query: FindOptions = {
235 [ Op.in ]: options.ids // FIXME: sequelize ANY seems broken
240 model: VideoChannelModel.scope({ method: [ VideoChannelScopeNames.SUMMARY, true ] }),
244 attributes: [ 'type', 'filename' ],
245 model: ThumbnailModel,
251 if (options.withFiles === true) {
253 model: VideoFileModel.unscoped(),
258 if (options.videoPlaylistId) {
260 model: VideoPlaylistElementModel.unscoped(),
263 videoPlaylistId: options.videoPlaylistId
270 [ ScopeNames.AVAILABLE_FOR_LIST_IDS ]: (options: AvailableForListIDsOptions) => {
271 const query: FindOptions = {
273 attributes: [ 'id' ],
278 [ Op.notIn ]: Sequelize.literal(
279 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
285 [ Op.notIn ]: Sequelize.literal(
287 'SELECT id FROM "videoChannel" WHERE "accountId" IN (' +
288 buildBlockedAccountSQL(options.serverAccountId, options.user ? options.user.Account.id : undefined) +
297 // Only list public/published videos
298 if (!options.filter || options.filter !== 'all-local') {
299 const privacyWhere = {
300 // Always list public videos
301 privacy: VideoPrivacy.PUBLIC,
302 // Always list published videos, or videos that are being transcoded but on which we don't want to wait for transcoding
305 state: VideoState.PUBLISHED
309 state: VideoState.TO_TRANSCODE,
310 waitTranscoding: false
316 Object.assign(query.where, privacyWhere)
319 if (options.videoPlaylistId) {
322 model: VideoPlaylistElementModel.unscoped(),
325 videoPlaylistId: options.videoPlaylistId
329 query.subQuery = false
332 if (options.filter || options.accountId || options.videoChannelId) {
333 const videoChannelInclude: IncludeOptions = {
335 model: VideoChannelModel.unscoped(),
339 if (options.videoChannelId) {
340 videoChannelInclude.where = {
341 id: options.videoChannelId
345 if (options.filter || options.accountId) {
346 const accountInclude: IncludeOptions = {
348 model: AccountModel.unscoped(),
352 if (options.filter) {
353 accountInclude.include = [
356 model: ActorModel.unscoped(),
358 where: VideoModel.buildActorWhereWithFilter(options.filter)
363 if (options.accountId) {
364 accountInclude.where = { id: options.accountId }
367 videoChannelInclude.include = [ accountInclude ]
370 query.include.push(videoChannelInclude)
373 if (options.followerActorId) {
374 let localVideosReq = ''
375 if (options.includeLocalVideos === true) {
376 localVideosReq = ' UNION ALL ' +
377 'SELECT "video"."id" AS "id" FROM "video" ' +
378 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
379 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
380 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
381 'WHERE "actor"."serverId" IS NULL'
384 // Force actorId to be a number to avoid SQL injections
385 const actorIdNumber = parseInt(options.followerActorId.toString(), 10)
386 query.where[ 'id' ][ Op.and ].push({
387 [ Op.in ]: Sequelize.literal(
389 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
390 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
391 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
393 'SELECT "video"."id" AS "id" FROM "video" ' +
394 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
395 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
396 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
397 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
398 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
405 if (options.withFiles === true) {
406 query.where[ 'id' ][ Op.and ].push({
407 [ Op.in ]: Sequelize.literal(
408 '(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 const createTagsIn = (tags: string[]) => {
416 return tags.map(t => VideoModel.sequelize.escape(t))
420 if (options.tagsOneOf) {
421 query.where[ 'id' ][ Op.and ].push({
422 [ Op.in ]: Sequelize.literal(
424 'SELECT "videoId" FROM "videoTag" ' +
425 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
426 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsOneOf) + ')' +
432 if (options.tagsAllOf) {
433 query.where[ 'id' ][ Op.and ].push({
434 [ Op.in ]: Sequelize.literal(
436 'SELECT "videoId" FROM "videoTag" ' +
437 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
438 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsAllOf) + ')' +
439 'GROUP BY "videoTag"."videoId" HAVING COUNT(*) = ' + options.tagsAllOf.length +
446 if (options.nsfw === true || options.nsfw === false) {
447 query.where[ 'nsfw' ] = options.nsfw
450 if (options.categoryOneOf) {
451 query.where[ 'category' ] = {
452 [ Op.or ]: options.categoryOneOf
456 if (options.licenceOneOf) {
457 query.where[ 'licence' ] = {
458 [ Op.or ]: options.licenceOneOf
462 if (options.languageOneOf) {
463 query.where[ 'language' ] = {
464 [ Op.or ]: options.languageOneOf
468 if (options.trendingDays) {
469 query.include.push(VideoModel.buildTrendingQuery(options.trendingDays))
471 query.subQuery = false
474 if (options.historyOfUser) {
476 model: UserVideoHistoryModel,
479 userId: options.historyOfUser.id
483 // Even if the relation is n:m, we know that a user only have 0..1 video history
484 // So we won't have multiple rows for the same video
485 // Without this, we would not be able to sort on "updatedAt" column of UserVideoHistoryModel
486 query.subQuery = false
491 [ ScopeNames.WITH_THUMBNAILS ]: {
494 model: ThumbnailModel,
499 [ ScopeNames.WITH_USER_ID ]: {
502 attributes: [ 'accountId' ],
503 model: VideoChannelModel.unscoped(),
507 attributes: [ 'userId' ],
508 model: AccountModel.unscoped(),
515 [ ScopeNames.WITH_ACCOUNT_DETAILS ]: {
518 model: VideoChannelModel.unscoped(),
523 exclude: [ 'privateKey', 'publicKey' ]
525 model: ActorModel.unscoped(),
529 attributes: [ 'host' ],
530 model: ServerModel.unscoped(),
534 model: AvatarModel.unscoped(),
540 model: AccountModel.unscoped(),
544 model: ActorModel.unscoped(),
546 exclude: [ 'privateKey', 'publicKey' ]
551 attributes: [ 'host' ],
552 model: ServerModel.unscoped(),
556 model: AvatarModel.unscoped(),
567 [ ScopeNames.WITH_TAGS ]: {
568 include: [ TagModel ]
570 [ ScopeNames.WITH_BLACKLISTED ]: {
573 attributes: [ 'id', 'reason' ],
574 model: VideoBlacklistModel,
579 [ ScopeNames.WITH_FILES ]: (withRedundancies = false) => {
580 let subInclude: any[] = []
582 if (withRedundancies === true) {
585 attributes: [ 'fileUrl' ],
586 model: VideoRedundancyModel.unscoped(),
595 model: VideoFileModel.unscoped(),
596 separate: true, // We may have multiple files, having multiple redundancies so let's separate this join
603 [ ScopeNames.WITH_STREAMING_PLAYLISTS ]: (withRedundancies = false) => {
604 let subInclude: any[] = []
606 if (withRedundancies === true) {
609 attributes: [ 'fileUrl' ],
610 model: VideoRedundancyModel.unscoped(),
619 model: VideoStreamingPlaylistModel.unscoped(),
620 separate: true, // We may have multiple streaming playlists, having multiple redundancies so let's separate this join
627 [ ScopeNames.WITH_SCHEDULED_UPDATE ]: {
630 model: ScheduleVideoUpdateModel.unscoped(),
635 [ ScopeNames.WITH_USER_HISTORY ]: (userId: number) => {
639 attributes: [ 'currentTime' ],
640 model: UserVideoHistoryModel.unscoped(),
654 export class VideoModel extends Model<VideoModel> {
657 @Default(DataType.UUIDV4)
659 @Column(DataType.UUID)
663 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
669 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category', true))
675 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence', true))
681 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language', true))
682 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
686 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
691 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
697 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description', true))
698 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
703 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support', true))
704 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
708 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
738 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
739 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
744 commentsEnabled: boolean
748 downloadEnabled: boolean
752 waitTranscoding: boolean
756 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
767 @Default(DataType.NOW)
774 originallyPublishedAt: Date
776 @ForeignKey(() => VideoChannelModel)
780 @BelongsTo(() => VideoChannelModel, {
786 VideoChannel: VideoChannelModel
788 @BelongsToMany(() => TagModel, {
789 foreignKey: 'videoId',
790 through: () => VideoTagModel,
795 @HasMany(() => ThumbnailModel, {
803 Thumbnails: ThumbnailModel[]
805 @HasMany(() => VideoPlaylistElementModel, {
812 VideoPlaylistElements: VideoPlaylistElementModel[]
814 @HasMany(() => VideoAbuseModel, {
821 VideoAbuses: VideoAbuseModel[]
823 @HasMany(() => VideoFileModel, {
831 VideoFiles: VideoFileModel[]
833 @HasMany(() => VideoStreamingPlaylistModel, {
841 VideoStreamingPlaylists: VideoStreamingPlaylistModel[]
843 @HasMany(() => VideoShareModel, {
850 VideoShares: VideoShareModel[]
852 @HasMany(() => AccountVideoRateModel, {
859 AccountVideoRates: AccountVideoRateModel[]
861 @HasMany(() => VideoCommentModel, {
869 VideoComments: VideoCommentModel[]
871 @HasMany(() => VideoViewModel, {
878 VideoViews: VideoViewModel[]
880 @HasMany(() => UserVideoHistoryModel, {
887 UserVideoHistories: UserVideoHistoryModel[]
889 @HasOne(() => ScheduleVideoUpdateModel, {
896 ScheduleVideoUpdate: ScheduleVideoUpdateModel
898 @HasOne(() => VideoBlacklistModel, {
905 VideoBlacklist: VideoBlacklistModel
907 @HasOne(() => VideoImportModel, {
914 VideoImport: VideoImportModel
916 @HasMany(() => VideoCaptionModel, {
923 [ 'separate' as any ]: true
925 VideoCaptions: VideoCaptionModel[]
928 static async sendDelete (instance: VideoModel, options) {
929 if (instance.isOwned()) {
930 if (!instance.VideoChannel) {
931 instance.VideoChannel = await instance.$get('VideoChannel', {
935 include: [ ActorModel ]
938 transaction: options.transaction
939 }) as VideoChannelModel
942 return sendDeleteVideo(instance, options.transaction)
949 static async removeFiles (instance: VideoModel) {
950 const tasks: Promise<any>[] = []
952 logger.info('Removing files of video %s.', instance.url)
954 if (instance.isOwned()) {
955 if (!Array.isArray(instance.VideoFiles)) {
956 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
959 // Remove physical files and torrents
960 instance.VideoFiles.forEach(file => {
961 tasks.push(instance.removeFile(file))
962 tasks.push(instance.removeTorrent(file))
965 // Remove playlists file
966 tasks.push(instance.removeStreamingPlaylist())
969 // Do not wait video deletion because we could be in a transaction
972 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
978 static listLocal () {
985 return VideoModel.scope([
986 ScopeNames.WITH_FILES,
987 ScopeNames.WITH_STREAMING_PLAYLISTS,
988 ScopeNames.WITH_THUMBNAILS
992 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
993 function getRawQuery (select: string) {
994 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
995 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
996 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
997 'WHERE "Account"."actorId" = ' + actorId
998 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
999 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
1000 'WHERE "VideoShare"."actorId" = ' + actorId
1002 return `(${queryVideo}) UNION (${queryVideoShare})`
1005 const rawQuery = getRawQuery('"Video"."id"')
1006 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
1012 order: getVideoSort('createdAt', [ 'Tags', 'name', 'ASC' ] as any), // FIXME: sequelize typings
1015 [ Op.in ]: Sequelize.literal('(' + rawQuery + ')')
1018 { privacy: VideoPrivacy.PUBLIC },
1019 { privacy: VideoPrivacy.UNLISTED }
1024 attributes: [ 'language' ],
1025 model: VideoCaptionModel.unscoped(),
1029 attributes: [ 'id', 'url' ],
1030 model: VideoShareModel.unscoped(),
1032 // We only want videos shared by this actor
1047 attributes: [ 'id', 'url' ],
1048 model: ActorModel.unscoped()
1053 model: VideoChannelModel.unscoped(),
1057 attributes: [ 'name' ],
1058 model: AccountModel.unscoped(),
1062 attributes: [ 'id', 'url', 'followersUrl' ],
1063 model: ActorModel.unscoped(),
1069 attributes: [ 'id', 'url', 'followersUrl' ],
1070 model: ActorModel.unscoped(),
1080 return Bluebird.all([
1081 VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findAll(query),
1082 VideoModel.sequelize.query<{ total: string }>(rawCountQuery, { type: QueryTypes.SELECT })
1083 ]).then(([ rows, totals ]) => {
1084 // totals: totalVideos + totalVideoShares
1086 let totalVideoShares = 0
1087 if (totals[ 0 ]) totalVideos = parseInt(totals[ 0 ].total, 10)
1088 if (totals[ 1 ]) totalVideoShares = parseInt(totals[ 1 ].total, 10)
1090 const total = totalVideos + totalVideoShares
1098 static listUserVideosForApi (accountId: number, start: number, count: number, sort: string, withFiles = false) {
1099 function buildBaseQuery (): FindOptions {
1103 order: getVideoSort(sort),
1106 model: VideoChannelModel,
1110 model: AccountModel,
1122 const countQuery = buildBaseQuery()
1123 const findQuery = buildBaseQuery()
1125 findQuery.include.push({
1126 model: ScheduleVideoUpdateModel,
1130 findQuery.include.push({
1131 model: VideoBlacklistModel,
1135 if (withFiles === true) {
1136 findQuery.include.push({
1137 model: VideoFileModel.unscoped(),
1142 return Promise.all([
1143 VideoModel.count(countQuery),
1144 VideoModel.findAll(findQuery)
1145 ]).then(([ count, rows ]) => {
1153 static async listForApi (options: {
1158 includeLocalVideos: boolean,
1160 categoryOneOf?: number[],
1161 licenceOneOf?: number[],
1162 languageOneOf?: string[],
1163 tagsOneOf?: string[],
1164 tagsAllOf?: string[],
1165 filter?: VideoFilter,
1167 videoChannelId?: number,
1168 followerActorId?: number
1169 videoPlaylistId?: number,
1170 trendingDays?: number,
1172 historyOfUser?: UserModel
1173 }, countVideos = true) {
1174 if (options.filter && options.filter === 'all-local' && !options.user.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1175 throw new Error('Try to filter all-local but no user has not the see all videos right')
1178 const query: FindOptions = {
1179 offset: options.start,
1180 limit: options.count,
1181 order: getVideoSort(options.sort)
1184 let trendingDays: number
1185 if (options.sort.endsWith('trending')) {
1186 trendingDays = CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1188 query.group = 'VideoModel.id'
1191 const serverActor = await getServerActor()
1193 // followerActorId === null has a meaning, so just check undefined
1194 const followerActorId = options.followerActorId !== undefined ? options.followerActorId : serverActor.id
1196 const queryOptions = {
1198 serverAccountId: serverActor.Account.id,
1200 categoryOneOf: options.categoryOneOf,
1201 licenceOneOf: options.licenceOneOf,
1202 languageOneOf: options.languageOneOf,
1203 tagsOneOf: options.tagsOneOf,
1204 tagsAllOf: options.tagsAllOf,
1205 filter: options.filter,
1206 withFiles: options.withFiles,
1207 accountId: options.accountId,
1208 videoChannelId: options.videoChannelId,
1209 videoPlaylistId: options.videoPlaylistId,
1210 includeLocalVideos: options.includeLocalVideos,
1212 historyOfUser: options.historyOfUser,
1216 return VideoModel.getAvailableForApi(query, queryOptions, countVideos)
1219 static async searchAndPopulateAccountAndServer (options: {
1220 includeLocalVideos: boolean
1225 startDate?: string // ISO 8601
1226 endDate?: string // ISO 8601
1227 originallyPublishedStartDate?: string
1228 originallyPublishedEndDate?: string
1230 categoryOneOf?: number[]
1231 licenceOneOf?: number[]
1232 languageOneOf?: string[]
1233 tagsOneOf?: string[]
1234 tagsAllOf?: string[]
1235 durationMin?: number // seconds
1236 durationMax?: number // seconds
1238 filter?: VideoFilter
1242 if (options.startDate || options.endDate) {
1243 const publishedAtRange = {}
1245 if (options.startDate) publishedAtRange[ Op.gte ] = options.startDate
1246 if (options.endDate) publishedAtRange[ Op.lte ] = options.endDate
1248 whereAnd.push({ publishedAt: publishedAtRange })
1251 if (options.originallyPublishedStartDate || options.originallyPublishedEndDate) {
1252 const originallyPublishedAtRange = {}
1254 if (options.originallyPublishedStartDate) originallyPublishedAtRange[ Op.gte ] = options.originallyPublishedStartDate
1255 if (options.originallyPublishedEndDate) originallyPublishedAtRange[ Op.lte ] = options.originallyPublishedEndDate
1257 whereAnd.push({ originallyPublishedAt: originallyPublishedAtRange })
1260 if (options.durationMin || options.durationMax) {
1261 const durationRange = {}
1263 if (options.durationMin) durationRange[ Op.gte ] = options.durationMin
1264 if (options.durationMax) durationRange[ Op.lte ] = options.durationMax
1266 whereAnd.push({ duration: durationRange })
1269 const attributesInclude = []
1270 const escapedSearch = VideoModel.sequelize.escape(options.search)
1271 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
1272 if (options.search) {
1276 [ Op.in ]: Sequelize.literal(
1278 'SELECT "video"."id" FROM "video" ' +
1280 'lower(immutable_unaccent("video"."name")) % lower(immutable_unaccent(' + escapedSearch + ')) OR ' +
1281 'lower(immutable_unaccent("video"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))' +
1283 'SELECT "video"."id" FROM "video" LEFT JOIN "videoTag" ON "videoTag"."videoId" = "video"."id" ' +
1284 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
1285 'WHERE "tag"."name" = ' + escapedSearch +
1292 attributesInclude.push(createSimilarityAttribute('VideoModel.name', options.search))
1295 // Cannot search on similarity if we don't have a search
1296 if (!options.search) {
1297 attributesInclude.push(
1298 Sequelize.literal('0 as similarity')
1302 const query: FindOptions = {
1304 include: attributesInclude
1306 offset: options.start,
1307 limit: options.count,
1308 order: getVideoSort(options.sort),
1310 [ Op.and ]: whereAnd
1314 const serverActor = await getServerActor()
1315 const queryOptions = {
1316 followerActorId: serverActor.id,
1317 serverAccountId: serverActor.Account.id,
1318 includeLocalVideos: options.includeLocalVideos,
1320 categoryOneOf: options.categoryOneOf,
1321 licenceOneOf: options.licenceOneOf,
1322 languageOneOf: options.languageOneOf,
1323 tagsOneOf: options.tagsOneOf,
1324 tagsAllOf: options.tagsAllOf,
1326 filter: options.filter
1329 return VideoModel.getAvailableForApi(query, queryOptions)
1332 static load (id: number | string, t?: Transaction) {
1333 const where = buildWhereIdOrUUID(id)
1339 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1342 static loadWithRights (id: number | string, t?: Transaction) {
1343 const where = buildWhereIdOrUUID(id)
1349 return VideoModel.scope([
1350 ScopeNames.WITH_BLACKLISTED,
1351 ScopeNames.WITH_USER_ID,
1352 ScopeNames.WITH_THUMBNAILS
1356 static loadOnlyId (id: number | string, t?: Transaction) {
1357 const where = buildWhereIdOrUUID(id)
1360 attributes: [ 'id' ],
1365 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1368 static loadWithFiles (id: number, t?: Transaction, logging?: boolean) {
1369 return VideoModel.scope([
1370 ScopeNames.WITH_FILES,
1371 ScopeNames.WITH_STREAMING_PLAYLISTS,
1372 ScopeNames.WITH_THUMBNAILS
1373 ]).findByPk(id, { transaction: t, logging })
1376 static loadByUUIDWithFile (uuid: string) {
1383 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1386 static loadByUrl (url: string, transaction?: Transaction) {
1387 const query: FindOptions = {
1394 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(query)
1397 static loadByUrlAndPopulateAccount (url: string, transaction?: Transaction) {
1398 const query: FindOptions = {
1405 return VideoModel.scope([
1406 ScopeNames.WITH_ACCOUNT_DETAILS,
1407 ScopeNames.WITH_FILES,
1408 ScopeNames.WITH_STREAMING_PLAYLISTS,
1409 ScopeNames.WITH_THUMBNAILS
1413 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Transaction, userId?: number) {
1414 const where = buildWhereIdOrUUID(id)
1417 order: [ [ 'Tags', 'name', 'ASC' ] ] as any,
1422 const scopes: (string | ScopeOptions)[] = [
1423 ScopeNames.WITH_TAGS,
1424 ScopeNames.WITH_BLACKLISTED,
1425 ScopeNames.WITH_ACCOUNT_DETAILS,
1426 ScopeNames.WITH_SCHEDULED_UPDATE,
1427 ScopeNames.WITH_FILES,
1428 ScopeNames.WITH_STREAMING_PLAYLISTS,
1429 ScopeNames.WITH_THUMBNAILS
1433 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1441 static loadForGetAPI (id: number | string, t?: Transaction, userId?: number) {
1442 const where = buildWhereIdOrUUID(id)
1445 order: [ [ 'Tags', 'name', 'ASC' ] ] as any, // FIXME: sequelize typings
1450 const scopes: (string | ScopeOptions)[] = [
1451 ScopeNames.WITH_TAGS,
1452 ScopeNames.WITH_BLACKLISTED,
1453 ScopeNames.WITH_ACCOUNT_DETAILS,
1454 ScopeNames.WITH_SCHEDULED_UPDATE,
1455 ScopeNames.WITH_THUMBNAILS,
1456 { method: [ ScopeNames.WITH_FILES, true ] },
1457 { method: [ ScopeNames.WITH_STREAMING_PLAYLISTS, true ] }
1461 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1469 static async getStats () {
1470 const totalLocalVideos = await VideoModel.count({
1475 const totalVideos = await VideoModel.count()
1477 let totalLocalVideoViews = await VideoModel.sum('views', {
1482 // Sequelize could return null...
1483 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1487 totalLocalVideoViews,
1492 static incrementViews (id: number, views: number) {
1493 return VideoModel.increment('views', {
1501 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1502 // Instances only share videos
1503 const query = 'SELECT 1 FROM "videoShare" ' +
1504 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1505 'WHERE "actorFollow"."actorId" = $followerActorId AND "videoShare"."videoId" = $videoId ' +
1509 type: QueryTypes.SELECT,
1510 bind: { followerActorId, videoId },
1514 return VideoModel.sequelize.query(query, options)
1515 .then(results => results.length === 1)
1518 // threshold corresponds to how many video the field should have to be returned
1519 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1520 const serverActor = await getServerActor()
1521 const followerActorId = serverActor.id
1523 const scopeOptions: AvailableForListIDsOptions = {
1524 serverAccountId: serverActor.Account.id,
1526 includeLocalVideos: true
1529 const query: FindOptions = {
1530 attributes: [ field ],
1533 having: Sequelize.where(
1534 Sequelize.fn('COUNT', Sequelize.col(field)), { [ Op.gte ]: threshold }
1536 order: [ (this.sequelize as any).random() ]
1539 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST_IDS, scopeOptions ] })
1541 .then(rows => rows.map(r => r[ field ]))
1544 static buildTrendingQuery (trendingDays: number) {
1548 model: VideoViewModel,
1552 [ Op.gte ]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1558 private static buildActorWhereWithFilter (filter?: VideoFilter) {
1559 if (filter && (filter === 'local' || filter === 'all-local')) {
1568 private static async getAvailableForApi (
1570 options: AvailableForListIDsOptions,
1573 const idsScope: ScopeOptions = {
1575 ScopeNames.AVAILABLE_FOR_LIST_IDS, options
1579 // Remove trending sort on count, because it uses a group by
1580 const countOptions = Object.assign({}, options, { trendingDays: undefined })
1581 const countQuery: CountOptions = Object.assign({}, query, { attributes: undefined, group: undefined })
1582 const countScope: ScopeOptions = {
1584 ScopeNames.AVAILABLE_FOR_LIST_IDS, countOptions
1588 const [ count, rowsId ] = await Promise.all([
1589 countVideos ? VideoModel.scope(countScope).count(countQuery) : Promise.resolve<number>(undefined),
1590 VideoModel.scope(idsScope).findAll(query)
1592 const ids = rowsId.map(r => r.id)
1594 if (ids.length === 0) return { data: [], total: count }
1596 const secondQuery: FindOptions = {
1599 attributes: query.attributes,
1600 order: [ // Keep original order
1602 ids.map(id => `"VideoModel".id = ${id} DESC`).join(', ')
1607 const apiScope: (string | ScopeOptions)[] = []
1610 apiScope.push({ method: [ ScopeNames.WITH_USER_HISTORY, options.user.id ] })
1615 ScopeNames.FOR_API, {
1617 withFiles: options.withFiles,
1618 videoPlaylistId: options.videoPlaylistId
1623 const rows = await VideoModel.scope(apiScope).findAll(secondQuery)
1631 static getCategoryLabel (id: number) {
1632 return VIDEO_CATEGORIES[ id ] || 'Misc'
1635 static getLicenceLabel (id: number) {
1636 return VIDEO_LICENCES[ id ] || 'Unknown'
1639 static getLanguageLabel (id: string) {
1640 return VIDEO_LANGUAGES[ id ] || 'Unknown'
1643 static getPrivacyLabel (id: number) {
1644 return VIDEO_PRIVACIES[ id ] || 'Unknown'
1647 static getStateLabel (id: number) {
1648 return VIDEO_STATES[ id ] || 'Unknown'
1651 getOriginalFile () {
1652 if (Array.isArray(this.VideoFiles) === false) return undefined
1654 // The original file is the file that have the higher resolution
1655 return maxBy(this.VideoFiles, file => file.resolution)
1658 async addAndSaveThumbnail (thumbnail: ThumbnailModel, transaction: Transaction) {
1659 thumbnail.videoId = this.id
1661 const savedThumbnail = await thumbnail.save({ transaction })
1663 if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = []
1665 // Already have this thumbnail, skip
1666 if (this.Thumbnails.find(t => t.id === savedThumbnail.id)) return
1668 this.Thumbnails.push(savedThumbnail)
1671 getVideoFilename (videoFile: VideoFileModel) {
1672 return this.uuid + '-' + videoFile.resolution + videoFile.extname
1675 generateThumbnailName () {
1676 return this.uuid + '.jpg'
1680 if (Array.isArray(this.Thumbnails) === false) return undefined
1682 return this.Thumbnails.find(t => t.type === ThumbnailType.MINIATURE)
1685 generatePreviewName () {
1686 return this.uuid + '.jpg'
1690 if (Array.isArray(this.Thumbnails) === false) return undefined
1692 return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW)
1695 getTorrentFileName (videoFile: VideoFileModel) {
1696 const extension = '.torrent'
1697 return this.uuid + '-' + videoFile.resolution + extension
1701 return this.remote === false
1704 getTorrentFilePath (videoFile: VideoFileModel) {
1705 return join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1708 getVideoFilePath (videoFile: VideoFileModel) {
1709 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1712 async createTorrentAndSetInfoHash (videoFile: VideoFileModel) {
1714 // Keep the extname, it's used by the client to stream the file inside a web browser
1715 name: `${this.name} ${videoFile.resolution}p${videoFile.extname}`,
1716 createdBy: 'PeerTube',
1718 [ WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT + '/tracker/socket' ],
1719 [ WEBSERVER.URL + '/tracker/announce' ]
1721 urlList: [ WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile) ]
1724 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
1726 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1727 logger.info('Creating torrent %s.', filePath)
1729 await writeFile(filePath, torrent)
1731 const parsedTorrent = parseTorrent(torrent)
1732 videoFile.infoHash = parsedTorrent.infoHash
1735 getWatchStaticPath () {
1736 return '/videos/watch/' + this.uuid
1739 getEmbedStaticPath () {
1740 return '/videos/embed/' + this.uuid
1743 getMiniatureStaticPath () {
1744 const thumbnail = this.getMiniature()
1745 if (!thumbnail) return null
1747 return join(STATIC_PATHS.THUMBNAILS, thumbnail.filename)
1750 getPreviewStaticPath () {
1751 const preview = this.getPreview()
1752 if (!preview) return null
1754 // We use a local cache, so specify our cache endpoint instead of potential remote URL
1755 return join(STATIC_PATHS.PREVIEWS, preview.filename)
1758 toFormattedJSON (options?: VideoFormattingJSONOptions): Video {
1759 return videoModelToFormattedJSON(this, options)
1762 toFormattedDetailsJSON (): VideoDetails {
1763 return videoModelToFormattedDetailsJSON(this)
1766 getFormattedVideoFilesJSON (): VideoFile[] {
1767 return videoFilesModelToFormattedJSON(this, this.VideoFiles)
1770 toActivityPubObject (): VideoTorrentObject {
1771 return videoModelToActivityPubObject(this)
1774 getTruncatedDescription () {
1775 if (!this.description) return null
1777 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1778 return peertubeTruncate(this.description, maxLength)
1781 getOriginalFileResolution () {
1782 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1784 return getVideoFileResolution(originalFilePath)
1787 getDescriptionAPIPath () {
1788 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1791 removeFile (videoFile: VideoFileModel, isRedundancy = false) {
1792 const baseDir = isRedundancy ? CONFIG.STORAGE.REDUNDANCY_DIR : CONFIG.STORAGE.VIDEOS_DIR
1794 const filePath = join(baseDir, this.getVideoFilename(videoFile))
1795 return remove(filePath)
1796 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1799 removeTorrent (videoFile: VideoFileModel) {
1800 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1801 return remove(torrentPath)
1802 .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err }))
1805 removeStreamingPlaylist (isRedundancy = false) {
1806 const baseDir = isRedundancy ? HLS_REDUNDANCY_DIRECTORY : HLS_STREAMING_PLAYLIST_DIRECTORY
1808 const filePath = join(baseDir, this.uuid)
1809 return remove(filePath)
1810 .catch(err => logger.warn('Cannot delete playlist directory %s.', filePath, { err }))
1814 if (this.isOwned()) return false
1816 return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)
1820 this.changed('updatedAt', true)
1829 if (this.isOwned()) {
1830 baseUrlHttp = WEBSERVER.URL
1831 baseUrlWs = WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT
1833 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1834 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1837 return { baseUrlHttp, baseUrlWs }
1840 generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1841 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1842 const announce = this.getTrackerUrls(baseUrlHttp, baseUrlWs)
1843 let urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1845 const redundancies = videoFile.RedundancyVideos
1846 if (isArray(redundancies)) urlList = urlList.concat(redundancies.map(r => r.fileUrl))
1848 const magnetHash = {
1852 infoHash: videoFile.infoHash,
1856 return magnetUtil.encode(magnetHash)
1859 getTrackerUrls (baseUrlHttp: string, baseUrlWs: string) {
1860 return [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1863 getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1864 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1867 getTorrentDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1868 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1871 getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1872 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1875 getVideoRedundancyUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1876 return baseUrlHttp + STATIC_PATHS.REDUNDANCY + this.getVideoFilename(videoFile)
1879 getVideoFileDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1880 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + this.getVideoFilename(videoFile)
1883 getBandwidthBits (videoFile: VideoFileModel) {
1884 return Math.ceil((videoFile.size * 8) / this.duration)