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'
6 import * as Sequelize from 'sequelize'
29 } from 'sequelize-typescript'
30 import { UserRight, VideoPrivacy, VideoState } from '../../../shared'
31 import { VideoTorrentObject } from '../../../shared/models/activitypub/objects'
32 import { Video, VideoDetails, VideoFile } from '../../../shared/models/videos'
33 import { VideoFilter } from '../../../shared/models/videos/video-query.type'
34 import { createTorrentPromise, peertubeTruncate } from '../../helpers/core-utils'
35 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
36 import { isArray, isBooleanValid } from '../../helpers/custom-validators/misc'
39 isVideoDescriptionValid,
47 } from '../../helpers/custom-validators/videos'
48 import { generateImageFromVideoFile, getVideoFileResolution } from '../../helpers/ffmpeg-utils'
49 import { logger } from '../../helpers/logger'
50 import { getServerActor } from '../../helpers/utils'
55 HLS_REDUNDANCY_DIRECTORY,
56 HLS_STREAMING_PLAYLIST_DIRECTORY,
59 STATIC_DOWNLOAD_PATHS,
68 } from '../../initializers'
69 import { sendDeleteVideo } from '../../lib/activitypub/send'
70 import { AccountModel } from '../account/account'
71 import { AccountVideoRateModel } from '../account/account-video-rate'
72 import { ActorModel } from '../activitypub/actor'
73 import { AvatarModel } from '../avatar/avatar'
74 import { ServerModel } from '../server/server'
76 buildBlockedAccountSQL,
77 buildTrigramSearchIndex,
79 createSimilarityAttribute,
84 import { TagModel } from './tag'
85 import { VideoAbuseModel } from './video-abuse'
86 import { ScopeNames as VideoChannelScopeNames, VideoChannelModel } from './video-channel'
87 import { VideoCommentModel } from './video-comment'
88 import { VideoFileModel } from './video-file'
89 import { VideoShareModel } from './video-share'
90 import { VideoTagModel } from './video-tag'
91 import { ScheduleVideoUpdateModel } from './schedule-video-update'
92 import { VideoCaptionModel } from './video-caption'
93 import { VideoBlacklistModel } from './video-blacklist'
94 import { remove, writeFile } from 'fs-extra'
95 import { VideoViewModel } from './video-views'
96 import { VideoRedundancyModel } from '../redundancy/video-redundancy'
98 videoFilesModelToFormattedJSON,
99 VideoFormattingJSONOptions,
100 videoModelToActivityPubObject,
101 videoModelToFormattedDetailsJSON,
102 videoModelToFormattedJSON
103 } from './video-format-utils'
104 import { UserVideoHistoryModel } from '../account/user-video-history'
105 import { UserModel } from '../account/user'
106 import { VideoImportModel } from './video-import'
107 import { VideoStreamingPlaylistModel } from './video-streaming-playlist'
108 import { VideoPlaylistElementModel } from './video-playlist-element'
109 import { CONFIG } from '../../initializers/config'
111 // FIXME: Define indexes here because there is an issue with TS and Sequelize.literal when called directly in the annotation
112 const indexes: Sequelize.DefineIndexesOptions[] = [
113 buildTrigramSearchIndex('video_name_trigram', 'name'),
115 { fields: [ 'createdAt' ] },
116 { fields: [ 'publishedAt' ] },
117 { fields: [ 'duration' ] },
118 { fields: [ 'views' ] },
119 { fields: [ 'channelId' ] },
121 fields: [ 'originallyPublishedAt' ],
123 originallyPublishedAt: {
124 [Sequelize.Op.ne]: null
129 fields: [ 'category' ], // We don't care videos with an unknown category
132 [Sequelize.Op.ne]: null
137 fields: [ 'licence' ], // We don't care videos with an unknown licence
140 [Sequelize.Op.ne]: null
145 fields: [ 'language' ], // We don't care videos with an unknown language
148 [Sequelize.Op.ne]: null
153 fields: [ 'nsfw' ], // Most of the videos are not NSFW
159 fields: [ 'remote' ], // Only index local videos
174 export enum ScopeNames {
175 AVAILABLE_FOR_LIST_IDS = 'AVAILABLE_FOR_LIST_IDS',
177 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
178 WITH_TAGS = 'WITH_TAGS',
179 WITH_FILES = 'WITH_FILES',
180 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
181 WITH_BLACKLISTED = 'WITH_BLACKLISTED',
182 WITH_USER_HISTORY = 'WITH_USER_HISTORY',
183 WITH_STREAMING_PLAYLISTS = 'WITH_STREAMING_PLAYLISTS',
184 WITH_USER_ID = 'WITH_USER_ID'
187 type ForAPIOptions = {
190 videoPlaylistId?: number
195 type AvailableForListIDsOptions = {
196 serverAccountId: number
197 followerActorId: number
198 includeLocalVideos: boolean
201 categoryOneOf?: number[]
203 licenceOneOf?: number[]
204 languageOneOf?: string[]
211 videoChannelId?: number
213 videoPlaylistId?: number
215 trendingDays?: number
217 historyOfUser?: UserModel
221 [ ScopeNames.FOR_API ]: (options: ForAPIOptions) => {
222 const query: IFindOptions<VideoModel> = {
225 [ Sequelize.Op.any ]: options.ids
230 model: VideoChannelModel.scope({ method: [ VideoChannelScopeNames.SUMMARY, true ] }),
236 if (options.withFiles === true) {
238 model: VideoFileModel.unscoped(),
243 if (options.videoPlaylistId) {
245 model: VideoPlaylistElementModel.unscoped(),
248 videoPlaylistId: options.videoPlaylistId
255 [ ScopeNames.AVAILABLE_FOR_LIST_IDS ]: (options: AvailableForListIDsOptions) => {
256 const query: IFindOptions<VideoModel> = {
258 attributes: [ 'id' ],
261 [ Sequelize.Op.and ]: [
263 [ Sequelize.Op.notIn ]: Sequelize.literal(
264 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
270 [ Sequelize.Op.notIn ]: Sequelize.literal(
272 'SELECT id FROM "videoChannel" WHERE "accountId" IN (' +
273 buildBlockedAccountSQL(options.serverAccountId, options.user ? options.user.Account.id : undefined) +
282 // Only list public/published videos
283 if (!options.filter || options.filter !== 'all-local') {
284 const privacyWhere = {
285 // Always list public videos
286 privacy: VideoPrivacy.PUBLIC,
287 // Always list published videos, or videos that are being transcoded but on which we don't want to wait for transcoding
288 [ Sequelize.Op.or ]: [
290 state: VideoState.PUBLISHED
293 [ Sequelize.Op.and ]: {
294 state: VideoState.TO_TRANSCODE,
295 waitTranscoding: false
301 Object.assign(query.where, privacyWhere)
304 if (options.videoPlaylistId) {
307 model: VideoPlaylistElementModel.unscoped(),
310 videoPlaylistId: options.videoPlaylistId
314 query.subQuery = false
317 if (options.filter || options.accountId || options.videoChannelId) {
318 const videoChannelInclude: IIncludeOptions = {
320 model: VideoChannelModel.unscoped(),
324 if (options.videoChannelId) {
325 videoChannelInclude.where = {
326 id: options.videoChannelId
330 if (options.filter || options.accountId) {
331 const accountInclude: IIncludeOptions = {
333 model: AccountModel.unscoped(),
337 if (options.filter) {
338 accountInclude.include = [
341 model: ActorModel.unscoped(),
343 where: VideoModel.buildActorWhereWithFilter(options.filter)
348 if (options.accountId) {
349 accountInclude.where = { id: options.accountId }
352 videoChannelInclude.include = [ accountInclude ]
355 query.include.push(videoChannelInclude)
358 if (options.followerActorId) {
359 let localVideosReq = ''
360 if (options.includeLocalVideos === true) {
361 localVideosReq = ' UNION ALL ' +
362 'SELECT "video"."id" AS "id" FROM "video" ' +
363 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
364 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
365 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
366 'WHERE "actor"."serverId" IS NULL'
369 // Force actorId to be a number to avoid SQL injections
370 const actorIdNumber = parseInt(options.followerActorId.toString(), 10)
371 query.where[ 'id' ][ Sequelize.Op.and ].push({
372 [ Sequelize.Op.in ]: Sequelize.literal(
374 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
375 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
376 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
378 'SELECT "video"."id" AS "id" FROM "video" ' +
379 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
380 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
381 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
382 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
383 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
390 if (options.withFiles === true) {
391 query.where[ 'id' ][ Sequelize.Op.and ].push({
392 [ Sequelize.Op.in ]: Sequelize.literal(
393 '(SELECT "videoId" FROM "videoFile")'
398 // FIXME: issues with sequelize count when making a join on n:m relation, so we just make a IN()
399 if (options.tagsAllOf || options.tagsOneOf) {
400 const createTagsIn = (tags: string[]) => {
401 return tags.map(t => VideoModel.sequelize.escape(t))
405 if (options.tagsOneOf) {
406 query.where[ 'id' ][ Sequelize.Op.and ].push({
407 [ Sequelize.Op.in ]: Sequelize.literal(
409 'SELECT "videoId" FROM "videoTag" ' +
410 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
411 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsOneOf) + ')' +
417 if (options.tagsAllOf) {
418 query.where[ 'id' ][ Sequelize.Op.and ].push({
419 [ Sequelize.Op.in ]: Sequelize.literal(
421 'SELECT "videoId" FROM "videoTag" ' +
422 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
423 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsAllOf) + ')' +
424 'GROUP BY "videoTag"."videoId" HAVING COUNT(*) = ' + options.tagsAllOf.length +
431 if (options.nsfw === true || options.nsfw === false) {
432 query.where[ 'nsfw' ] = options.nsfw
435 if (options.categoryOneOf) {
436 query.where[ 'category' ] = {
437 [ Sequelize.Op.or ]: options.categoryOneOf
441 if (options.licenceOneOf) {
442 query.where[ 'licence' ] = {
443 [ Sequelize.Op.or ]: options.licenceOneOf
447 if (options.languageOneOf) {
448 query.where[ 'language' ] = {
449 [ Sequelize.Op.or ]: options.languageOneOf
453 if (options.trendingDays) {
454 query.include.push(VideoModel.buildTrendingQuery(options.trendingDays))
456 query.subQuery = false
459 if (options.historyOfUser) {
461 model: UserVideoHistoryModel,
464 userId: options.historyOfUser.id
468 // Even if the relation is n:m, we know that a user only have 0..1 video history
469 // So we won't have multiple rows for the same video
470 // Without this, we would not be able to sort on "updatedAt" column of UserVideoHistoryModel
471 query.subQuery = false
476 [ ScopeNames.WITH_USER_ID ]: {
479 attributes: [ 'accountId' ],
480 model: () => VideoChannelModel.unscoped(),
484 attributes: [ 'userId' ],
485 model: () => AccountModel.unscoped(),
492 [ ScopeNames.WITH_ACCOUNT_DETAILS ]: {
495 model: () => VideoChannelModel.unscoped(),
500 exclude: [ 'privateKey', 'publicKey' ]
502 model: () => ActorModel.unscoped(),
506 attributes: [ 'host' ],
507 model: () => ServerModel.unscoped(),
511 model: () => AvatarModel.unscoped(),
517 model: () => AccountModel.unscoped(),
521 model: () => ActorModel.unscoped(),
523 exclude: [ 'privateKey', 'publicKey' ]
528 attributes: [ 'host' ],
529 model: () => ServerModel.unscoped(),
533 model: () => AvatarModel.unscoped(),
544 [ ScopeNames.WITH_TAGS ]: {
545 include: [ () => TagModel ]
547 [ ScopeNames.WITH_BLACKLISTED ]: {
550 attributes: [ 'id', 'reason' ],
551 model: () => VideoBlacklistModel,
556 [ ScopeNames.WITH_FILES ]: (withRedundancies = false) => {
557 let subInclude: any[] = []
559 if (withRedundancies === true) {
562 attributes: [ 'fileUrl' ],
563 model: VideoRedundancyModel.unscoped(),
572 model: VideoFileModel.unscoped(),
574 [ 'separate' as any ]: true, // We may have multiple files, having multiple redundancies so let's separate this join
581 [ ScopeNames.WITH_STREAMING_PLAYLISTS ]: (withRedundancies = false) => {
582 let subInclude: any[] = []
584 if (withRedundancies === true) {
587 attributes: [ 'fileUrl' ],
588 model: VideoRedundancyModel.unscoped(),
597 model: VideoStreamingPlaylistModel.unscoped(),
599 [ 'separate' as any ]: true, // We may have multiple streaming playlists, having multiple redundancies so let's separate this join
606 [ ScopeNames.WITH_SCHEDULED_UPDATE ]: {
609 model: () => ScheduleVideoUpdateModel.unscoped(),
614 [ ScopeNames.WITH_USER_HISTORY ]: (userId: number) => {
618 attributes: [ 'currentTime' ],
619 model: UserVideoHistoryModel.unscoped(),
633 export class VideoModel extends Model<VideoModel> {
636 @Default(DataType.UUIDV4)
638 @Column(DataType.UUID)
642 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
648 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category'))
654 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence'))
660 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language'))
661 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
665 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
670 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
676 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description'))
677 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
682 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support'))
683 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
687 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
717 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
718 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
723 commentsEnabled: boolean
727 downloadEnabled: boolean
731 waitTranscoding: boolean
735 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
746 @Default(Sequelize.NOW)
753 originallyPublishedAt: Date
755 @ForeignKey(() => VideoChannelModel)
759 @BelongsTo(() => VideoChannelModel, {
765 VideoChannel: VideoChannelModel
767 @BelongsToMany(() => TagModel, {
768 foreignKey: 'videoId',
769 through: () => VideoTagModel,
774 @HasMany(() => VideoPlaylistElementModel, {
781 VideoPlaylistElements: VideoPlaylistElementModel[]
783 @HasMany(() => VideoAbuseModel, {
790 VideoAbuses: VideoAbuseModel[]
792 @HasMany(() => VideoFileModel, {
800 VideoFiles: VideoFileModel[]
802 @HasMany(() => VideoStreamingPlaylistModel, {
810 VideoStreamingPlaylists: VideoStreamingPlaylistModel[]
812 @HasMany(() => VideoShareModel, {
819 VideoShares: VideoShareModel[]
821 @HasMany(() => AccountVideoRateModel, {
828 AccountVideoRates: AccountVideoRateModel[]
830 @HasMany(() => VideoCommentModel, {
838 VideoComments: VideoCommentModel[]
840 @HasMany(() => VideoViewModel, {
847 VideoViews: VideoViewModel[]
849 @HasMany(() => UserVideoHistoryModel, {
856 UserVideoHistories: UserVideoHistoryModel[]
858 @HasOne(() => ScheduleVideoUpdateModel, {
865 ScheduleVideoUpdate: ScheduleVideoUpdateModel
867 @HasOne(() => VideoBlacklistModel, {
874 VideoBlacklist: VideoBlacklistModel
876 @HasOne(() => VideoImportModel, {
883 VideoImport: VideoImportModel
885 @HasMany(() => VideoCaptionModel, {
892 [ 'separate' as any ]: true
894 VideoCaptions: VideoCaptionModel[]
897 static async sendDelete (instance: VideoModel, options) {
898 if (instance.isOwned()) {
899 if (!instance.VideoChannel) {
900 instance.VideoChannel = await instance.$get('VideoChannel', {
904 include: [ ActorModel ]
907 transaction: options.transaction
908 }) as VideoChannelModel
911 return sendDeleteVideo(instance, options.transaction)
918 static async removeFiles (instance: VideoModel) {
919 const tasks: Promise<any>[] = []
921 logger.info('Removing files of video %s.', instance.url)
923 tasks.push(instance.removeThumbnail())
925 if (instance.isOwned()) {
926 if (!Array.isArray(instance.VideoFiles)) {
927 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
930 tasks.push(instance.removePreview())
932 // Remove physical files and torrents
933 instance.VideoFiles.forEach(file => {
934 tasks.push(instance.removeFile(file))
935 tasks.push(instance.removeTorrent(file))
938 // Remove playlists file
939 tasks.push(instance.removeStreamingPlaylist())
942 // Do not wait video deletion because we could be in a transaction
945 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
951 static listLocal () {
958 return VideoModel.scope([ ScopeNames.WITH_FILES, ScopeNames.WITH_STREAMING_PLAYLISTS ]).findAll(query)
961 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
962 function getRawQuery (select: string) {
963 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
964 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
965 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
966 'WHERE "Account"."actorId" = ' + actorId
967 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
968 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
969 'WHERE "VideoShare"."actorId" = ' + actorId
971 return `(${queryVideo}) UNION (${queryVideoShare})`
974 const rawQuery = getRawQuery('"Video"."id"')
975 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
981 order: getVideoSort('createdAt', [ 'Tags', 'name', 'ASC' ]),
984 [ Sequelize.Op.in ]: Sequelize.literal('(' + rawQuery + ')')
986 [ Sequelize.Op.or ]: [
987 { privacy: VideoPrivacy.PUBLIC },
988 { privacy: VideoPrivacy.UNLISTED }
993 attributes: [ 'language' ],
994 model: VideoCaptionModel.unscoped(),
998 attributes: [ 'id', 'url' ],
999 model: VideoShareModel.unscoped(),
1001 // We only want videos shared by this actor
1003 [ Sequelize.Op.and ]: [
1006 [ Sequelize.Op.not ]: null
1016 attributes: [ 'id', 'url' ],
1017 model: ActorModel.unscoped()
1022 model: VideoChannelModel.unscoped(),
1026 attributes: [ 'name' ],
1027 model: AccountModel.unscoped(),
1031 attributes: [ 'id', 'url', 'followersUrl' ],
1032 model: ActorModel.unscoped(),
1038 attributes: [ 'id', 'url', 'followersUrl' ],
1039 model: ActorModel.unscoped(),
1049 return Bluebird.all([
1050 // FIXME: typing issue
1051 VideoModel.findAll(query as any),
1052 VideoModel.sequelize.query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT })
1053 ]).then(([ rows, totals ]) => {
1054 // totals: totalVideos + totalVideoShares
1056 let totalVideoShares = 0
1057 if (totals[ 0 ]) totalVideos = parseInt(totals[ 0 ].total, 10)
1058 if (totals[ 1 ]) totalVideoShares = parseInt(totals[ 1 ].total, 10)
1060 const total = totalVideos + totalVideoShares
1068 static listUserVideosForApi (accountId: number, start: number, count: number, sort: string, withFiles = false) {
1069 const query: IFindOptions<VideoModel> = {
1072 order: getVideoSort(sort),
1075 model: VideoChannelModel,
1079 model: AccountModel,
1088 model: ScheduleVideoUpdateModel,
1092 model: VideoBlacklistModel,
1098 if (withFiles === true) {
1099 query.include.push({
1100 model: VideoFileModel.unscoped(),
1105 return VideoModel.findAndCountAll(query).then(({ rows, count }) => {
1113 static async listForApi (options: {
1118 includeLocalVideos: boolean,
1120 categoryOneOf?: number[],
1121 licenceOneOf?: number[],
1122 languageOneOf?: string[],
1123 tagsOneOf?: string[],
1124 tagsAllOf?: string[],
1125 filter?: VideoFilter,
1127 videoChannelId?: number,
1128 followerActorId?: number
1129 videoPlaylistId?: number,
1130 trendingDays?: number,
1132 historyOfUser?: UserModel
1133 }, countVideos = true) {
1134 if (options.filter && options.filter === 'all-local' && !options.user.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1135 throw new Error('Try to filter all-local but no user has not the see all videos right')
1138 const query: IFindOptions<VideoModel> = {
1139 offset: options.start,
1140 limit: options.count,
1141 order: getVideoSort(options.sort)
1144 let trendingDays: number
1145 if (options.sort.endsWith('trending')) {
1146 trendingDays = CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1148 query.group = 'VideoModel.id'
1151 const serverActor = await getServerActor()
1153 // followerActorId === null has a meaning, so just check undefined
1154 const followerActorId = options.followerActorId !== undefined ? options.followerActorId : serverActor.id
1156 const queryOptions = {
1158 serverAccountId: serverActor.Account.id,
1160 categoryOneOf: options.categoryOneOf,
1161 licenceOneOf: options.licenceOneOf,
1162 languageOneOf: options.languageOneOf,
1163 tagsOneOf: options.tagsOneOf,
1164 tagsAllOf: options.tagsAllOf,
1165 filter: options.filter,
1166 withFiles: options.withFiles,
1167 accountId: options.accountId,
1168 videoChannelId: options.videoChannelId,
1169 videoPlaylistId: options.videoPlaylistId,
1170 includeLocalVideos: options.includeLocalVideos,
1172 historyOfUser: options.historyOfUser,
1176 return VideoModel.getAvailableForApi(query, queryOptions, countVideos)
1179 static async searchAndPopulateAccountAndServer (options: {
1180 includeLocalVideos: boolean
1185 startDate?: string // ISO 8601
1186 endDate?: string // ISO 8601
1187 originallyPublishedStartDate?: string
1188 originallyPublishedEndDate?: string
1190 categoryOneOf?: number[]
1191 licenceOneOf?: number[]
1192 languageOneOf?: string[]
1193 tagsOneOf?: string[]
1194 tagsAllOf?: string[]
1195 durationMin?: number // seconds
1196 durationMax?: number // seconds
1198 filter?: VideoFilter
1202 if (options.startDate || options.endDate) {
1203 const publishedAtRange = {}
1205 if (options.startDate) publishedAtRange[ Sequelize.Op.gte ] = options.startDate
1206 if (options.endDate) publishedAtRange[ Sequelize.Op.lte ] = options.endDate
1208 whereAnd.push({ publishedAt: publishedAtRange })
1211 if (options.originallyPublishedStartDate || options.originallyPublishedEndDate) {
1212 const originallyPublishedAtRange = {}
1214 if (options.originallyPublishedStartDate) originallyPublishedAtRange[ Sequelize.Op.gte ] = options.originallyPublishedStartDate
1215 if (options.originallyPublishedEndDate) originallyPublishedAtRange[ Sequelize.Op.lte ] = options.originallyPublishedEndDate
1217 whereAnd.push({ originallyPublishedAt: originallyPublishedAtRange })
1220 if (options.durationMin || options.durationMax) {
1221 const durationRange = {}
1223 if (options.durationMin) durationRange[ Sequelize.Op.gte ] = options.durationMin
1224 if (options.durationMax) durationRange[ Sequelize.Op.lte ] = options.durationMax
1226 whereAnd.push({ duration: durationRange })
1229 const attributesInclude = []
1230 const escapedSearch = VideoModel.sequelize.escape(options.search)
1231 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
1232 if (options.search) {
1236 [ Sequelize.Op.in ]: Sequelize.literal(
1238 'SELECT "video"."id" FROM "video" ' +
1240 'lower(immutable_unaccent("video"."name")) % lower(immutable_unaccent(' + escapedSearch + ')) OR ' +
1241 'lower(immutable_unaccent("video"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))' +
1243 'SELECT "video"."id" FROM "video" LEFT JOIN "videoTag" ON "videoTag"."videoId" = "video"."id" ' +
1244 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
1245 'WHERE "tag"."name" = ' + escapedSearch +
1252 attributesInclude.push(createSimilarityAttribute('VideoModel.name', options.search))
1255 // Cannot search on similarity if we don't have a search
1256 if (!options.search) {
1257 attributesInclude.push(
1258 Sequelize.literal('0 as similarity')
1262 const query: IFindOptions<VideoModel> = {
1264 include: attributesInclude
1266 offset: options.start,
1267 limit: options.count,
1268 order: getVideoSort(options.sort),
1270 [ Sequelize.Op.and ]: whereAnd
1274 const serverActor = await getServerActor()
1275 const queryOptions = {
1276 followerActorId: serverActor.id,
1277 serverAccountId: serverActor.Account.id,
1278 includeLocalVideos: options.includeLocalVideos,
1280 categoryOneOf: options.categoryOneOf,
1281 licenceOneOf: options.licenceOneOf,
1282 languageOneOf: options.languageOneOf,
1283 tagsOneOf: options.tagsOneOf,
1284 tagsAllOf: options.tagsAllOf,
1286 filter: options.filter
1289 return VideoModel.getAvailableForApi(query, queryOptions)
1292 static load (id: number | string, t?: Sequelize.Transaction) {
1293 const where = buildWhereIdOrUUID(id)
1299 return VideoModel.findOne(options)
1302 static loadWithRights (id: number | string, t?: Sequelize.Transaction) {
1303 const where = buildWhereIdOrUUID(id)
1309 return VideoModel.scope([ ScopeNames.WITH_BLACKLISTED, ScopeNames.WITH_USER_ID ]).findOne(options)
1312 static loadOnlyId (id: number | string, t?: Sequelize.Transaction) {
1313 const where = buildWhereIdOrUUID(id)
1316 attributes: [ 'id' ],
1321 return VideoModel.findOne(options)
1324 static loadWithFiles (id: number, t?: Sequelize.Transaction, logging?: boolean) {
1325 return VideoModel.scope([ ScopeNames.WITH_FILES, ScopeNames.WITH_STREAMING_PLAYLISTS ])
1326 .findByPk(id, { transaction: t, logging })
1329 static loadByUUIDWithFile (uuid: string) {
1336 return VideoModel.findOne(options)
1339 static loadByUrl (url: string, transaction?: Sequelize.Transaction) {
1340 const query: IFindOptions<VideoModel> = {
1347 return VideoModel.findOne(query)
1350 static loadByUrlAndPopulateAccount (url: string, transaction?: Sequelize.Transaction) {
1351 const query: IFindOptions<VideoModel> = {
1358 return VideoModel.scope([
1359 ScopeNames.WITH_ACCOUNT_DETAILS,
1360 ScopeNames.WITH_FILES,
1361 ScopeNames.WITH_STREAMING_PLAYLISTS
1365 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Sequelize.Transaction, userId?: number) {
1366 const where = buildWhereIdOrUUID(id)
1369 order: [ [ 'Tags', 'name', 'ASC' ] ],
1375 ScopeNames.WITH_TAGS,
1376 ScopeNames.WITH_BLACKLISTED,
1377 ScopeNames.WITH_ACCOUNT_DETAILS,
1378 ScopeNames.WITH_SCHEDULED_UPDATE,
1379 ScopeNames.WITH_FILES,
1380 ScopeNames.WITH_STREAMING_PLAYLISTS
1384 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] } as any) // FIXME: typings
1392 static loadForGetAPI (id: number | string, t?: Sequelize.Transaction, userId?: number) {
1393 const where = buildWhereIdOrUUID(id)
1396 order: [ [ 'Tags', 'name', 'ASC' ] ],
1402 ScopeNames.WITH_TAGS,
1403 ScopeNames.WITH_BLACKLISTED,
1404 ScopeNames.WITH_ACCOUNT_DETAILS,
1405 ScopeNames.WITH_SCHEDULED_UPDATE,
1406 { method: [ ScopeNames.WITH_FILES, true ] } as any, // FIXME: typings
1407 { method: [ ScopeNames.WITH_STREAMING_PLAYLISTS, true ] } as any // FIXME: typings
1411 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] } as any) // FIXME: typings
1419 static async getStats () {
1420 const totalLocalVideos = await VideoModel.count({
1425 const totalVideos = await VideoModel.count()
1427 let totalLocalVideoViews = await VideoModel.sum('views', {
1432 // Sequelize could return null...
1433 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1437 totalLocalVideoViews,
1442 static incrementViews (id: number, views: number) {
1443 return VideoModel.increment('views', {
1451 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1452 // Instances only share videos
1453 const query = 'SELECT 1 FROM "videoShare" ' +
1454 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1455 'WHERE "actorFollow"."actorId" = $followerActorId AND "videoShare"."videoId" = $videoId ' +
1459 type: Sequelize.QueryTypes.SELECT,
1460 bind: { followerActorId, videoId },
1464 return VideoModel.sequelize.query(query, options)
1465 .then(results => results.length === 1)
1468 // threshold corresponds to how many video the field should have to be returned
1469 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1470 const serverActor = await getServerActor()
1471 const followerActorId = serverActor.id
1473 const scopeOptions: AvailableForListIDsOptions = {
1474 serverAccountId: serverActor.Account.id,
1476 includeLocalVideos: true
1479 const query: IFindOptions<VideoModel> = {
1480 attributes: [ field ],
1483 having: Sequelize.where(Sequelize.fn('COUNT', Sequelize.col(field)), {
1484 [ Sequelize.Op.gte ]: threshold
1485 }) as any, // FIXME: typings
1486 order: [ this.sequelize.random() ]
1489 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST_IDS, scopeOptions ] })
1491 .then(rows => rows.map(r => r[ field ]))
1494 static buildTrendingQuery (trendingDays: number) {
1498 model: VideoViewModel,
1502 [ Sequelize.Op.gte ]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1508 private static buildActorWhereWithFilter (filter?: VideoFilter) {
1509 if (filter && (filter === 'local' || filter === 'all-local')) {
1518 private static async getAvailableForApi (
1519 query: IFindOptions<VideoModel>,
1520 options: AvailableForListIDsOptions,
1525 ScopeNames.AVAILABLE_FOR_LIST_IDS, options
1529 // Remove trending sort on count, because it uses a group by
1530 const countOptions = Object.assign({}, options, { trendingDays: undefined })
1531 const countQuery = Object.assign({}, query, { attributes: undefined, group: undefined })
1532 const countScope = {
1534 ScopeNames.AVAILABLE_FOR_LIST_IDS, countOptions
1538 const [ count, rowsId ] = await Promise.all([
1539 countVideos ? VideoModel.scope(countScope).count(countQuery) : Promise.resolve<number>(undefined),
1540 VideoModel.scope(idsScope).findAll(query)
1542 const ids = rowsId.map(r => r.id)
1544 if (ids.length === 0) return { data: [], total: count }
1546 const secondQuery: IFindOptions<VideoModel> = {
1549 attributes: query.attributes,
1550 order: [ // Keep original order
1552 ids.map(id => `"VideoModel".id = ${id} DESC`).join(', ')
1558 const apiScope: any[] = []
1561 apiScope.push({ method: [ ScopeNames.WITH_USER_HISTORY, options.user.id ] })
1563 // Even if the relation is n:m, we know that a user only have 0..1 video history
1564 // So we won't have multiple rows for the same video
1565 // A subquery adds some bugs in our query so disable it
1566 secondQuery.subQuery = false
1571 ScopeNames.FOR_API, {
1573 withFiles: options.withFiles,
1574 videoPlaylistId: options.videoPlaylistId
1579 const rows = await VideoModel.scope(apiScope).findAll(secondQuery)
1587 static getCategoryLabel (id: number) {
1588 return VIDEO_CATEGORIES[ id ] || 'Misc'
1591 static getLicenceLabel (id: number) {
1592 return VIDEO_LICENCES[ id ] || 'Unknown'
1595 static getLanguageLabel (id: string) {
1596 return VIDEO_LANGUAGES[ id ] || 'Unknown'
1599 static getPrivacyLabel (id: number) {
1600 return VIDEO_PRIVACIES[ id ] || 'Unknown'
1603 static getStateLabel (id: number) {
1604 return VIDEO_STATES[ id ] || 'Unknown'
1607 getOriginalFile () {
1608 if (Array.isArray(this.VideoFiles) === false) return undefined
1610 // The original file is the file that have the higher resolution
1611 return maxBy(this.VideoFiles, file => file.resolution)
1614 getVideoFilename (videoFile: VideoFileModel) {
1615 return this.uuid + '-' + videoFile.resolution + videoFile.extname
1618 getThumbnailName () {
1619 const extension = '.jpg'
1620 return this.uuid + extension
1624 const extension = '.jpg'
1625 return this.uuid + extension
1628 getTorrentFileName (videoFile: VideoFileModel) {
1629 const extension = '.torrent'
1630 return this.uuid + '-' + videoFile.resolution + extension
1634 return this.remote === false
1637 createPreview (videoFile: VideoFileModel) {
1638 return generateImageFromVideoFile(
1639 this.getVideoFilePath(videoFile),
1640 CONFIG.STORAGE.PREVIEWS_DIR,
1641 this.getPreviewName(),
1646 createThumbnail (videoFile: VideoFileModel) {
1647 return generateImageFromVideoFile(
1648 this.getVideoFilePath(videoFile),
1649 CONFIG.STORAGE.THUMBNAILS_DIR,
1650 this.getThumbnailName(),
1655 getTorrentFilePath (videoFile: VideoFileModel) {
1656 return join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1659 getVideoFilePath (videoFile: VideoFileModel) {
1660 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1663 async createTorrentAndSetInfoHash (videoFile: VideoFileModel) {
1665 // Keep the extname, it's used by the client to stream the file inside a web browser
1666 name: `${this.name} ${videoFile.resolution}p${videoFile.extname}`,
1667 createdBy: 'PeerTube',
1669 [ WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT + '/tracker/socket' ],
1670 [ WEBSERVER.URL + '/tracker/announce' ]
1672 urlList: [ WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile) ]
1675 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
1677 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1678 logger.info('Creating torrent %s.', filePath)
1680 await writeFile(filePath, torrent)
1682 const parsedTorrent = parseTorrent(torrent)
1683 videoFile.infoHash = parsedTorrent.infoHash
1686 getWatchStaticPath () {
1687 return '/videos/watch/' + this.uuid
1690 getEmbedStaticPath () {
1691 return '/videos/embed/' + this.uuid
1694 getThumbnailStaticPath () {
1695 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
1698 getPreviewStaticPath () {
1699 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
1702 toFormattedJSON (options?: VideoFormattingJSONOptions): Video {
1703 return videoModelToFormattedJSON(this, options)
1706 toFormattedDetailsJSON (): VideoDetails {
1707 return videoModelToFormattedDetailsJSON(this)
1710 getFormattedVideoFilesJSON (): VideoFile[] {
1711 return videoFilesModelToFormattedJSON(this, this.VideoFiles)
1714 toActivityPubObject (): VideoTorrentObject {
1715 return videoModelToActivityPubObject(this)
1718 getTruncatedDescription () {
1719 if (!this.description) return null
1721 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1722 return peertubeTruncate(this.description, maxLength)
1725 getOriginalFileResolution () {
1726 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1728 return getVideoFileResolution(originalFilePath)
1731 getDescriptionAPIPath () {
1732 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1735 removeThumbnail () {
1736 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
1737 return remove(thumbnailPath)
1738 .catch(err => logger.warn('Cannot delete thumbnail %s.', thumbnailPath, { err }))
1742 const previewPath = join(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
1743 return remove(previewPath)
1744 .catch(err => logger.warn('Cannot delete preview %s.', previewPath, { err }))
1747 removeFile (videoFile: VideoFileModel, isRedundancy = false) {
1748 const baseDir = isRedundancy ? CONFIG.STORAGE.REDUNDANCY_DIR : CONFIG.STORAGE.VIDEOS_DIR
1750 const filePath = join(baseDir, this.getVideoFilename(videoFile))
1751 return remove(filePath)
1752 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1755 removeTorrent (videoFile: VideoFileModel) {
1756 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1757 return remove(torrentPath)
1758 .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err }))
1761 removeStreamingPlaylist (isRedundancy = false) {
1762 const baseDir = isRedundancy ? HLS_REDUNDANCY_DIRECTORY : HLS_STREAMING_PLAYLIST_DIRECTORY
1764 const filePath = join(baseDir, this.uuid)
1765 return remove(filePath)
1766 .catch(err => logger.warn('Cannot delete playlist directory %s.', filePath, { err }))
1770 if (this.isOwned()) return false
1772 return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)
1776 this.changed('updatedAt', true)
1785 if (this.isOwned()) {
1786 baseUrlHttp = WEBSERVER.URL
1787 baseUrlWs = WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT
1789 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1790 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1793 return { baseUrlHttp, baseUrlWs }
1796 generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1797 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1798 const announce = this.getTrackerUrls(baseUrlHttp, baseUrlWs)
1799 let urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1801 const redundancies = videoFile.RedundancyVideos
1802 if (isArray(redundancies)) urlList = urlList.concat(redundancies.map(r => r.fileUrl))
1804 const magnetHash = {
1808 infoHash: videoFile.infoHash,
1812 return magnetUtil.encode(magnetHash)
1815 getTrackerUrls (baseUrlHttp: string, baseUrlWs: string) {
1816 return [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1819 getThumbnailUrl (baseUrlHttp: string) {
1820 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName()
1823 getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1824 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1827 getTorrentDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1828 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1831 getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1832 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1835 getVideoRedundancyUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1836 return baseUrlHttp + STATIC_PATHS.REDUNDANCY + this.getVideoFilename(videoFile)
1839 getVideoFileDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1840 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + this.getVideoFilename(videoFile)
1843 getBandwidthBits (videoFile: VideoFileModel) {
1844 return Math.ceil((videoFile.size * 8) / this.duration)