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 CONSTRAINTS_FIELDS, HLS_PLAYLIST_DIRECTORY, HLS_REDUNDANCY_DIRECTORY,
58 STATIC_DOWNLOAD_PATHS,
66 } from '../../initializers'
67 import { sendDeleteVideo } from '../../lib/activitypub/send'
68 import { AccountModel } from '../account/account'
69 import { AccountVideoRateModel } from '../account/account-video-rate'
70 import { ActorModel } from '../activitypub/actor'
71 import { AvatarModel } from '../avatar/avatar'
72 import { ServerModel } from '../server/server'
73 import { buildBlockedAccountSQL, buildTrigramSearchIndex, createSimilarityAttribute, getVideoSort, throwIfNotValid } from '../utils'
74 import { TagModel } from './tag'
75 import { VideoAbuseModel } from './video-abuse'
76 import { VideoChannelModel } from './video-channel'
77 import { VideoCommentModel } from './video-comment'
78 import { VideoFileModel } from './video-file'
79 import { VideoShareModel } from './video-share'
80 import { VideoTagModel } from './video-tag'
81 import { ScheduleVideoUpdateModel } from './schedule-video-update'
82 import { VideoCaptionModel } from './video-caption'
83 import { VideoBlacklistModel } from './video-blacklist'
84 import { remove, writeFile } from 'fs-extra'
85 import { VideoViewModel } from './video-views'
86 import { VideoRedundancyModel } from '../redundancy/video-redundancy'
88 videoFilesModelToFormattedJSON,
89 VideoFormattingJSONOptions,
90 videoModelToActivityPubObject,
91 videoModelToFormattedDetailsJSON,
92 videoModelToFormattedJSON
93 } from './video-format-utils'
94 import * as validator from 'validator'
95 import { UserVideoHistoryModel } from '../account/user-video-history'
96 import { UserModel } from '../account/user'
97 import { VideoImportModel } from './video-import'
98 import { VideoStreamingPlaylistModel } from './video-streaming-playlist'
100 // FIXME: Define indexes here because there is an issue with TS and Sequelize.literal when called directly in the annotation
101 const indexes: Sequelize.DefineIndexesOptions[] = [
102 buildTrigramSearchIndex('video_name_trigram', 'name'),
104 { fields: [ 'createdAt' ] },
105 { fields: [ 'publishedAt' ] },
106 { fields: [ 'originallyPublishedAt' ] },
107 { fields: [ 'duration' ] },
108 { fields: [ 'views' ] },
109 { fields: [ 'channelId' ] },
111 fields: [ 'category' ], // We don't care videos with an unknown category
114 [Sequelize.Op.ne]: null
119 fields: [ 'licence' ], // We don't care videos with an unknown licence
122 [Sequelize.Op.ne]: null
127 fields: [ 'language' ], // We don't care videos with an unknown language
130 [Sequelize.Op.ne]: null
135 fields: [ 'nsfw' ], // Most of the videos are not NSFW
141 fields: [ 'remote' ], // Only index local videos
156 export enum ScopeNames {
157 AVAILABLE_FOR_LIST_IDS = 'AVAILABLE_FOR_LIST_IDS',
159 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
160 WITH_TAGS = 'WITH_TAGS',
161 WITH_FILES = 'WITH_FILES',
162 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
163 WITH_BLACKLISTED = 'WITH_BLACKLISTED',
164 WITH_USER_HISTORY = 'WITH_USER_HISTORY',
165 WITH_STREAMING_PLAYLISTS = 'WITH_STREAMING_PLAYLISTS',
166 WITH_USER_ID = 'WITH_USER_ID'
169 type ForAPIOptions = {
174 type AvailableForListIDsOptions = {
175 serverAccountId: number
176 followerActorId: number
177 includeLocalVideos: boolean
179 categoryOneOf?: number[]
181 licenceOneOf?: number[]
182 languageOneOf?: string[]
187 videoChannelId?: number
188 trendingDays?: number
190 historyOfUser?: UserModel
194 [ ScopeNames.FOR_API ]: (options: ForAPIOptions) => {
195 const accountInclude = {
196 attributes: [ 'id', 'name' ],
197 model: AccountModel.unscoped(),
201 attributes: [ 'id', 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
202 model: ActorModel.unscoped(),
206 attributes: [ 'host' ],
207 model: ServerModel.unscoped(),
211 model: AvatarModel.unscoped(),
219 const videoChannelInclude = {
220 attributes: [ 'name', 'description', 'id' ],
221 model: VideoChannelModel.unscoped(),
225 attributes: [ 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
226 model: ActorModel.unscoped(),
230 attributes: [ 'host' ],
231 model: ServerModel.unscoped(),
235 model: AvatarModel.unscoped(),
244 const query: IFindOptions<VideoModel> = {
247 [ Sequelize.Op.any ]: options.ids
250 include: [ videoChannelInclude ]
253 if (options.withFiles === true) {
255 model: VideoFileModel.unscoped(),
262 [ ScopeNames.AVAILABLE_FOR_LIST_IDS ]: (options: AvailableForListIDsOptions) => {
263 const query: IFindOptions<VideoModel> = {
265 attributes: [ 'id' ],
268 [ Sequelize.Op.and ]: [
270 [ Sequelize.Op.notIn ]: Sequelize.literal(
271 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
277 [ Sequelize.Op.notIn ]: Sequelize.literal(
279 'SELECT id FROM "videoChannel" WHERE "accountId" IN (' +
280 buildBlockedAccountSQL(options.serverAccountId, options.user ? options.user.Account.id : undefined) +
289 // Only list public/published videos
290 if (!options.filter || options.filter !== 'all-local') {
291 const privacyWhere = {
292 // Always list public videos
293 privacy: VideoPrivacy.PUBLIC,
294 // Always list published videos, or videos that are being transcoded but on which we don't want to wait for transcoding
295 [ Sequelize.Op.or ]: [
297 state: VideoState.PUBLISHED
300 [ Sequelize.Op.and ]: {
301 state: VideoState.TO_TRANSCODE,
302 waitTranscoding: false
308 Object.assign(query.where, privacyWhere)
311 if (options.filter || options.accountId || options.videoChannelId) {
312 const videoChannelInclude: IIncludeOptions = {
314 model: VideoChannelModel.unscoped(),
318 if (options.videoChannelId) {
319 videoChannelInclude.where = {
320 id: options.videoChannelId
324 if (options.filter || options.accountId) {
325 const accountInclude: IIncludeOptions = {
327 model: AccountModel.unscoped(),
331 if (options.filter) {
332 accountInclude.include = [
335 model: ActorModel.unscoped(),
337 where: VideoModel.buildActorWhereWithFilter(options.filter)
342 if (options.accountId) {
343 accountInclude.where = { id: options.accountId }
346 videoChannelInclude.include = [ accountInclude ]
349 query.include.push(videoChannelInclude)
352 if (options.followerActorId) {
353 let localVideosReq = ''
354 if (options.includeLocalVideos === true) {
355 localVideosReq = ' UNION ALL ' +
356 'SELECT "video"."id" AS "id" FROM "video" ' +
357 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
358 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
359 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
360 'WHERE "actor"."serverId" IS NULL'
363 // Force actorId to be a number to avoid SQL injections
364 const actorIdNumber = parseInt(options.followerActorId.toString(), 10)
365 query.where[ 'id' ][ Sequelize.Op.and ].push({
366 [ Sequelize.Op.in ]: Sequelize.literal(
368 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
369 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
370 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
372 'SELECT "video"."id" AS "id" FROM "video" ' +
373 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
374 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
375 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
376 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
377 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
384 if (options.withFiles === true) {
385 query.where[ 'id' ][ Sequelize.Op.and ].push({
386 [ Sequelize.Op.in ]: Sequelize.literal(
387 '(SELECT "videoId" FROM "videoFile")'
392 // FIXME: issues with sequelize count when making a join on n:m relation, so we just make a IN()
393 if (options.tagsAllOf || options.tagsOneOf) {
394 const createTagsIn = (tags: string[]) => {
395 return tags.map(t => VideoModel.sequelize.escape(t))
399 if (options.tagsOneOf) {
400 query.where[ 'id' ][ Sequelize.Op.and ].push({
401 [ Sequelize.Op.in ]: Sequelize.literal(
403 'SELECT "videoId" FROM "videoTag" ' +
404 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
405 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsOneOf) + ')' +
411 if (options.tagsAllOf) {
412 query.where[ 'id' ][ Sequelize.Op.and ].push({
413 [ Sequelize.Op.in ]: Sequelize.literal(
415 'SELECT "videoId" FROM "videoTag" ' +
416 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
417 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsAllOf) + ')' +
418 'GROUP BY "videoTag"."videoId" HAVING COUNT(*) = ' + options.tagsAllOf.length +
425 if (options.nsfw === true || options.nsfw === false) {
426 query.where[ 'nsfw' ] = options.nsfw
429 if (options.categoryOneOf) {
430 query.where[ 'category' ] = {
431 [ Sequelize.Op.or ]: options.categoryOneOf
435 if (options.licenceOneOf) {
436 query.where[ 'licence' ] = {
437 [ Sequelize.Op.or ]: options.licenceOneOf
441 if (options.languageOneOf) {
442 query.where[ 'language' ] = {
443 [ Sequelize.Op.or ]: options.languageOneOf
447 if (options.trendingDays) {
448 query.include.push(VideoModel.buildTrendingQuery(options.trendingDays))
450 query.subQuery = false
453 if (options.historyOfUser) {
455 model: UserVideoHistoryModel,
458 userId: options.historyOfUser.id
462 // Even if the relation is n:m, we know that a user only have 0..1 video history
463 // So we won't have multiple rows for the same video
464 // Without this, we would not be able to sort on "updatedAt" column of UserVideoHistoryModel
465 query.subQuery = false
470 [ ScopeNames.WITH_USER_ID ]: {
473 attributes: [ 'accountId' ],
474 model: () => VideoChannelModel.unscoped(),
478 attributes: [ 'userId' ],
479 model: () => AccountModel.unscoped(),
486 [ ScopeNames.WITH_ACCOUNT_DETAILS ]: {
489 model: () => VideoChannelModel.unscoped(),
494 exclude: [ 'privateKey', 'publicKey' ]
496 model: () => ActorModel.unscoped(),
500 attributes: [ 'host' ],
501 model: () => ServerModel.unscoped(),
505 model: () => AvatarModel.unscoped(),
511 model: () => AccountModel.unscoped(),
515 model: () => ActorModel.unscoped(),
517 exclude: [ 'privateKey', 'publicKey' ]
522 attributes: [ 'host' ],
523 model: () => ServerModel.unscoped(),
527 model: () => AvatarModel.unscoped(),
538 [ ScopeNames.WITH_TAGS ]: {
539 include: [ () => TagModel ]
541 [ ScopeNames.WITH_BLACKLISTED ]: {
544 attributes: [ 'id', 'reason' ],
545 model: () => VideoBlacklistModel,
550 [ ScopeNames.WITH_FILES ]: (withRedundancies = false) => {
551 let subInclude: any[] = []
553 if (withRedundancies === true) {
556 attributes: [ 'fileUrl' ],
557 model: VideoRedundancyModel.unscoped(),
566 model: VideoFileModel.unscoped(),
568 [ 'separate' as any ]: true, // We may have multiple files, having multiple redundancies so let's separate this join
575 [ ScopeNames.WITH_STREAMING_PLAYLISTS ]: (withRedundancies = false) => {
576 let subInclude: any[] = []
578 if (withRedundancies === true) {
581 attributes: [ 'fileUrl' ],
582 model: VideoRedundancyModel.unscoped(),
591 model: VideoStreamingPlaylistModel.unscoped(),
593 [ 'separate' as any ]: true, // We may have multiple streaming playlists, having multiple redundancies so let's separate this join
600 [ ScopeNames.WITH_SCHEDULED_UPDATE ]: {
603 model: () => ScheduleVideoUpdateModel.unscoped(),
608 [ ScopeNames.WITH_USER_HISTORY ]: (userId: number) => {
612 attributes: [ 'currentTime' ],
613 model: UserVideoHistoryModel.unscoped(),
627 export class VideoModel extends Model<VideoModel> {
630 @Default(DataType.UUIDV4)
632 @Column(DataType.UUID)
636 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
642 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category'))
648 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence'))
654 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language'))
655 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
659 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
664 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
670 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description'))
671 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
676 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support'))
677 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
681 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
711 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
712 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
717 commentsEnabled: boolean
721 downloadEnabled: boolean
725 waitTranscoding: boolean
729 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
740 @Default(Sequelize.NOW)
745 originallyPublishedAt: Date
747 @ForeignKey(() => VideoChannelModel)
751 @BelongsTo(() => VideoChannelModel, {
757 VideoChannel: VideoChannelModel
759 @BelongsToMany(() => TagModel, {
760 foreignKey: 'videoId',
761 through: () => VideoTagModel,
766 @HasMany(() => VideoAbuseModel, {
773 VideoAbuses: VideoAbuseModel[]
775 @HasMany(() => VideoFileModel, {
783 VideoFiles: VideoFileModel[]
785 @HasMany(() => VideoStreamingPlaylistModel, {
793 VideoStreamingPlaylists: VideoStreamingPlaylistModel[]
795 @HasMany(() => VideoShareModel, {
802 VideoShares: VideoShareModel[]
804 @HasMany(() => AccountVideoRateModel, {
811 AccountVideoRates: AccountVideoRateModel[]
813 @HasMany(() => VideoCommentModel, {
821 VideoComments: VideoCommentModel[]
823 @HasMany(() => VideoViewModel, {
830 VideoViews: VideoViewModel[]
832 @HasMany(() => UserVideoHistoryModel, {
839 UserVideoHistories: UserVideoHistoryModel[]
841 @HasOne(() => ScheduleVideoUpdateModel, {
848 ScheduleVideoUpdate: ScheduleVideoUpdateModel
850 @HasOne(() => VideoBlacklistModel, {
857 VideoBlacklist: VideoBlacklistModel
859 @HasOne(() => VideoImportModel, {
866 VideoImport: VideoImportModel
868 @HasMany(() => VideoCaptionModel, {
875 [ 'separate' as any ]: true
877 VideoCaptions: VideoCaptionModel[]
880 static async sendDelete (instance: VideoModel, options) {
881 if (instance.isOwned()) {
882 if (!instance.VideoChannel) {
883 instance.VideoChannel = await instance.$get('VideoChannel', {
887 include: [ ActorModel ]
890 transaction: options.transaction
891 }) as VideoChannelModel
894 return sendDeleteVideo(instance, options.transaction)
901 static async removeFiles (instance: VideoModel) {
902 const tasks: Promise<any>[] = []
904 logger.info('Removing files of video %s.', instance.url)
906 tasks.push(instance.removeThumbnail())
908 if (instance.isOwned()) {
909 if (!Array.isArray(instance.VideoFiles)) {
910 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
913 tasks.push(instance.removePreview())
915 // Remove physical files and torrents
916 instance.VideoFiles.forEach(file => {
917 tasks.push(instance.removeFile(file))
918 tasks.push(instance.removeTorrent(file))
921 // Remove playlists file
922 tasks.push(instance.removeStreamingPlaylist())
925 // Do not wait video deletion because we could be in a transaction
928 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
934 static listLocal () {
941 return VideoModel.scope([ ScopeNames.WITH_FILES, ScopeNames.WITH_STREAMING_PLAYLISTS ]).findAll(query)
944 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
945 function getRawQuery (select: string) {
946 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
947 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
948 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
949 'WHERE "Account"."actorId" = ' + actorId
950 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
951 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
952 'WHERE "VideoShare"."actorId" = ' + actorId
954 return `(${queryVideo}) UNION (${queryVideoShare})`
957 const rawQuery = getRawQuery('"Video"."id"')
958 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
964 order: getVideoSort('createdAt', [ 'Tags', 'name', 'ASC' ]),
967 [ Sequelize.Op.in ]: Sequelize.literal('(' + rawQuery + ')')
969 [ Sequelize.Op.or ]: [
970 { privacy: VideoPrivacy.PUBLIC },
971 { privacy: VideoPrivacy.UNLISTED }
976 attributes: [ 'language' ],
977 model: VideoCaptionModel.unscoped(),
981 attributes: [ 'id', 'url' ],
982 model: VideoShareModel.unscoped(),
984 // We only want videos shared by this actor
986 [ Sequelize.Op.and ]: [
989 [ Sequelize.Op.not ]: null
999 attributes: [ 'id', 'url' ],
1000 model: ActorModel.unscoped()
1005 model: VideoChannelModel.unscoped(),
1009 attributes: [ 'name' ],
1010 model: AccountModel.unscoped(),
1014 attributes: [ 'id', 'url', 'followersUrl' ],
1015 model: ActorModel.unscoped(),
1021 attributes: [ 'id', 'url', 'followersUrl' ],
1022 model: ActorModel.unscoped(),
1032 return Bluebird.all([
1033 // FIXME: typing issue
1034 VideoModel.findAll(query as any),
1035 VideoModel.sequelize.query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT })
1036 ]).then(([ rows, totals ]) => {
1037 // totals: totalVideos + totalVideoShares
1039 let totalVideoShares = 0
1040 if (totals[ 0 ]) totalVideos = parseInt(totals[ 0 ].total, 10)
1041 if (totals[ 1 ]) totalVideoShares = parseInt(totals[ 1 ].total, 10)
1043 const total = totalVideos + totalVideoShares
1051 static listUserVideosForApi (accountId: number, start: number, count: number, sort: string, withFiles = false) {
1052 const query: IFindOptions<VideoModel> = {
1055 order: getVideoSort(sort),
1058 model: VideoChannelModel,
1062 model: AccountModel,
1071 model: ScheduleVideoUpdateModel,
1075 model: VideoBlacklistModel,
1081 if (withFiles === true) {
1082 query.include.push({
1083 model: VideoFileModel.unscoped(),
1088 return VideoModel.findAndCountAll(query).then(({ rows, count }) => {
1096 static async listForApi (options: {
1101 includeLocalVideos: boolean,
1103 categoryOneOf?: number[],
1104 licenceOneOf?: number[],
1105 languageOneOf?: string[],
1106 tagsOneOf?: string[],
1107 tagsAllOf?: string[],
1108 filter?: VideoFilter,
1110 videoChannelId?: number,
1111 followerActorId?: number
1112 trendingDays?: number,
1114 historyOfUser?: UserModel
1115 }, countVideos = true) {
1116 if (options.filter && options.filter === 'all-local' && !options.user.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1117 throw new Error('Try to filter all-local but no user has not the see all videos right')
1120 const query: IFindOptions<VideoModel> = {
1121 offset: options.start,
1122 limit: options.count,
1123 order: getVideoSort(options.sort)
1126 let trendingDays: number
1127 if (options.sort.endsWith('trending')) {
1128 trendingDays = CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1130 query.group = 'VideoModel.id'
1133 const serverActor = await getServerActor()
1135 // followerActorId === null has a meaning, so just check undefined
1136 const followerActorId = options.followerActorId !== undefined ? options.followerActorId : serverActor.id
1138 const queryOptions = {
1140 serverAccountId: serverActor.Account.id,
1142 categoryOneOf: options.categoryOneOf,
1143 licenceOneOf: options.licenceOneOf,
1144 languageOneOf: options.languageOneOf,
1145 tagsOneOf: options.tagsOneOf,
1146 tagsAllOf: options.tagsAllOf,
1147 filter: options.filter,
1148 withFiles: options.withFiles,
1149 accountId: options.accountId,
1150 videoChannelId: options.videoChannelId,
1151 includeLocalVideos: options.includeLocalVideos,
1153 historyOfUser: options.historyOfUser,
1157 return VideoModel.getAvailableForApi(query, queryOptions, countVideos)
1160 static async searchAndPopulateAccountAndServer (options: {
1161 includeLocalVideos: boolean
1166 startDate?: string // ISO 8601
1167 endDate?: string // ISO 8601
1169 categoryOneOf?: number[]
1170 licenceOneOf?: number[]
1171 languageOneOf?: string[]
1172 tagsOneOf?: string[]
1173 tagsAllOf?: string[]
1174 durationMin?: number // seconds
1175 durationMax?: number // seconds
1177 filter?: VideoFilter
1181 if (options.startDate || options.endDate) {
1182 const publishedAtRange = {}
1184 if (options.startDate) publishedAtRange[ Sequelize.Op.gte ] = options.startDate
1185 if (options.endDate) publishedAtRange[ Sequelize.Op.lte ] = options.endDate
1187 whereAnd.push({ publishedAt: publishedAtRange })
1190 if (options.durationMin || options.durationMax) {
1191 const durationRange = {}
1193 if (options.durationMin) durationRange[ Sequelize.Op.gte ] = options.durationMin
1194 if (options.durationMax) durationRange[ Sequelize.Op.lte ] = options.durationMax
1196 whereAnd.push({ duration: durationRange })
1199 const attributesInclude = []
1200 const escapedSearch = VideoModel.sequelize.escape(options.search)
1201 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
1202 if (options.search) {
1206 [ Sequelize.Op.in ]: Sequelize.literal(
1208 'SELECT "video"."id" FROM "video" ' +
1210 'lower(immutable_unaccent("video"."name")) % lower(immutable_unaccent(' + escapedSearch + ')) OR ' +
1211 'lower(immutable_unaccent("video"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))' +
1213 'SELECT "video"."id" FROM "video" LEFT JOIN "videoTag" ON "videoTag"."videoId" = "video"."id" ' +
1214 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
1215 'WHERE "tag"."name" = ' + escapedSearch +
1222 attributesInclude.push(createSimilarityAttribute('VideoModel.name', options.search))
1225 // Cannot search on similarity if we don't have a search
1226 if (!options.search) {
1227 attributesInclude.push(
1228 Sequelize.literal('0 as similarity')
1232 const query: IFindOptions<VideoModel> = {
1234 include: attributesInclude
1236 offset: options.start,
1237 limit: options.count,
1238 order: getVideoSort(options.sort),
1240 [ Sequelize.Op.and ]: whereAnd
1244 const serverActor = await getServerActor()
1245 const queryOptions = {
1246 followerActorId: serverActor.id,
1247 serverAccountId: serverActor.Account.id,
1248 includeLocalVideos: options.includeLocalVideos,
1250 categoryOneOf: options.categoryOneOf,
1251 licenceOneOf: options.licenceOneOf,
1252 languageOneOf: options.languageOneOf,
1253 tagsOneOf: options.tagsOneOf,
1254 tagsAllOf: options.tagsAllOf,
1256 filter: options.filter
1259 return VideoModel.getAvailableForApi(query, queryOptions)
1262 static load (id: number | string, t?: Sequelize.Transaction) {
1263 const where = VideoModel.buildWhereIdOrUUID(id)
1269 return VideoModel.findOne(options)
1272 static loadWithRights (id: number | string, t?: Sequelize.Transaction) {
1273 const where = VideoModel.buildWhereIdOrUUID(id)
1279 return VideoModel.scope([ ScopeNames.WITH_BLACKLISTED, ScopeNames.WITH_USER_ID ]).findOne(options)
1282 static loadOnlyId (id: number | string, t?: Sequelize.Transaction) {
1283 const where = VideoModel.buildWhereIdOrUUID(id)
1286 attributes: [ 'id' ],
1291 return VideoModel.findOne(options)
1294 static loadWithFiles (id: number, t?: Sequelize.Transaction, logging?: boolean) {
1295 return VideoModel.scope([ ScopeNames.WITH_FILES, ScopeNames.WITH_STREAMING_PLAYLISTS ])
1296 .findById(id, { transaction: t, logging })
1299 static loadByUUIDWithFile (uuid: string) {
1306 return VideoModel.findOne(options)
1309 static loadByUrl (url: string, transaction?: Sequelize.Transaction) {
1310 const query: IFindOptions<VideoModel> = {
1317 return VideoModel.findOne(query)
1320 static loadByUrlAndPopulateAccount (url: string, transaction?: Sequelize.Transaction) {
1321 const query: IFindOptions<VideoModel> = {
1328 return VideoModel.scope([
1329 ScopeNames.WITH_ACCOUNT_DETAILS,
1330 ScopeNames.WITH_FILES,
1331 ScopeNames.WITH_STREAMING_PLAYLISTS
1335 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Sequelize.Transaction, userId?: number) {
1336 const where = VideoModel.buildWhereIdOrUUID(id)
1339 order: [ [ 'Tags', 'name', 'ASC' ] ],
1345 ScopeNames.WITH_TAGS,
1346 ScopeNames.WITH_BLACKLISTED,
1347 ScopeNames.WITH_ACCOUNT_DETAILS,
1348 ScopeNames.WITH_SCHEDULED_UPDATE,
1349 ScopeNames.WITH_FILES,
1350 ScopeNames.WITH_STREAMING_PLAYLISTS
1354 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] } as any) // FIXME: typings
1362 static loadForGetAPI (id: number | string, t?: Sequelize.Transaction, userId?: number) {
1363 const where = VideoModel.buildWhereIdOrUUID(id)
1366 order: [ [ 'Tags', 'name', 'ASC' ] ],
1372 ScopeNames.WITH_TAGS,
1373 ScopeNames.WITH_BLACKLISTED,
1374 ScopeNames.WITH_ACCOUNT_DETAILS,
1375 ScopeNames.WITH_SCHEDULED_UPDATE,
1376 { method: [ ScopeNames.WITH_FILES, true ] } as any, // FIXME: typings
1377 { method: [ ScopeNames.WITH_STREAMING_PLAYLISTS, true ] } as any // FIXME: typings
1381 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] } as any) // FIXME: typings
1389 static async getStats () {
1390 const totalLocalVideos = await VideoModel.count({
1395 const totalVideos = await VideoModel.count()
1397 let totalLocalVideoViews = await VideoModel.sum('views', {
1402 // Sequelize could return null...
1403 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1407 totalLocalVideoViews,
1412 static incrementViews (id: number, views: number) {
1413 return VideoModel.increment('views', {
1421 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1422 // Instances only share videos
1423 const query = 'SELECT 1 FROM "videoShare" ' +
1424 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1425 'WHERE "actorFollow"."actorId" = $followerActorId AND "videoShare"."videoId" = $videoId ' +
1429 type: Sequelize.QueryTypes.SELECT,
1430 bind: { followerActorId, videoId },
1434 return VideoModel.sequelize.query(query, options)
1435 .then(results => results.length === 1)
1438 // threshold corresponds to how many video the field should have to be returned
1439 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1440 const serverActor = await getServerActor()
1441 const followerActorId = serverActor.id
1443 const scopeOptions: AvailableForListIDsOptions = {
1444 serverAccountId: serverActor.Account.id,
1446 includeLocalVideos: true
1449 const query: IFindOptions<VideoModel> = {
1450 attributes: [ field ],
1453 having: Sequelize.where(Sequelize.fn('COUNT', Sequelize.col(field)), {
1454 [ Sequelize.Op.gte ]: threshold
1455 }) as any, // FIXME: typings
1456 order: [ this.sequelize.random() ]
1459 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST_IDS, scopeOptions ] })
1461 .then(rows => rows.map(r => r[ field ]))
1464 static buildTrendingQuery (trendingDays: number) {
1468 model: VideoViewModel,
1472 [ Sequelize.Op.gte ]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1478 private static buildActorWhereWithFilter (filter?: VideoFilter) {
1479 if (filter && (filter === 'local' || filter === 'all-local')) {
1488 private static async getAvailableForApi (
1489 query: IFindOptions<VideoModel>,
1490 options: AvailableForListIDsOptions,
1495 ScopeNames.AVAILABLE_FOR_LIST_IDS, options
1499 // Remove trending sort on count, because it uses a group by
1500 const countOptions = Object.assign({}, options, { trendingDays: undefined })
1501 const countQuery = Object.assign({}, query, { attributes: undefined, group: undefined })
1502 const countScope = {
1504 ScopeNames.AVAILABLE_FOR_LIST_IDS, countOptions
1508 const [ count, rowsId ] = await Promise.all([
1509 countVideos ? VideoModel.scope(countScope).count(countQuery) : Promise.resolve<number>(undefined),
1510 VideoModel.scope(idsScope).findAll(query)
1512 const ids = rowsId.map(r => r.id)
1514 if (ids.length === 0) return { data: [], total: count }
1517 const apiScope: any[] = [
1519 method: [ ScopeNames.FOR_API, { ids, withFiles: options.withFiles } as ForAPIOptions ]
1524 apiScope.push({ method: [ ScopeNames.WITH_USER_HISTORY, options.user.id ] })
1527 const secondQuery = {
1530 attributes: query.attributes,
1531 order: [ // Keep original order
1533 ids.map(id => `"VideoModel".id = ${id} DESC`).join(', ')
1537 const rows = await VideoModel.scope(apiScope).findAll(secondQuery)
1545 static getCategoryLabel (id: number) {
1546 return VIDEO_CATEGORIES[ id ] || 'Misc'
1549 static getLicenceLabel (id: number) {
1550 return VIDEO_LICENCES[ id ] || 'Unknown'
1553 static getLanguageLabel (id: string) {
1554 return VIDEO_LANGUAGES[ id ] || 'Unknown'
1557 static getPrivacyLabel (id: number) {
1558 return VIDEO_PRIVACIES[ id ] || 'Unknown'
1561 static getStateLabel (id: number) {
1562 return VIDEO_STATES[ id ] || 'Unknown'
1565 static buildWhereIdOrUUID (id: number | string) {
1566 return validator.isInt('' + id) ? { id } : { uuid: id }
1569 getOriginalFile () {
1570 if (Array.isArray(this.VideoFiles) === false) return undefined
1572 // The original file is the file that have the higher resolution
1573 return maxBy(this.VideoFiles, file => file.resolution)
1576 getVideoFilename (videoFile: VideoFileModel) {
1577 return this.uuid + '-' + videoFile.resolution + videoFile.extname
1580 getThumbnailName () {
1581 // We always have a copy of the thumbnail
1582 const extension = '.jpg'
1583 return this.uuid + extension
1587 const extension = '.jpg'
1588 return this.uuid + extension
1591 getTorrentFileName (videoFile: VideoFileModel) {
1592 const extension = '.torrent'
1593 return this.uuid + '-' + videoFile.resolution + extension
1597 return this.remote === false
1600 createPreview (videoFile: VideoFileModel) {
1601 return generateImageFromVideoFile(
1602 this.getVideoFilePath(videoFile),
1603 CONFIG.STORAGE.PREVIEWS_DIR,
1604 this.getPreviewName(),
1609 createThumbnail (videoFile: VideoFileModel) {
1610 return generateImageFromVideoFile(
1611 this.getVideoFilePath(videoFile),
1612 CONFIG.STORAGE.THUMBNAILS_DIR,
1613 this.getThumbnailName(),
1618 getTorrentFilePath (videoFile: VideoFileModel) {
1619 return join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1622 getVideoFilePath (videoFile: VideoFileModel) {
1623 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1626 async createTorrentAndSetInfoHash (videoFile: VideoFileModel) {
1628 // Keep the extname, it's used by the client to stream the file inside a web browser
1629 name: `${this.name} ${videoFile.resolution}p${videoFile.extname}`,
1630 createdBy: 'PeerTube',
1632 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ],
1633 [ CONFIG.WEBSERVER.URL + '/tracker/announce' ]
1635 urlList: [ CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile) ]
1638 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
1640 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1641 logger.info('Creating torrent %s.', filePath)
1643 await writeFile(filePath, torrent)
1645 const parsedTorrent = parseTorrent(torrent)
1646 videoFile.infoHash = parsedTorrent.infoHash
1649 getWatchStaticPath () {
1650 return '/videos/watch/' + this.uuid
1653 getEmbedStaticPath () {
1654 return '/videos/embed/' + this.uuid
1657 getThumbnailStaticPath () {
1658 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
1661 getPreviewStaticPath () {
1662 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
1665 toFormattedJSON (options?: VideoFormattingJSONOptions): Video {
1666 return videoModelToFormattedJSON(this, options)
1669 toFormattedDetailsJSON (): VideoDetails {
1670 return videoModelToFormattedDetailsJSON(this)
1673 getFormattedVideoFilesJSON (): VideoFile[] {
1674 return videoFilesModelToFormattedJSON(this, this.VideoFiles)
1677 toActivityPubObject (): VideoTorrentObject {
1678 return videoModelToActivityPubObject(this)
1681 getTruncatedDescription () {
1682 if (!this.description) return null
1684 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1685 return peertubeTruncate(this.description, maxLength)
1688 getOriginalFileResolution () {
1689 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1691 return getVideoFileResolution(originalFilePath)
1694 getDescriptionAPIPath () {
1695 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1698 removeThumbnail () {
1699 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
1700 return remove(thumbnailPath)
1701 .catch(err => logger.warn('Cannot delete thumbnail %s.', thumbnailPath, { err }))
1705 const previewPath = join(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
1706 return remove(previewPath)
1707 .catch(err => logger.warn('Cannot delete preview %s.', previewPath, { err }))
1710 removeFile (videoFile: VideoFileModel, isRedundancy = false) {
1711 const baseDir = isRedundancy ? CONFIG.STORAGE.REDUNDANCY_DIR : CONFIG.STORAGE.VIDEOS_DIR
1713 const filePath = join(baseDir, this.getVideoFilename(videoFile))
1714 return remove(filePath)
1715 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1718 removeTorrent (videoFile: VideoFileModel) {
1719 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1720 return remove(torrentPath)
1721 .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err }))
1724 removeStreamingPlaylist (isRedundancy = false) {
1725 const baseDir = isRedundancy ? HLS_REDUNDANCY_DIRECTORY : HLS_PLAYLIST_DIRECTORY
1727 const filePath = join(baseDir, this.uuid)
1728 return remove(filePath)
1729 .catch(err => logger.warn('Cannot delete playlist directory %s.', filePath, { err }))
1733 if (this.isOwned()) return false
1735 const now = Date.now()
1736 const createdAtTime = this.createdAt.getTime()
1737 const updatedAtTime = this.updatedAt.getTime()
1739 return (now - createdAtTime) > ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL &&
1740 (now - updatedAtTime) > ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL
1744 this.changed('updatedAt', true)
1753 if (this.isOwned()) {
1754 baseUrlHttp = CONFIG.WEBSERVER.URL
1755 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1757 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1758 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1761 return { baseUrlHttp, baseUrlWs }
1764 generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1765 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1766 const announce = this.getTrackerUrls(baseUrlHttp, baseUrlWs)
1767 let urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1769 const redundancies = videoFile.RedundancyVideos
1770 if (isArray(redundancies)) urlList = urlList.concat(redundancies.map(r => r.fileUrl))
1772 const magnetHash = {
1776 infoHash: videoFile.infoHash,
1780 return magnetUtil.encode(magnetHash)
1783 getTrackerUrls (baseUrlHttp: string, baseUrlWs: string) {
1784 return [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1787 getThumbnailUrl (baseUrlHttp: string) {
1788 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName()
1791 getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1792 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1795 getTorrentDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1796 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1799 getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1800 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1803 getVideoRedundancyUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1804 return baseUrlHttp + STATIC_PATHS.REDUNDANCY + this.getVideoFilename(videoFile)
1807 getVideoFileDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1808 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + this.getVideoFilename(videoFile)
1811 getBandwidthBits (videoFile: VideoFileModel) {
1812 return Math.ceil((videoFile.size * 8) / this.duration)