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 const findScopes = [
1130 ScopeNames.WITH_SCHEDULED_UPDATE,
1131 ScopeNames.WITH_BLACKLISTED,
1132 ScopeNames.WITH_THUMBNAILS
1135 if (withFiles === true) {
1136 findQuery.include.push({
1137 model: VideoFileModel.unscoped(),
1142 return Promise.all([
1143 VideoModel.count(countQuery),
1144 VideoModel.scope(findScopes).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,
1527 withoutId: true // Don't break aggregation
1530 const query: FindOptions = {
1531 attributes: [ field ],
1534 having: Sequelize.where(
1535 Sequelize.fn('COUNT', Sequelize.col(field)), { [ Op.gte ]: threshold }
1537 order: [ (this.sequelize as any).random() ]
1540 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST_IDS, scopeOptions ] })
1542 .then(rows => rows.map(r => r[ field ]))
1545 static buildTrendingQuery (trendingDays: number) {
1549 model: VideoViewModel,
1553 [ Op.gte ]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1559 private static buildActorWhereWithFilter (filter?: VideoFilter) {
1560 if (filter && (filter === 'local' || filter === 'all-local')) {
1569 private static async getAvailableForApi (
1571 options: AvailableForListIDsOptions,
1574 const idsScope: ScopeOptions = {
1576 ScopeNames.AVAILABLE_FOR_LIST_IDS, options
1580 // Remove trending sort on count, because it uses a group by
1581 const countOptions = Object.assign({}, options, { trendingDays: undefined })
1582 const countQuery: CountOptions = Object.assign({}, query, { attributes: undefined, group: undefined })
1583 const countScope: ScopeOptions = {
1585 ScopeNames.AVAILABLE_FOR_LIST_IDS, countOptions
1589 const [ count, rowsId ] = await Promise.all([
1590 countVideos ? VideoModel.scope(countScope).count(countQuery) : Promise.resolve<number>(undefined),
1591 VideoModel.scope(idsScope).findAll(query)
1593 const ids = rowsId.map(r => r.id)
1595 if (ids.length === 0) return { data: [], total: count }
1597 const secondQuery: FindOptions = {
1600 attributes: query.attributes,
1601 order: [ // Keep original order
1603 ids.map(id => `"VideoModel".id = ${id} DESC`).join(', ')
1608 const apiScope: (string | ScopeOptions)[] = []
1611 apiScope.push({ method: [ ScopeNames.WITH_USER_HISTORY, options.user.id ] })
1616 ScopeNames.FOR_API, {
1618 withFiles: options.withFiles,
1619 videoPlaylistId: options.videoPlaylistId
1624 const rows = await VideoModel.scope(apiScope).findAll(secondQuery)
1632 static getCategoryLabel (id: number) {
1633 return VIDEO_CATEGORIES[ id ] || 'Misc'
1636 static getLicenceLabel (id: number) {
1637 return VIDEO_LICENCES[ id ] || 'Unknown'
1640 static getLanguageLabel (id: string) {
1641 return VIDEO_LANGUAGES[ id ] || 'Unknown'
1644 static getPrivacyLabel (id: number) {
1645 return VIDEO_PRIVACIES[ id ] || 'Unknown'
1648 static getStateLabel (id: number) {
1649 return VIDEO_STATES[ id ] || 'Unknown'
1652 getOriginalFile () {
1653 if (Array.isArray(this.VideoFiles) === false) return undefined
1655 // The original file is the file that have the higher resolution
1656 return maxBy(this.VideoFiles, file => file.resolution)
1659 async addAndSaveThumbnail (thumbnail: ThumbnailModel, transaction: Transaction) {
1660 thumbnail.videoId = this.id
1662 const savedThumbnail = await thumbnail.save({ transaction })
1664 if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = []
1666 // Already have this thumbnail, skip
1667 if (this.Thumbnails.find(t => t.id === savedThumbnail.id)) return
1669 this.Thumbnails.push(savedThumbnail)
1672 getVideoFilename (videoFile: VideoFileModel) {
1673 return this.uuid + '-' + videoFile.resolution + videoFile.extname
1676 generateThumbnailName () {
1677 return this.uuid + '.jpg'
1681 if (Array.isArray(this.Thumbnails) === false) return undefined
1683 return this.Thumbnails.find(t => t.type === ThumbnailType.MINIATURE)
1686 generatePreviewName () {
1687 return this.uuid + '.jpg'
1691 if (Array.isArray(this.Thumbnails) === false) return undefined
1693 return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW)
1696 getTorrentFileName (videoFile: VideoFileModel) {
1697 const extension = '.torrent'
1698 return this.uuid + '-' + videoFile.resolution + extension
1702 return this.remote === false
1705 getTorrentFilePath (videoFile: VideoFileModel) {
1706 return join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1709 getVideoFilePath (videoFile: VideoFileModel) {
1710 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1713 async createTorrentAndSetInfoHash (videoFile: VideoFileModel) {
1715 // Keep the extname, it's used by the client to stream the file inside a web browser
1716 name: `${this.name} ${videoFile.resolution}p${videoFile.extname}`,
1717 createdBy: 'PeerTube',
1719 [ WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT + '/tracker/socket' ],
1720 [ WEBSERVER.URL + '/tracker/announce' ]
1722 urlList: [ WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile) ]
1725 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
1727 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1728 logger.info('Creating torrent %s.', filePath)
1730 await writeFile(filePath, torrent)
1732 const parsedTorrent = parseTorrent(torrent)
1733 videoFile.infoHash = parsedTorrent.infoHash
1736 getWatchStaticPath () {
1737 return '/videos/watch/' + this.uuid
1740 getEmbedStaticPath () {
1741 return '/videos/embed/' + this.uuid
1744 getMiniatureStaticPath () {
1745 const thumbnail = this.getMiniature()
1746 if (!thumbnail) return null
1748 return join(STATIC_PATHS.THUMBNAILS, thumbnail.filename)
1751 getPreviewStaticPath () {
1752 const preview = this.getPreview()
1753 if (!preview) return null
1755 // We use a local cache, so specify our cache endpoint instead of potential remote URL
1756 return join(STATIC_PATHS.PREVIEWS, preview.filename)
1759 toFormattedJSON (options?: VideoFormattingJSONOptions): Video {
1760 return videoModelToFormattedJSON(this, options)
1763 toFormattedDetailsJSON (): VideoDetails {
1764 return videoModelToFormattedDetailsJSON(this)
1767 getFormattedVideoFilesJSON (): VideoFile[] {
1768 return videoFilesModelToFormattedJSON(this, this.VideoFiles)
1771 toActivityPubObject (): VideoTorrentObject {
1772 return videoModelToActivityPubObject(this)
1775 getTruncatedDescription () {
1776 if (!this.description) return null
1778 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1779 return peertubeTruncate(this.description, maxLength)
1782 getOriginalFileResolution () {
1783 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1785 return getVideoFileResolution(originalFilePath)
1788 getDescriptionAPIPath () {
1789 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1792 removeFile (videoFile: VideoFileModel, isRedundancy = false) {
1793 const baseDir = isRedundancy ? CONFIG.STORAGE.REDUNDANCY_DIR : CONFIG.STORAGE.VIDEOS_DIR
1795 const filePath = join(baseDir, this.getVideoFilename(videoFile))
1796 return remove(filePath)
1797 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1800 removeTorrent (videoFile: VideoFileModel) {
1801 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1802 return remove(torrentPath)
1803 .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err }))
1806 removeStreamingPlaylist (isRedundancy = false) {
1807 const baseDir = isRedundancy ? HLS_REDUNDANCY_DIRECTORY : HLS_STREAMING_PLAYLIST_DIRECTORY
1809 const filePath = join(baseDir, this.uuid)
1810 return remove(filePath)
1811 .catch(err => logger.warn('Cannot delete playlist directory %s.', filePath, { err }))
1815 if (this.isOwned()) return false
1817 return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)
1821 this.changed('updatedAt', true)
1830 if (this.isOwned()) {
1831 baseUrlHttp = WEBSERVER.URL
1832 baseUrlWs = WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT
1834 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1835 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1838 return { baseUrlHttp, baseUrlWs }
1841 generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1842 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1843 const announce = this.getTrackerUrls(baseUrlHttp, baseUrlWs)
1844 let urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1846 const redundancies = videoFile.RedundancyVideos
1847 if (isArray(redundancies)) urlList = urlList.concat(redundancies.map(r => r.fileUrl))
1849 const magnetHash = {
1853 infoHash: videoFile.infoHash,
1857 return magnetUtil.encode(magnetHash)
1860 getTrackerUrls (baseUrlHttp: string, baseUrlWs: string) {
1861 return [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1864 getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1865 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1868 getTorrentDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1869 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1872 getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1873 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1876 getVideoRedundancyUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1877 return baseUrlHttp + STATIC_PATHS.REDUNDANCY + this.getVideoFilename(videoFile)
1880 getVideoFileDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1881 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + this.getVideoFilename(videoFile)
1884 getBandwidthBits (videoFile: VideoFileModel) {
1885 return Math.ceil((videoFile.size * 8) / this.duration)