1 import * as Bluebird from 'bluebird'
2 import { remove } from 'fs-extra'
3 import { maxBy, minBy, pick } from 'lodash'
4 import { join } from 'path'
5 import { FindOptions, IncludeOptions, Op, QueryTypes, ScopeOptions, Sequelize, Transaction, WhereOptions } from 'sequelize'
26 } from 'sequelize-typescript'
27 import { buildNSFWFilter } from '@server/helpers/express-utils'
28 import { getPrivaciesForFederation, isPrivacyForFederation } from '@server/helpers/video'
29 import { getHLSDirectory, getTorrentFileName, getTorrentFilePath, getVideoFilename, getVideoFilePath } from '@server/lib/video-paths'
30 import { getServerActor } from '@server/models/application/application'
31 import { ModelCache } from '@server/models/model-cache'
32 import { VideoFile } from '@shared/models/videos/video-file.model'
33 import { ResultList, UserRight, VideoPrivacy, VideoState } from '../../../shared'
34 import { VideoObject } from '../../../shared/models/activitypub/objects'
35 import { Video, VideoDetails } from '../../../shared/models/videos'
36 import { ThumbnailType } from '../../../shared/models/videos/thumbnail.type'
37 import { VideoFilter } from '../../../shared/models/videos/video-query.type'
38 import { VideoStreamingPlaylistType } from '../../../shared/models/videos/video-streaming-playlist.type'
39 import { peertubeTruncate } from '../../helpers/core-utils'
40 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
41 import { isBooleanValid } from '../../helpers/custom-validators/misc'
44 isVideoDescriptionValid,
52 } from '../../helpers/custom-validators/videos'
53 import { getVideoFileResolution } from '../../helpers/ffmpeg-utils'
54 import { logger } from '../../helpers/logger'
55 import { CONFIG } from '../../initializers/config'
62 STATIC_DOWNLOAD_PATHS,
70 } from '../../initializers/constants'
71 import { sendDeleteVideo } from '../../lib/activitypub/send'
74 MChannelAccountDefault,
77 MStreamingPlaylistFilesVideo,
81 MVideoAccountLightBlacklistAllFiles,
86 MVideoFormattableDetails,
92 MVideoThumbnailBlacklist,
96 } from '../../types/models'
97 import { MThumbnail } from '../../types/models/video/thumbnail'
98 import { MVideoFile, MVideoFileRedundanciesOpt, MVideoFileStreamingPlaylistVideo } from '../../types/models/video/video-file'
99 import { VideoAbuseModel } from '../abuse/video-abuse'
100 import { AccountModel } from '../account/account'
101 import { AccountVideoRateModel } from '../account/account-video-rate'
102 import { UserVideoHistoryModel } from '../account/user-video-history'
103 import { ActorModel } from '../activitypub/actor'
104 import { AvatarModel } from '../avatar/avatar'
105 import { VideoRedundancyModel } from '../redundancy/video-redundancy'
106 import { ServerModel } from '../server/server'
107 import { buildTrigramSearchIndex, buildWhereIdOrUUID, getVideoSort, isOutdated, throwIfNotValid } from '../utils'
108 import { ScheduleVideoUpdateModel } from './schedule-video-update'
109 import { TagModel } from './tag'
110 import { ThumbnailModel } from './thumbnail'
111 import { VideoBlacklistModel } from './video-blacklist'
112 import { VideoCaptionModel } from './video-caption'
113 import { ScopeNames as VideoChannelScopeNames, SummaryOptions, VideoChannelModel } from './video-channel'
114 import { VideoCommentModel } from './video-comment'
115 import { VideoFileModel } from './video-file'
117 videoFilesModelToFormattedJSON,
118 VideoFormattingJSONOptions,
119 videoModelToActivityPubObject,
120 videoModelToFormattedDetailsJSON,
121 videoModelToFormattedJSON
122 } from './video-format-utils'
123 import { VideoImportModel } from './video-import'
124 import { VideoPlaylistElementModel } from './video-playlist-element'
125 import { buildListQuery, BuildVideosQueryOptions, wrapForAPIResults } from './video-query-builder'
126 import { VideoShareModel } from './video-share'
127 import { VideoStreamingPlaylistModel } from './video-streaming-playlist'
128 import { VideoTagModel } from './video-tag'
129 import { VideoViewModel } from './video-view'
130 import { LiveManager } from '@server/lib/live-manager'
131 import { VideoLiveModel } from './video-live'
133 export enum ScopeNames {
134 AVAILABLE_FOR_LIST_IDS = 'AVAILABLE_FOR_LIST_IDS',
136 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
137 WITH_TAGS = 'WITH_TAGS',
138 WITH_WEBTORRENT_FILES = 'WITH_WEBTORRENT_FILES',
139 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
140 WITH_BLACKLISTED = 'WITH_BLACKLISTED',
141 WITH_USER_HISTORY = 'WITH_USER_HISTORY',
142 WITH_STREAMING_PLAYLISTS = 'WITH_STREAMING_PLAYLISTS',
143 WITH_USER_ID = 'WITH_USER_ID',
144 WITH_IMMUTABLE_ATTRIBUTES = 'WITH_IMMUTABLE_ATTRIBUTES',
145 WITH_THUMBNAILS = 'WITH_THUMBNAILS'
148 export type ForAPIOptions = {
151 videoPlaylistId?: number
155 withAccountBlockerIds?: number[]
158 export type AvailableForListIDsOptions = {
159 serverAccountId: number
160 followerActorId: number
161 includeLocalVideos: boolean
163 attributesType?: 'none' | 'id' | 'all'
166 categoryOneOf?: number[]
168 licenceOneOf?: number[]
169 languageOneOf?: string[]
176 videoChannelId?: number
178 videoPlaylistId?: number
180 trendingDays?: number
181 user?: MUserAccountId
182 historyOfUser?: MUserId
184 baseWhere?: WhereOptions[]
188 [ScopeNames.WITH_IMMUTABLE_ATTRIBUTES]: {
189 attributes: [ 'id', 'url', 'uuid', 'remote' ]
191 [ScopeNames.FOR_API]: (options: ForAPIOptions) => {
192 const query: FindOptions = {
195 model: VideoChannelModel.scope({
197 VideoChannelScopeNames.SUMMARY, {
199 withAccountBlockerIds: options.withAccountBlockerIds
206 attributes: [ 'type', 'filename' ],
207 model: ThumbnailModel,
221 if (options.withFiles === true) {
223 model: VideoFileModel,
228 if (options.videoPlaylistId) {
230 model: VideoPlaylistElementModel.unscoped(),
233 videoPlaylistId: options.videoPlaylistId
240 [ScopeNames.WITH_THUMBNAILS]: {
243 model: ThumbnailModel,
248 [ScopeNames.WITH_USER_ID]: {
251 attributes: [ 'accountId' ],
252 model: VideoChannelModel.unscoped(),
256 attributes: [ 'userId' ],
257 model: AccountModel.unscoped(),
264 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
267 model: VideoChannelModel.unscoped(),
272 exclude: [ 'privateKey', 'publicKey' ]
274 model: ActorModel.unscoped(),
278 attributes: [ 'host' ],
279 model: ServerModel.unscoped(),
283 model: AvatarModel.unscoped(),
289 model: AccountModel.unscoped(),
293 model: ActorModel.unscoped(),
295 exclude: [ 'privateKey', 'publicKey' ]
300 attributes: [ 'host' ],
301 model: ServerModel.unscoped(),
305 model: AvatarModel.unscoped(),
316 [ScopeNames.WITH_TAGS]: {
317 include: [ TagModel ]
319 [ScopeNames.WITH_BLACKLISTED]: {
322 attributes: [ 'id', 'reason', 'unfederated' ],
323 model: VideoBlacklistModel,
328 [ScopeNames.WITH_WEBTORRENT_FILES]: (withRedundancies = false) => {
329 let subInclude: any[] = []
331 if (withRedundancies === true) {
334 attributes: [ 'fileUrl' ],
335 model: VideoRedundancyModel.unscoped(),
344 model: VideoFileModel,
345 separate: true, // We may have multiple files, having multiple redundancies so let's separate this join
352 [ScopeNames.WITH_STREAMING_PLAYLISTS]: (withRedundancies = false) => {
353 const subInclude: IncludeOptions[] = [
355 model: VideoFileModel,
360 if (withRedundancies === true) {
362 attributes: [ 'fileUrl' ],
363 model: VideoRedundancyModel.unscoped(),
371 model: VideoStreamingPlaylistModel.unscoped(),
372 separate: true, // We may have multiple streaming playlists, having multiple redundancies so let's separate this join
379 [ScopeNames.WITH_SCHEDULED_UPDATE]: {
382 model: ScheduleVideoUpdateModel.unscoped(),
387 [ScopeNames.WITH_USER_HISTORY]: (userId: number) => {
391 attributes: [ 'currentTime' ],
392 model: UserVideoHistoryModel.unscoped(),
405 buildTrigramSearchIndex('video_name_trigram', 'name'),
407 { fields: [ 'createdAt' ] },
410 { name: 'publishedAt', order: 'DESC' },
411 { name: 'id', order: 'ASC' }
414 { fields: [ 'duration' ] },
415 { fields: [ 'views' ] },
416 { fields: [ 'channelId' ] },
418 fields: [ 'originallyPublishedAt' ],
420 originallyPublishedAt: {
426 fields: [ 'category' ], // We don't care videos with an unknown category
434 fields: [ 'licence' ], // We don't care videos with an unknown licence
442 fields: [ 'language' ], // We don't care videos with an unknown language
450 fields: [ 'nsfw' ], // Most of the videos are not NSFW
456 fields: [ 'remote' ], // Only index local videos
471 export class VideoModel extends Model<VideoModel> {
474 @Default(DataType.UUIDV4)
476 @Column(DataType.UUID)
480 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
486 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category', true))
492 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence', true))
498 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language', true))
499 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
503 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
505 privacy: VideoPrivacy
508 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
514 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description', true))
515 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
520 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support', true))
521 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
525 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
560 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
561 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
566 commentsEnabled: boolean
570 downloadEnabled: boolean
574 waitTranscoding: boolean
578 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
589 @Default(DataType.NOW)
596 originallyPublishedAt: Date
598 @ForeignKey(() => VideoChannelModel)
602 @BelongsTo(() => VideoChannelModel, {
608 VideoChannel: VideoChannelModel
610 @BelongsToMany(() => TagModel, {
611 foreignKey: 'videoId',
612 through: () => VideoTagModel,
617 @HasMany(() => ThumbnailModel, {
625 Thumbnails: ThumbnailModel[]
627 @HasMany(() => VideoPlaylistElementModel, {
634 VideoPlaylistElements: VideoPlaylistElementModel[]
636 @HasMany(() => VideoAbuseModel, {
643 VideoAbuses: VideoAbuseModel[]
645 @HasMany(() => VideoFileModel, {
653 VideoFiles: VideoFileModel[]
655 @HasMany(() => VideoStreamingPlaylistModel, {
663 VideoStreamingPlaylists: VideoStreamingPlaylistModel[]
665 @HasMany(() => VideoShareModel, {
672 VideoShares: VideoShareModel[]
674 @HasMany(() => AccountVideoRateModel, {
681 AccountVideoRates: AccountVideoRateModel[]
683 @HasMany(() => VideoCommentModel, {
691 VideoComments: VideoCommentModel[]
693 @HasMany(() => VideoViewModel, {
700 VideoViews: VideoViewModel[]
702 @HasMany(() => UserVideoHistoryModel, {
709 UserVideoHistories: UserVideoHistoryModel[]
711 @HasOne(() => ScheduleVideoUpdateModel, {
718 ScheduleVideoUpdate: ScheduleVideoUpdateModel
720 @HasOne(() => VideoBlacklistModel, {
727 VideoBlacklist: VideoBlacklistModel
729 @HasOne(() => VideoLiveModel, {
736 VideoLive: VideoLiveModel
738 @HasOne(() => VideoImportModel, {
745 VideoImport: VideoImportModel
747 @HasMany(() => VideoCaptionModel, {
754 ['separate' as any]: true
756 VideoCaptions: VideoCaptionModel[]
759 static async sendDelete (instance: MVideoAccountLight, options) {
760 if (instance.isOwned()) {
761 if (!instance.VideoChannel) {
762 instance.VideoChannel = await instance.$get('VideoChannel', {
767 transaction: options.transaction
768 }) as MChannelAccountDefault
771 return sendDeleteVideo(instance, options.transaction)
778 static async removeFiles (instance: VideoModel) {
779 const tasks: Promise<any>[] = []
781 logger.info('Removing files of video %s.', instance.url)
783 if (instance.isOwned()) {
784 if (!Array.isArray(instance.VideoFiles)) {
785 instance.VideoFiles = await instance.$get('VideoFiles')
788 // Remove physical files and torrents
789 instance.VideoFiles.forEach(file => {
790 tasks.push(instance.removeFile(file))
791 tasks.push(instance.removeTorrent(file))
794 // Remove playlists file
795 if (!Array.isArray(instance.VideoStreamingPlaylists)) {
796 instance.VideoStreamingPlaylists = await instance.$get('VideoStreamingPlaylists')
799 for (const p of instance.VideoStreamingPlaylists) {
800 tasks.push(instance.removeStreamingPlaylistFiles(p))
804 // Do not wait video deletion because we could be in a transaction
807 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
814 static stopLiveIfNeeded (instance: VideoModel) {
815 if (!instance.isLive) return
817 return LiveManager.Instance.stopSessionOf(instance.id)
821 static invalidateCache (instance: VideoModel) {
822 ModelCache.Instance.invalidateCache('video', instance.id)
826 static async saveEssentialDataToAbuses (instance: VideoModel, options) {
827 const tasks: Promise<any>[] = []
829 if (!Array.isArray(instance.VideoAbuses)) {
830 instance.VideoAbuses = await instance.$get('VideoAbuses')
832 if (instance.VideoAbuses.length === 0) return undefined
835 logger.info('Saving video abuses details of video %s.', instance.url)
837 const details = instance.toFormattedDetailsJSON()
839 for (const abuse of instance.VideoAbuses) {
840 abuse.deletedVideo = details
841 tasks.push(abuse.save({ transaction: options.transaction }))
846 logger.error('Some errors when saving details of video %s in its abuses before destroy hook.', instance.uuid, { err })
852 static listLocal (): Bluebird<MVideoWithAllFiles[]> {
859 return VideoModel.scope([
860 ScopeNames.WITH_WEBTORRENT_FILES,
861 ScopeNames.WITH_STREAMING_PLAYLISTS,
862 ScopeNames.WITH_THUMBNAILS
866 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
867 function getRawQuery (select: string) {
868 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
869 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
870 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
871 'WHERE "Account"."actorId" = ' + actorId
872 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
873 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
874 'WHERE "VideoShare"."actorId" = ' + actorId
876 return `(${queryVideo}) UNION (${queryVideoShare})`
879 const rawQuery = getRawQuery('"Video"."id"')
880 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
886 order: getVideoSort('-createdAt', [ 'Tags', 'name', 'ASC' ] as any), // FIXME: sequelize typings
889 [Op.in]: Sequelize.literal('(' + rawQuery + ')')
891 [Op.or]: getPrivaciesForFederation()
895 attributes: [ 'language', 'fileUrl' ],
896 model: VideoCaptionModel.unscoped(),
900 attributes: [ 'id', 'url' ],
901 model: VideoShareModel.unscoped(),
903 // We only want videos shared by this actor
918 attributes: [ 'id', 'url' ],
919 model: ActorModel.unscoped()
924 model: VideoChannelModel.unscoped(),
928 attributes: [ 'name' ],
929 model: AccountModel.unscoped(),
933 attributes: [ 'id', 'url', 'followersUrl' ],
934 model: ActorModel.unscoped(),
940 attributes: [ 'id', 'url', 'followersUrl' ],
941 model: ActorModel.unscoped(),
951 return Bluebird.all([
952 VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findAll(query),
953 VideoModel.sequelize.query<{ total: string }>(rawCountQuery, { type: QueryTypes.SELECT })
954 ]).then(([ rows, totals ]) => {
955 // totals: totalVideos + totalVideoShares
957 let totalVideoShares = 0
958 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
959 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
961 const total = totalVideos + totalVideoShares
969 static listUserVideosForApi (
976 function buildBaseQuery (): FindOptions {
980 order: getVideoSort(sort),
983 model: VideoChannelModel,
999 baseQuery = Object.assign(baseQuery, {
1002 [Op.iLike]: '%' + search + '%'
1011 const countQuery = buildBaseQuery()
1012 const findQuery = buildBaseQuery()
1014 const findScopes: (string | ScopeOptions)[] = [
1015 ScopeNames.WITH_SCHEDULED_UPDATE,
1016 ScopeNames.WITH_BLACKLISTED,
1017 ScopeNames.WITH_THUMBNAILS
1020 return Promise.all([
1021 VideoModel.count(countQuery),
1022 VideoModel.scope(findScopes).findAll<MVideoForUser>(findQuery)
1023 ]).then(([ count, rows ]) => {
1031 static async listForApi (options: {
1036 includeLocalVideos: boolean
1038 categoryOneOf?: number[]
1039 licenceOneOf?: number[]
1040 languageOneOf?: string[]
1041 tagsOneOf?: string[]
1042 tagsAllOf?: string[]
1043 filter?: VideoFilter
1045 videoChannelId?: number
1046 followerActorId?: number
1047 videoPlaylistId?: number
1048 trendingDays?: number
1049 user?: MUserAccountId
1050 historyOfUser?: MUserId
1051 countVideos?: boolean
1053 if (options.filter && options.filter === 'all-local' && !options.user.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1054 throw new Error('Try to filter all-local but no user has not the see all videos right')
1057 const trendingDays = options.sort.endsWith('trending')
1058 ? CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1061 const serverActor = await getServerActor()
1063 // followerActorId === null has a meaning, so just check undefined
1064 const followerActorId = options.followerActorId !== undefined
1065 ? options.followerActorId
1068 const queryOptions = {
1069 start: options.start,
1070 count: options.count,
1073 serverAccountId: serverActor.Account.id,
1075 categoryOneOf: options.categoryOneOf,
1076 licenceOneOf: options.licenceOneOf,
1077 languageOneOf: options.languageOneOf,
1078 tagsOneOf: options.tagsOneOf,
1079 tagsAllOf: options.tagsAllOf,
1080 filter: options.filter,
1081 withFiles: options.withFiles,
1082 accountId: options.accountId,
1083 videoChannelId: options.videoChannelId,
1084 videoPlaylistId: options.videoPlaylistId,
1085 includeLocalVideos: options.includeLocalVideos,
1087 historyOfUser: options.historyOfUser,
1091 return VideoModel.getAvailableForApi(queryOptions, options.countVideos)
1094 static async searchAndPopulateAccountAndServer (options: {
1095 includeLocalVideos: boolean
1100 startDate?: string // ISO 8601
1101 endDate?: string // ISO 8601
1102 originallyPublishedStartDate?: string
1103 originallyPublishedEndDate?: string
1105 categoryOneOf?: number[]
1106 licenceOneOf?: number[]
1107 languageOneOf?: string[]
1108 tagsOneOf?: string[]
1109 tagsAllOf?: string[]
1110 durationMin?: number // seconds
1111 durationMax?: number // seconds
1112 user?: MUserAccountId
1113 filter?: VideoFilter
1115 const serverActor = await getServerActor()
1116 const queryOptions = {
1117 followerActorId: serverActor.id,
1118 serverAccountId: serverActor.Account.id,
1119 includeLocalVideos: options.includeLocalVideos,
1121 categoryOneOf: options.categoryOneOf,
1122 licenceOneOf: options.licenceOneOf,
1123 languageOneOf: options.languageOneOf,
1124 tagsOneOf: options.tagsOneOf,
1125 tagsAllOf: options.tagsAllOf,
1127 filter: options.filter,
1128 start: options.start,
1129 count: options.count,
1131 startDate: options.startDate,
1132 endDate: options.endDate,
1133 originallyPublishedStartDate: options.originallyPublishedStartDate,
1134 originallyPublishedEndDate: options.originallyPublishedEndDate,
1136 durationMin: options.durationMin,
1137 durationMax: options.durationMax,
1139 search: options.search
1142 return VideoModel.getAvailableForApi(queryOptions)
1145 static countLocalLives () {
1153 return VideoModel.count(options)
1156 static countLivesOfAccount (accountId: number) {
1165 model: VideoChannelModel.unscoped(),
1173 return VideoModel.count(options)
1176 static load (id: number | string, t?: Transaction): Bluebird<MVideoThumbnail> {
1177 const where = buildWhereIdOrUUID(id)
1183 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1186 static loadWithBlacklist (id: number | string, t?: Transaction): Bluebird<MVideoThumbnailBlacklist> {
1187 const where = buildWhereIdOrUUID(id)
1193 return VideoModel.scope([
1194 ScopeNames.WITH_THUMBNAILS,
1195 ScopeNames.WITH_BLACKLISTED
1199 static loadImmutableAttributes (id: number | string, t?: Transaction): Bluebird<MVideoImmutable> {
1202 where: buildWhereIdOrUUID(id),
1206 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1209 return ModelCache.Instance.doCache({
1210 cacheType: 'load-video-immutable-id',
1217 static loadWithRights (id: number | string, t?: Transaction): Bluebird<MVideoWithRights> {
1218 const where = buildWhereIdOrUUID(id)
1224 return VideoModel.scope([
1225 ScopeNames.WITH_BLACKLISTED,
1226 ScopeNames.WITH_USER_ID,
1227 ScopeNames.WITH_THUMBNAILS
1231 static loadOnlyId (id: number | string, t?: Transaction): Bluebird<MVideoIdThumbnail> {
1232 const where = buildWhereIdOrUUID(id)
1235 attributes: [ 'id' ],
1240 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1243 static loadWithFiles (id: number | string, t?: Transaction, logging?: boolean): Bluebird<MVideoWithAllFiles> {
1244 const where = buildWhereIdOrUUID(id)
1252 return VideoModel.scope([
1253 ScopeNames.WITH_WEBTORRENT_FILES,
1254 ScopeNames.WITH_STREAMING_PLAYLISTS,
1255 ScopeNames.WITH_THUMBNAILS
1259 static loadByUUID (uuid: string): Bluebird<MVideoThumbnail> {
1266 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1269 static loadByUrl (url: string, transaction?: Transaction): Bluebird<MVideoThumbnail> {
1270 const query: FindOptions = {
1277 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(query)
1280 static loadByUrlImmutableAttributes (url: string, transaction?: Transaction): Bluebird<MVideoImmutable> {
1282 const query: FindOptions = {
1289 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1292 return ModelCache.Instance.doCache({
1293 cacheType: 'load-video-immutable-url',
1300 static loadByUrlAndPopulateAccount (url: string, transaction?: Transaction): Bluebird<MVideoAccountLightBlacklistAllFiles> {
1301 const query: FindOptions = {
1308 return VideoModel.scope([
1309 ScopeNames.WITH_ACCOUNT_DETAILS,
1310 ScopeNames.WITH_WEBTORRENT_FILES,
1311 ScopeNames.WITH_STREAMING_PLAYLISTS,
1312 ScopeNames.WITH_THUMBNAILS,
1313 ScopeNames.WITH_BLACKLISTED
1317 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Transaction, userId?: number): Bluebird<MVideoFullLight> {
1318 const where = buildWhereIdOrUUID(id)
1321 order: [ [ 'Tags', 'name', 'ASC' ] ] as any,
1326 const scopes: (string | ScopeOptions)[] = [
1327 ScopeNames.WITH_TAGS,
1328 ScopeNames.WITH_BLACKLISTED,
1329 ScopeNames.WITH_ACCOUNT_DETAILS,
1330 ScopeNames.WITH_SCHEDULED_UPDATE,
1331 ScopeNames.WITH_WEBTORRENT_FILES,
1332 ScopeNames.WITH_STREAMING_PLAYLISTS,
1333 ScopeNames.WITH_THUMBNAILS
1337 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1345 static loadForGetAPI (parameters: {
1349 }): Bluebird<MVideoDetails> {
1350 const { id, t, userId } = parameters
1351 const where = buildWhereIdOrUUID(id)
1354 order: [ [ 'Tags', 'name', 'ASC' ] ] as any, // FIXME: sequelize typings
1359 const scopes: (string | ScopeOptions)[] = [
1360 ScopeNames.WITH_TAGS,
1361 ScopeNames.WITH_BLACKLISTED,
1362 ScopeNames.WITH_ACCOUNT_DETAILS,
1363 ScopeNames.WITH_SCHEDULED_UPDATE,
1364 ScopeNames.WITH_THUMBNAILS,
1365 { method: [ ScopeNames.WITH_WEBTORRENT_FILES, true ] },
1366 { method: [ ScopeNames.WITH_STREAMING_PLAYLISTS, true ] }
1370 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1378 static async getStats () {
1379 const totalLocalVideos = await VideoModel.count({
1385 let totalLocalVideoViews = await VideoModel.sum('views', {
1391 // Sequelize could return null...
1392 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1394 const { total: totalVideos } = await VideoModel.listForApi({
1397 sort: '-publishedAt',
1398 nsfw: buildNSFWFilter(),
1399 includeLocalVideos: true,
1405 totalLocalVideoViews,
1410 static incrementViews (id: number, views: number) {
1411 return VideoModel.increment('views', {
1419 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1420 // Instances only share videos
1421 const query = 'SELECT 1 FROM "videoShare" ' +
1422 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1423 'WHERE "actorFollow"."actorId" = $followerActorId AND "actorFollow"."state" = \'accepted\' AND "videoShare"."videoId" = $videoId ' +
1427 type: QueryTypes.SELECT as QueryTypes.SELECT,
1428 bind: { followerActorId, videoId },
1432 return VideoModel.sequelize.query(query, options)
1433 .then(results => results.length === 1)
1436 static bulkUpdateSupportField (videoChannel: MChannel, t: Transaction) {
1439 channelId: videoChannel.id
1444 return VideoModel.update({ support: videoChannel.support }, options)
1447 static getAllIdsFromChannel (videoChannel: MChannelId): Bluebird<number[]> {
1449 attributes: [ 'id' ],
1451 channelId: videoChannel.id
1455 return VideoModel.findAll(query)
1456 .then(videos => videos.map(v => v.id))
1459 // threshold corresponds to how many video the field should have to be returned
1460 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1461 const serverActor = await getServerActor()
1462 const followerActorId = serverActor.id
1464 const queryOptions: BuildVideosQueryOptions = {
1465 attributes: [ `"${field}"` ],
1466 group: `GROUP BY "${field}"`,
1467 having: `HAVING COUNT("${field}") >= ${threshold}`,
1471 serverAccountId: serverActor.Account.id,
1473 includeLocalVideos: true
1476 const { query, replacements } = buildListQuery(VideoModel, queryOptions)
1478 return this.sequelize.query<any>(query, { replacements, type: QueryTypes.SELECT })
1479 .then(rows => rows.map(r => r[field]))
1482 static buildTrendingQuery (trendingDays: number) {
1486 model: VideoViewModel,
1490 [Op.gte]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1496 private static async getAvailableForApi (
1497 options: BuildVideosQueryOptions,
1499 ): Promise<ResultList<VideoModel>> {
1500 function getCount () {
1501 if (countVideos !== true) return Promise.resolve(undefined)
1503 const countOptions = Object.assign({}, options, { isCount: true })
1504 const { query: queryCount, replacements: replacementsCount } = buildListQuery(VideoModel, countOptions)
1506 return VideoModel.sequelize.query<any>(queryCount, { replacements: replacementsCount, type: QueryTypes.SELECT })
1507 .then(rows => rows.length !== 0 ? rows[0].total : 0)
1510 function getModels () {
1511 if (options.count === 0) return Promise.resolve([])
1513 const { query, replacements, order } = buildListQuery(VideoModel, options)
1514 const queryModels = wrapForAPIResults(query, replacements, options, order)
1516 return VideoModel.sequelize.query<any>(queryModels, { replacements, type: QueryTypes.SELECT, nest: true })
1517 .then(rows => VideoModel.buildAPIResult(rows))
1520 const [ count, rows ] = await Promise.all([ getCount(), getModels() ])
1528 private static buildAPIResult (rows: any[]) {
1529 const videosMemo: { [ id: number ]: VideoModel } = {}
1530 const videoStreamingPlaylistMemo: { [ id: number ]: VideoStreamingPlaylistModel } = {}
1532 const thumbnailsDone = new Set<number>()
1533 const historyDone = new Set<number>()
1534 const videoFilesDone = new Set<number>()
1536 const videos: VideoModel[] = []
1538 const avatarKeys = [ 'id', 'filename', 'fileUrl', 'onDisk', 'createdAt', 'updatedAt' ]
1539 const actorKeys = [ 'id', 'preferredUsername', 'url', 'serverId', 'avatarId' ]
1540 const serverKeys = [ 'id', 'host' ]
1541 const videoFileKeys = [ 'id', 'createdAt', 'updatedAt', 'resolution', 'size', 'extname', 'infoHash', 'fps', 'videoId' ]
1542 const videoStreamingPlaylistKeys = [ 'id' ]
1565 'originallyPublishedAt',
1571 function buildActor (rowActor: any) {
1572 const avatarModel = rowActor.Avatar.id !== null
1573 ? new AvatarModel(pick(rowActor.Avatar, avatarKeys))
1576 const serverModel = rowActor.Server.id !== null
1577 ? new ServerModel(pick(rowActor.Server, serverKeys))
1580 const actorModel = new ActorModel(pick(rowActor, actorKeys))
1581 actorModel.Avatar = avatarModel
1582 actorModel.Server = serverModel
1587 for (const row of rows) {
1588 if (!videosMemo[row.id]) {
1590 const channel = row.VideoChannel
1591 const channelModel = new VideoChannelModel(pick(channel, [ 'id', 'name', 'description', 'actorId' ]))
1592 channelModel.Actor = buildActor(channel.Actor)
1594 const account = row.VideoChannel.Account
1595 const accountModel = new AccountModel(pick(account, [ 'id', 'name' ]))
1596 accountModel.Actor = buildActor(account.Actor)
1598 channelModel.Account = accountModel
1600 const videoModel = new VideoModel(pick(row, videoKeys))
1601 videoModel.VideoChannel = channelModel
1603 videoModel.UserVideoHistories = []
1604 videoModel.Thumbnails = []
1605 videoModel.VideoFiles = []
1606 videoModel.VideoStreamingPlaylists = []
1608 videosMemo[row.id] = videoModel
1609 // Don't take object value to have a sorted array
1610 videos.push(videoModel)
1613 const videoModel = videosMemo[row.id]
1615 if (row.userVideoHistory?.id && !historyDone.has(row.userVideoHistory.id)) {
1616 const historyModel = new UserVideoHistoryModel(pick(row.userVideoHistory, [ 'id', 'currentTime' ]))
1617 videoModel.UserVideoHistories.push(historyModel)
1619 historyDone.add(row.userVideoHistory.id)
1622 if (row.Thumbnails?.id && !thumbnailsDone.has(row.Thumbnails.id)) {
1623 const thumbnailModel = new ThumbnailModel(pick(row.Thumbnails, [ 'id', 'type', 'filename' ]))
1624 videoModel.Thumbnails.push(thumbnailModel)
1626 thumbnailsDone.add(row.Thumbnails.id)
1629 if (row.VideoFiles?.id && !videoFilesDone.has(row.VideoFiles.id)) {
1630 const videoFileModel = new VideoFileModel(pick(row.VideoFiles, videoFileKeys))
1631 videoModel.VideoFiles.push(videoFileModel)
1633 videoFilesDone.add(row.VideoFiles.id)
1636 if (row.VideoFiles?.id && !videoFilesDone.has(row.VideoFiles.id)) {
1637 const videoFileModel = new VideoFileModel(pick(row.VideoFiles, videoFileKeys))
1638 videoModel.VideoFiles.push(videoFileModel)
1640 videoFilesDone.add(row.VideoFiles.id)
1643 if (row.VideoStreamingPlaylists?.id && !videoStreamingPlaylistMemo[row.VideoStreamingPlaylists.id]) {
1644 const streamingPlaylist = new VideoStreamingPlaylistModel(pick(row.VideoStreamingPlaylists, videoStreamingPlaylistKeys))
1645 streamingPlaylist.VideoFiles = []
1647 videoModel.VideoStreamingPlaylists.push(streamingPlaylist)
1649 videoStreamingPlaylistMemo[streamingPlaylist.id] = streamingPlaylist
1652 if (row.VideoStreamingPlaylists?.VideoFiles?.id && !videoFilesDone.has(row.VideoStreamingPlaylists.VideoFiles.id)) {
1653 const streamingPlaylist = videoStreamingPlaylistMemo[row.VideoStreamingPlaylists.id]
1655 const videoFileModel = new VideoFileModel(pick(row.VideoStreamingPlaylists.VideoFiles, videoFileKeys))
1656 streamingPlaylist.VideoFiles.push(videoFileModel)
1658 videoFilesDone.add(row.VideoStreamingPlaylists.VideoFiles.id)
1665 static getCategoryLabel (id: number) {
1666 return VIDEO_CATEGORIES[id] || 'Misc'
1669 static getLicenceLabel (id: number) {
1670 return VIDEO_LICENCES[id] || 'Unknown'
1673 static getLanguageLabel (id: string) {
1674 return VIDEO_LANGUAGES[id] || 'Unknown'
1677 static getPrivacyLabel (id: number) {
1678 return VIDEO_PRIVACIES[id] || 'Unknown'
1681 static getStateLabel (id: number) {
1682 return VIDEO_STATES[id] || 'Unknown'
1686 return !!this.VideoBlacklist
1690 return this.VideoChannel.Account.Actor.Server?.isBlocked() || this.VideoChannel.Account.isBlocked()
1693 getQualityFileBy<T extends MVideoWithFile> (this: T, fun: (files: MVideoFile[], it: (file: MVideoFile) => number) => MVideoFile) {
1694 if (Array.isArray(this.VideoFiles) && this.VideoFiles.length !== 0) {
1695 const file = fun(this.VideoFiles, file => file.resolution)
1697 return Object.assign(file, { Video: this })
1700 // No webtorrent files, try with streaming playlist files
1701 if (Array.isArray(this.VideoStreamingPlaylists) && this.VideoStreamingPlaylists.length !== 0) {
1702 const streamingPlaylistWithVideo = Object.assign(this.VideoStreamingPlaylists[0], { Video: this })
1704 const file = fun(streamingPlaylistWithVideo.VideoFiles, file => file.resolution)
1705 return Object.assign(file, { VideoStreamingPlaylist: streamingPlaylistWithVideo })
1711 getMaxQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1712 return this.getQualityFileBy(maxBy)
1715 getMinQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1716 return this.getQualityFileBy(minBy)
1719 getWebTorrentFile<T extends MVideoWithFile> (this: T, resolution: number): MVideoFileVideo {
1720 if (Array.isArray(this.VideoFiles) === false) return undefined
1722 const file = this.VideoFiles.find(f => f.resolution === resolution)
1723 if (!file) return undefined
1725 return Object.assign(file, { Video: this })
1728 async addAndSaveThumbnail (thumbnail: MThumbnail, transaction: Transaction) {
1729 thumbnail.videoId = this.id
1731 const savedThumbnail = await thumbnail.save({ transaction })
1733 if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = []
1735 // Already have this thumbnail, skip
1736 if (this.Thumbnails.find(t => t.id === savedThumbnail.id)) return
1738 this.Thumbnails.push(savedThumbnail)
1741 generateThumbnailName () {
1742 return this.uuid + '.jpg'
1746 if (Array.isArray(this.Thumbnails) === false) return undefined
1748 return this.Thumbnails.find(t => t.type === ThumbnailType.MINIATURE)
1751 generatePreviewName () {
1752 return this.uuid + '.jpg'
1756 return !!this.getPreview()
1760 if (Array.isArray(this.Thumbnails) === false) return undefined
1762 return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW)
1766 return this.remote === false
1769 getWatchStaticPath () {
1770 return '/videos/watch/' + this.uuid
1773 getEmbedStaticPath () {
1774 return '/videos/embed/' + this.uuid
1777 getMiniatureStaticPath () {
1778 const thumbnail = this.getMiniature()
1779 if (!thumbnail) return null
1781 return join(STATIC_PATHS.THUMBNAILS, thumbnail.filename)
1784 getPreviewStaticPath () {
1785 const preview = this.getPreview()
1786 if (!preview) return null
1788 // We use a local cache, so specify our cache endpoint instead of potential remote URL
1789 return join(LAZY_STATIC_PATHS.PREVIEWS, preview.filename)
1792 toFormattedJSON (this: MVideoFormattable, options?: VideoFormattingJSONOptions): Video {
1793 return videoModelToFormattedJSON(this, options)
1796 toFormattedDetailsJSON (this: MVideoFormattableDetails): VideoDetails {
1797 return videoModelToFormattedDetailsJSON(this)
1800 getFormattedVideoFilesJSON (): VideoFile[] {
1801 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1802 let files: MVideoFileRedundanciesOpt[] = []
1804 if (Array.isArray(this.VideoFiles)) {
1805 files = files.concat(this.VideoFiles)
1808 for (const p of (this.VideoStreamingPlaylists || [])) {
1809 files = files.concat(p.VideoFiles || [])
1812 return videoFilesModelToFormattedJSON(this, baseUrlHttp, baseUrlWs, files)
1815 toActivityPubObject (this: MVideoAP): VideoObject {
1816 return videoModelToActivityPubObject(this)
1819 getTruncatedDescription () {
1820 if (!this.description) return null
1822 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1823 return peertubeTruncate(this.description, { length: maxLength })
1826 getMaxQualityResolution () {
1827 const file = this.getMaxQualityFile()
1828 const videoOrPlaylist = file.getVideoOrStreamingPlaylist()
1829 const originalFilePath = getVideoFilePath(videoOrPlaylist, file)
1831 return getVideoFileResolution(originalFilePath)
1834 getDescriptionAPIPath () {
1835 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1838 getHLSPlaylist (): MStreamingPlaylistFilesVideo {
1839 if (!this.VideoStreamingPlaylists) return undefined
1841 const playlist = this.VideoStreamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
1842 playlist.Video = this
1847 setHLSPlaylist (playlist: MStreamingPlaylist) {
1848 const toAdd = [ playlist ] as [ VideoStreamingPlaylistModel ]
1850 if (Array.isArray(this.VideoStreamingPlaylists) === false || this.VideoStreamingPlaylists.length === 0) {
1851 this.VideoStreamingPlaylists = toAdd
1855 this.VideoStreamingPlaylists = this.VideoStreamingPlaylists
1856 .filter(s => s.type !== VideoStreamingPlaylistType.HLS)
1860 removeFile (videoFile: MVideoFile, isRedundancy = false) {
1861 const filePath = getVideoFilePath(this, videoFile, isRedundancy)
1862 return remove(filePath)
1863 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1866 removeTorrent (videoFile: MVideoFile) {
1867 const torrentPath = getTorrentFilePath(this, videoFile)
1868 return remove(torrentPath)
1869 .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err }))
1872 async removeStreamingPlaylistFiles (streamingPlaylist: MStreamingPlaylist, isRedundancy = false) {
1873 const directoryPath = getHLSDirectory(this, isRedundancy)
1875 await remove(directoryPath)
1877 if (isRedundancy !== true) {
1878 const streamingPlaylistWithFiles = streamingPlaylist as MStreamingPlaylistFilesVideo
1879 streamingPlaylistWithFiles.Video = this
1881 if (!Array.isArray(streamingPlaylistWithFiles.VideoFiles)) {
1882 streamingPlaylistWithFiles.VideoFiles = await streamingPlaylistWithFiles.$get('VideoFiles')
1885 // Remove physical files and torrents
1887 streamingPlaylistWithFiles.VideoFiles.map(file => streamingPlaylistWithFiles.removeTorrent(file))
1893 if (this.isOwned()) return false
1895 return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)
1898 hasPrivacyForFederation () {
1899 return isPrivacyForFederation(this.privacy)
1902 isNewVideo (newPrivacy: VideoPrivacy) {
1903 return this.hasPrivacyForFederation() === false && isPrivacyForFederation(newPrivacy) === true
1907 this.changed('updatedAt', true)
1913 return this.privacy === VideoPrivacy.PRIVATE || this.privacy === VideoPrivacy.INTERNAL || !!this.VideoBlacklist
1916 setPrivacy (newPrivacy: VideoPrivacy) {
1917 if (this.privacy === VideoPrivacy.PRIVATE && newPrivacy !== VideoPrivacy.PRIVATE) {
1918 this.publishedAt = new Date()
1921 this.privacy = newPrivacy
1925 return this.privacy === VideoPrivacy.PRIVATE ||
1926 this.privacy === VideoPrivacy.UNLISTED ||
1927 this.privacy === VideoPrivacy.INTERNAL
1930 async publishIfNeededAndSave (t: Transaction) {
1931 if (this.state !== VideoState.PUBLISHED) {
1932 this.state = VideoState.PUBLISHED
1933 this.publishedAt = new Date()
1934 await this.save({ transaction: t })
1943 if (this.isOwned()) {
1945 baseUrlHttp: WEBSERVER.URL,
1946 baseUrlWs: WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT
1951 baseUrlHttp: REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host,
1952 baseUrlWs: REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1956 getTrackerUrls (baseUrlHttp: string, baseUrlWs: string) {
1957 return [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1960 getTorrentUrl (videoFile: MVideoFile, baseUrlHttp: string) {
1961 return baseUrlHttp + STATIC_PATHS.TORRENTS + getTorrentFileName(this, videoFile)
1964 getTorrentDownloadUrl (videoFile: MVideoFile, baseUrlHttp: string) {
1965 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + getTorrentFileName(this, videoFile)
1968 getVideoFileUrl (videoFile: MVideoFile, baseUrlHttp: string) {
1969 return baseUrlHttp + STATIC_PATHS.WEBSEED + getVideoFilename(this, videoFile)
1972 getVideoFileMetadataUrl (videoFile: MVideoFile, baseUrlHttp: string) {
1973 const path = '/api/v1/videos/'
1975 return this.isOwned()
1976 ? baseUrlHttp + path + this.uuid + '/metadata/' + videoFile.id
1977 : videoFile.metadataUrl
1980 getVideoRedundancyUrl (videoFile: MVideoFile, baseUrlHttp: string) {
1981 return baseUrlHttp + STATIC_PATHS.REDUNDANCY + getVideoFilename(this, videoFile)
1984 getVideoFileDownloadUrl (videoFile: MVideoFile, baseUrlHttp: string) {
1985 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + getVideoFilename(this, videoFile)
1988 getBandwidthBits (videoFile: MVideoFile) {
1989 return Math.ceil((videoFile.size * 8) / this.duration)