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, isStateForFederation } from '@server/helpers/video'
29 import { LiveManager } from '@server/lib/live-manager'
30 import { getHLSDirectory, getTorrentFileName, getTorrentFilePath, getVideoFilename, getVideoFilePath } from '@server/lib/video-paths'
31 import { getServerActor } from '@server/models/application/application'
32 import { ModelCache } from '@server/models/model-cache'
33 import { VideoFile } from '@shared/models/videos/video-file.model'
34 import { ResultList, UserRight, VideoPrivacy, VideoState } from '../../../shared'
35 import { VideoObject } from '../../../shared/models/activitypub/objects'
36 import { Video, VideoDetails } from '../../../shared/models/videos'
37 import { ThumbnailType } from '../../../shared/models/videos/thumbnail.type'
38 import { VideoFilter } from '../../../shared/models/videos/video-query.type'
39 import { VideoStreamingPlaylistType } from '../../../shared/models/videos/video-streaming-playlist.type'
40 import { peertubeTruncate } from '../../helpers/core-utils'
41 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
42 import { isBooleanValid } from '../../helpers/custom-validators/misc'
45 isVideoDescriptionValid,
53 } from '../../helpers/custom-validators/videos'
54 import { getVideoFileResolution } from '../../helpers/ffmpeg-utils'
55 import { logger } from '../../helpers/logger'
56 import { CONFIG } from '../../initializers/config'
63 STATIC_DOWNLOAD_PATHS,
71 } from '../../initializers/constants'
72 import { sendDeleteVideo } from '../../lib/activitypub/send'
75 MChannelAccountDefault,
78 MStreamingPlaylistFilesVideo,
82 MVideoAccountLightBlacklistAllFiles,
87 MVideoFormattableDetails,
93 MVideoThumbnailBlacklist,
97 } from '../../types/models'
98 import { MThumbnail } from '../../types/models/video/thumbnail'
99 import { MVideoFile, MVideoFileRedundanciesOpt, MVideoFileStreamingPlaylistVideo } from '../../types/models/video/video-file'
100 import { VideoAbuseModel } from '../abuse/video-abuse'
101 import { AccountModel } from '../account/account'
102 import { AccountVideoRateModel } from '../account/account-video-rate'
103 import { UserVideoHistoryModel } from '../account/user-video-history'
104 import { ActorModel } from '../activitypub/actor'
105 import { AvatarModel } from '../avatar/avatar'
106 import { VideoRedundancyModel } from '../redundancy/video-redundancy'
107 import { ServerModel } from '../server/server'
108 import { buildTrigramSearchIndex, buildWhereIdOrUUID, getVideoSort, isOutdated, throwIfNotValid } from '../utils'
109 import { ScheduleVideoUpdateModel } from './schedule-video-update'
110 import { TagModel } from './tag'
111 import { ThumbnailModel } from './thumbnail'
112 import { VideoBlacklistModel } from './video-blacklist'
113 import { VideoCaptionModel } from './video-caption'
114 import { ScopeNames as VideoChannelScopeNames, SummaryOptions, VideoChannelModel } from './video-channel'
115 import { VideoCommentModel } from './video-comment'
116 import { VideoFileModel } from './video-file'
118 videoFilesModelToFormattedJSON,
119 VideoFormattingJSONOptions,
120 videoModelToActivityPubObject,
121 videoModelToFormattedDetailsJSON,
122 videoModelToFormattedJSON
123 } from './video-format-utils'
124 import { VideoImportModel } from './video-import'
125 import { VideoLiveModel } from './video-live'
126 import { VideoPlaylistElementModel } from './video-playlist-element'
127 import { buildListQuery, BuildVideosQueryOptions, wrapForAPIResults } from './video-query-builder'
128 import { VideoShareModel } from './video-share'
129 import { VideoStreamingPlaylistModel } from './video-streaming-playlist'
130 import { VideoTagModel } from './video-tag'
131 import { VideoViewModel } from './video-view'
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',
146 WITH_LIVE = 'WITH_LIVE'
149 export type ForAPIOptions = {
152 videoPlaylistId?: number
156 withAccountBlockerIds?: number[]
159 export type AvailableForListIDsOptions = {
160 serverAccountId: number
161 followerActorId: number
162 includeLocalVideos: boolean
164 attributesType?: 'none' | 'id' | 'all'
167 categoryOneOf?: number[]
169 licenceOneOf?: number[]
170 languageOneOf?: string[]
177 videoChannelId?: number
179 videoPlaylistId?: number
181 trendingDays?: number
182 user?: MUserAccountId
183 historyOfUser?: MUserId
185 baseWhere?: WhereOptions[]
189 [ScopeNames.WITH_IMMUTABLE_ATTRIBUTES]: {
190 attributes: [ 'id', 'url', 'uuid', 'remote' ]
192 [ScopeNames.FOR_API]: (options: ForAPIOptions) => {
193 const query: FindOptions = {
196 model: VideoChannelModel.scope({
198 VideoChannelScopeNames.SUMMARY, {
200 withAccountBlockerIds: options.withAccountBlockerIds
207 attributes: [ 'type', 'filename' ],
208 model: ThumbnailModel,
222 if (options.withFiles === true) {
224 model: VideoFileModel,
229 if (options.videoPlaylistId) {
231 model: VideoPlaylistElementModel.unscoped(),
234 videoPlaylistId: options.videoPlaylistId
241 [ScopeNames.WITH_THUMBNAILS]: {
244 model: ThumbnailModel,
249 [ScopeNames.WITH_LIVE]: {
252 model: VideoLiveModel.unscoped(),
257 [ScopeNames.WITH_USER_ID]: {
260 attributes: [ 'accountId' ],
261 model: VideoChannelModel.unscoped(),
265 attributes: [ 'userId' ],
266 model: AccountModel.unscoped(),
273 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
276 model: VideoChannelModel.unscoped(),
281 exclude: [ 'privateKey', 'publicKey' ]
283 model: ActorModel.unscoped(),
287 attributes: [ 'host' ],
288 model: ServerModel.unscoped(),
292 model: AvatarModel.unscoped(),
298 model: AccountModel.unscoped(),
302 model: ActorModel.unscoped(),
304 exclude: [ 'privateKey', 'publicKey' ]
309 attributes: [ 'host' ],
310 model: ServerModel.unscoped(),
314 model: AvatarModel.unscoped(),
325 [ScopeNames.WITH_TAGS]: {
326 include: [ TagModel ]
328 [ScopeNames.WITH_BLACKLISTED]: {
331 attributes: [ 'id', 'reason', 'unfederated' ],
332 model: VideoBlacklistModel,
337 [ScopeNames.WITH_WEBTORRENT_FILES]: (withRedundancies = false) => {
338 let subInclude: any[] = []
340 if (withRedundancies === true) {
343 attributes: [ 'fileUrl' ],
344 model: VideoRedundancyModel.unscoped(),
353 model: VideoFileModel,
354 separate: true, // We may have multiple files, having multiple redundancies so let's separate this join
361 [ScopeNames.WITH_STREAMING_PLAYLISTS]: (withRedundancies = false) => {
362 const subInclude: IncludeOptions[] = [
364 model: VideoFileModel,
369 if (withRedundancies === true) {
371 attributes: [ 'fileUrl' ],
372 model: VideoRedundancyModel.unscoped(),
380 model: VideoStreamingPlaylistModel.unscoped(),
381 separate: true, // We may have multiple streaming playlists, having multiple redundancies so let's separate this join
388 [ScopeNames.WITH_SCHEDULED_UPDATE]: {
391 model: ScheduleVideoUpdateModel.unscoped(),
396 [ScopeNames.WITH_USER_HISTORY]: (userId: number) => {
400 attributes: [ 'currentTime' ],
401 model: UserVideoHistoryModel.unscoped(),
414 buildTrigramSearchIndex('video_name_trigram', 'name'),
416 { fields: [ 'createdAt' ] },
419 { name: 'publishedAt', order: 'DESC' },
420 { name: 'id', order: 'ASC' }
423 { fields: [ 'duration' ] },
424 { fields: [ 'views' ] },
425 { fields: [ 'channelId' ] },
427 fields: [ 'originallyPublishedAt' ],
429 originallyPublishedAt: {
435 fields: [ 'category' ], // We don't care videos with an unknown category
443 fields: [ 'licence' ], // We don't care videos with an unknown licence
451 fields: [ 'language' ], // We don't care videos with an unknown language
459 fields: [ 'nsfw' ], // Most of the videos are not NSFW
465 fields: [ 'remote' ], // Only index local videos
480 export class VideoModel extends Model<VideoModel> {
483 @Default(DataType.UUIDV4)
485 @Column(DataType.UUID)
489 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
495 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category', true))
501 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence', true))
507 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language', true))
508 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
512 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
514 privacy: VideoPrivacy
517 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
523 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description', true))
524 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
529 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support', true))
530 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
534 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
569 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
570 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
575 commentsEnabled: boolean
579 downloadEnabled: boolean
583 waitTranscoding: boolean
587 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
598 @Default(DataType.NOW)
605 originallyPublishedAt: Date
607 @ForeignKey(() => VideoChannelModel)
611 @BelongsTo(() => VideoChannelModel, {
617 VideoChannel: VideoChannelModel
619 @BelongsToMany(() => TagModel, {
620 foreignKey: 'videoId',
621 through: () => VideoTagModel,
626 @HasMany(() => ThumbnailModel, {
634 Thumbnails: ThumbnailModel[]
636 @HasMany(() => VideoPlaylistElementModel, {
643 VideoPlaylistElements: VideoPlaylistElementModel[]
645 @HasMany(() => VideoAbuseModel, {
652 VideoAbuses: VideoAbuseModel[]
654 @HasMany(() => VideoFileModel, {
662 VideoFiles: VideoFileModel[]
664 @HasMany(() => VideoStreamingPlaylistModel, {
672 VideoStreamingPlaylists: VideoStreamingPlaylistModel[]
674 @HasMany(() => VideoShareModel, {
681 VideoShares: VideoShareModel[]
683 @HasMany(() => AccountVideoRateModel, {
690 AccountVideoRates: AccountVideoRateModel[]
692 @HasMany(() => VideoCommentModel, {
700 VideoComments: VideoCommentModel[]
702 @HasMany(() => VideoViewModel, {
709 VideoViews: VideoViewModel[]
711 @HasMany(() => UserVideoHistoryModel, {
718 UserVideoHistories: UserVideoHistoryModel[]
720 @HasOne(() => ScheduleVideoUpdateModel, {
727 ScheduleVideoUpdate: ScheduleVideoUpdateModel
729 @HasOne(() => VideoBlacklistModel, {
736 VideoBlacklist: VideoBlacklistModel
738 @HasOne(() => VideoLiveModel, {
745 VideoLive: VideoLiveModel
747 @HasOne(() => VideoImportModel, {
754 VideoImport: VideoImportModel
756 @HasMany(() => VideoCaptionModel, {
763 ['separate' as any]: true
765 VideoCaptions: VideoCaptionModel[]
768 static async sendDelete (instance: MVideoAccountLight, options) {
769 if (instance.isOwned()) {
770 if (!instance.VideoChannel) {
771 instance.VideoChannel = await instance.$get('VideoChannel', {
776 transaction: options.transaction
777 }) as MChannelAccountDefault
780 return sendDeleteVideo(instance, options.transaction)
787 static async removeFiles (instance: VideoModel) {
788 const tasks: Promise<any>[] = []
790 logger.info('Removing files of video %s.', instance.url)
792 if (instance.isOwned()) {
793 if (!Array.isArray(instance.VideoFiles)) {
794 instance.VideoFiles = await instance.$get('VideoFiles')
797 // Remove physical files and torrents
798 instance.VideoFiles.forEach(file => {
799 tasks.push(instance.removeFile(file))
800 tasks.push(instance.removeTorrent(file))
803 // Remove playlists file
804 if (!Array.isArray(instance.VideoStreamingPlaylists)) {
805 instance.VideoStreamingPlaylists = await instance.$get('VideoStreamingPlaylists')
808 for (const p of instance.VideoStreamingPlaylists) {
809 tasks.push(instance.removeStreamingPlaylistFiles(p))
813 // Do not wait video deletion because we could be in a transaction
816 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
823 static stopLiveIfNeeded (instance: VideoModel) {
824 if (!instance.isLive) return
826 logger.info('Stopping live of video %s after video deletion.', instance.uuid)
828 return LiveManager.Instance.stopSessionOf(instance.id)
832 static invalidateCache (instance: VideoModel) {
833 ModelCache.Instance.invalidateCache('video', instance.id)
837 static async saveEssentialDataToAbuses (instance: VideoModel, options) {
838 const tasks: Promise<any>[] = []
840 if (!Array.isArray(instance.VideoAbuses)) {
841 instance.VideoAbuses = await instance.$get('VideoAbuses')
843 if (instance.VideoAbuses.length === 0) return undefined
846 logger.info('Saving video abuses details of video %s.', instance.url)
848 const details = instance.toFormattedDetailsJSON()
850 for (const abuse of instance.VideoAbuses) {
851 abuse.deletedVideo = details
852 tasks.push(abuse.save({ transaction: options.transaction }))
857 logger.error('Some errors when saving details of video %s in its abuses before destroy hook.', instance.uuid, { err })
863 static listLocal (): Bluebird<MVideoWithAllFiles[]> {
870 return VideoModel.scope([
871 ScopeNames.WITH_WEBTORRENT_FILES,
872 ScopeNames.WITH_STREAMING_PLAYLISTS,
873 ScopeNames.WITH_THUMBNAILS
877 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
878 function getRawQuery (select: string) {
879 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
880 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
881 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
882 'WHERE "Account"."actorId" = ' + actorId
883 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
884 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
885 'WHERE "VideoShare"."actorId" = ' + actorId
887 return `(${queryVideo}) UNION (${queryVideoShare})`
890 const rawQuery = getRawQuery('"Video"."id"')
891 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
897 order: getVideoSort('-createdAt', [ 'Tags', 'name', 'ASC' ] as any), // FIXME: sequelize typings
900 [Op.in]: Sequelize.literal('(' + rawQuery + ')')
902 [Op.or]: getPrivaciesForFederation()
906 attributes: [ 'language', 'fileUrl' ],
907 model: VideoCaptionModel.unscoped(),
911 attributes: [ 'id', 'url' ],
912 model: VideoShareModel.unscoped(),
914 // We only want videos shared by this actor
929 attributes: [ 'id', 'url' ],
930 model: ActorModel.unscoped()
935 model: VideoChannelModel.unscoped(),
939 attributes: [ 'name' ],
940 model: AccountModel.unscoped(),
944 attributes: [ 'id', 'url', 'followersUrl' ],
945 model: ActorModel.unscoped(),
951 attributes: [ 'id', 'url', 'followersUrl' ],
952 model: ActorModel.unscoped(),
958 model: VideoStreamingPlaylistModel.unscoped(),
962 model: VideoFileModel,
973 return Bluebird.all([
974 VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findAll(query),
975 VideoModel.sequelize.query<{ total: string }>(rawCountQuery, { type: QueryTypes.SELECT })
976 ]).then(([ rows, totals ]) => {
977 // totals: totalVideos + totalVideoShares
979 let totalVideoShares = 0
980 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
981 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
983 const total = totalVideos + totalVideoShares
991 static listUserVideosForApi (
998 function buildBaseQuery (): FindOptions {
1002 order: getVideoSort(sort),
1005 model: VideoChannelModel,
1009 model: AccountModel,
1021 baseQuery = Object.assign(baseQuery, {
1024 [Op.iLike]: '%' + search + '%'
1033 const countQuery = buildBaseQuery()
1034 const findQuery = buildBaseQuery()
1036 const findScopes: (string | ScopeOptions)[] = [
1037 ScopeNames.WITH_SCHEDULED_UPDATE,
1038 ScopeNames.WITH_BLACKLISTED,
1039 ScopeNames.WITH_THUMBNAILS
1042 return Promise.all([
1043 VideoModel.count(countQuery),
1044 VideoModel.scope(findScopes).findAll<MVideoForUser>(findQuery)
1045 ]).then(([ count, rows ]) => {
1053 static async listForApi (options: {
1058 includeLocalVideos: boolean
1060 categoryOneOf?: number[]
1061 licenceOneOf?: number[]
1062 languageOneOf?: string[]
1063 tagsOneOf?: string[]
1064 tagsAllOf?: string[]
1065 filter?: VideoFilter
1067 videoChannelId?: number
1068 followerActorId?: number
1069 videoPlaylistId?: number
1070 trendingDays?: number
1071 user?: MUserAccountId
1072 historyOfUser?: MUserId
1073 countVideos?: boolean
1075 if (options.filter && options.filter === 'all-local' && !options.user.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1076 throw new Error('Try to filter all-local but no user has not the see all videos right')
1079 const trendingDays = options.sort.endsWith('trending')
1080 ? CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1083 const serverActor = await getServerActor()
1085 // followerActorId === null has a meaning, so just check undefined
1086 const followerActorId = options.followerActorId !== undefined
1087 ? options.followerActorId
1090 const queryOptions = {
1091 start: options.start,
1092 count: options.count,
1095 serverAccountId: serverActor.Account.id,
1097 categoryOneOf: options.categoryOneOf,
1098 licenceOneOf: options.licenceOneOf,
1099 languageOneOf: options.languageOneOf,
1100 tagsOneOf: options.tagsOneOf,
1101 tagsAllOf: options.tagsAllOf,
1102 filter: options.filter,
1103 withFiles: options.withFiles,
1104 accountId: options.accountId,
1105 videoChannelId: options.videoChannelId,
1106 videoPlaylistId: options.videoPlaylistId,
1107 includeLocalVideos: options.includeLocalVideos,
1109 historyOfUser: options.historyOfUser,
1113 return VideoModel.getAvailableForApi(queryOptions, options.countVideos)
1116 static async searchAndPopulateAccountAndServer (options: {
1117 includeLocalVideos: boolean
1122 startDate?: string // ISO 8601
1123 endDate?: string // ISO 8601
1124 originallyPublishedStartDate?: string
1125 originallyPublishedEndDate?: string
1127 categoryOneOf?: number[]
1128 licenceOneOf?: number[]
1129 languageOneOf?: string[]
1130 tagsOneOf?: string[]
1131 tagsAllOf?: string[]
1132 durationMin?: number // seconds
1133 durationMax?: number // seconds
1134 user?: MUserAccountId
1135 filter?: VideoFilter
1137 const serverActor = await getServerActor()
1138 const queryOptions = {
1139 followerActorId: serverActor.id,
1140 serverAccountId: serverActor.Account.id,
1141 includeLocalVideos: options.includeLocalVideos,
1143 categoryOneOf: options.categoryOneOf,
1144 licenceOneOf: options.licenceOneOf,
1145 languageOneOf: options.languageOneOf,
1146 tagsOneOf: options.tagsOneOf,
1147 tagsAllOf: options.tagsAllOf,
1149 filter: options.filter,
1150 start: options.start,
1151 count: options.count,
1153 startDate: options.startDate,
1154 endDate: options.endDate,
1155 originallyPublishedStartDate: options.originallyPublishedStartDate,
1156 originallyPublishedEndDate: options.originallyPublishedEndDate,
1158 durationMin: options.durationMin,
1159 durationMax: options.durationMax,
1161 search: options.search
1164 return VideoModel.getAvailableForApi(queryOptions)
1167 static countLocalLives () {
1175 return VideoModel.count(options)
1178 static countLivesOfAccount (accountId: number) {
1187 model: VideoChannelModel.unscoped(),
1195 return VideoModel.count(options)
1198 static load (id: number | string, t?: Transaction): Bluebird<MVideoThumbnail> {
1199 const where = buildWhereIdOrUUID(id)
1205 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1208 static loadWithBlacklist (id: number | string, t?: Transaction): Bluebird<MVideoThumbnailBlacklist> {
1209 const where = buildWhereIdOrUUID(id)
1215 return VideoModel.scope([
1216 ScopeNames.WITH_THUMBNAILS,
1217 ScopeNames.WITH_BLACKLISTED
1221 static loadImmutableAttributes (id: number | string, t?: Transaction): Bluebird<MVideoImmutable> {
1224 where: buildWhereIdOrUUID(id),
1228 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1231 return ModelCache.Instance.doCache({
1232 cacheType: 'load-video-immutable-id',
1239 static loadWithRights (id: number | string, t?: Transaction): Bluebird<MVideoWithRights> {
1240 const where = buildWhereIdOrUUID(id)
1246 return VideoModel.scope([
1247 ScopeNames.WITH_BLACKLISTED,
1248 ScopeNames.WITH_USER_ID,
1249 ScopeNames.WITH_THUMBNAILS
1253 static loadOnlyId (id: number | string, t?: Transaction): Bluebird<MVideoIdThumbnail> {
1254 const where = buildWhereIdOrUUID(id)
1257 attributes: [ 'id' ],
1262 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1265 static loadWithFiles (id: number | string, t?: Transaction, logging?: boolean): Bluebird<MVideoWithAllFiles> {
1266 const where = buildWhereIdOrUUID(id)
1274 return VideoModel.scope([
1275 ScopeNames.WITH_WEBTORRENT_FILES,
1276 ScopeNames.WITH_STREAMING_PLAYLISTS,
1277 ScopeNames.WITH_THUMBNAILS
1281 static loadByUUID (uuid: string): Bluebird<MVideoThumbnail> {
1288 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1291 static loadByUrl (url: string, transaction?: Transaction): Bluebird<MVideoThumbnail> {
1292 const query: FindOptions = {
1299 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(query)
1302 static loadByUrlImmutableAttributes (url: string, transaction?: Transaction): Bluebird<MVideoImmutable> {
1304 const query: FindOptions = {
1311 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1314 return ModelCache.Instance.doCache({
1315 cacheType: 'load-video-immutable-url',
1322 static loadByUrlAndPopulateAccount (url: string, transaction?: Transaction): Bluebird<MVideoAccountLightBlacklistAllFiles> {
1323 const query: FindOptions = {
1330 return VideoModel.scope([
1331 ScopeNames.WITH_ACCOUNT_DETAILS,
1332 ScopeNames.WITH_WEBTORRENT_FILES,
1333 ScopeNames.WITH_STREAMING_PLAYLISTS,
1334 ScopeNames.WITH_THUMBNAILS,
1335 ScopeNames.WITH_BLACKLISTED
1339 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Transaction, userId?: number): Bluebird<MVideoFullLight> {
1340 const where = buildWhereIdOrUUID(id)
1343 order: [ [ 'Tags', 'name', 'ASC' ] ] as any,
1348 const scopes: (string | ScopeOptions)[] = [
1349 ScopeNames.WITH_TAGS,
1350 ScopeNames.WITH_BLACKLISTED,
1351 ScopeNames.WITH_ACCOUNT_DETAILS,
1352 ScopeNames.WITH_SCHEDULED_UPDATE,
1353 ScopeNames.WITH_WEBTORRENT_FILES,
1354 ScopeNames.WITH_STREAMING_PLAYLISTS,
1355 ScopeNames.WITH_THUMBNAILS,
1356 ScopeNames.WITH_LIVE
1360 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1368 static loadForGetAPI (parameters: {
1372 }): Bluebird<MVideoDetails> {
1373 const { id, t, userId } = parameters
1374 const where = buildWhereIdOrUUID(id)
1377 order: [ [ 'Tags', 'name', 'ASC' ] ] as any, // FIXME: sequelize typings
1382 const scopes: (string | ScopeOptions)[] = [
1383 ScopeNames.WITH_TAGS,
1384 ScopeNames.WITH_BLACKLISTED,
1385 ScopeNames.WITH_ACCOUNT_DETAILS,
1386 ScopeNames.WITH_SCHEDULED_UPDATE,
1387 ScopeNames.WITH_THUMBNAILS,
1388 ScopeNames.WITH_LIVE,
1389 { method: [ ScopeNames.WITH_WEBTORRENT_FILES, true ] },
1390 { method: [ ScopeNames.WITH_STREAMING_PLAYLISTS, true ] }
1394 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1402 static async getStats () {
1403 const totalLocalVideos = await VideoModel.count({
1409 let totalLocalVideoViews = await VideoModel.sum('views', {
1415 // Sequelize could return null...
1416 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1418 const { total: totalVideos } = await VideoModel.listForApi({
1421 sort: '-publishedAt',
1422 nsfw: buildNSFWFilter(),
1423 includeLocalVideos: true,
1429 totalLocalVideoViews,
1434 static incrementViews (id: number, views: number) {
1435 return VideoModel.increment('views', {
1443 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1444 // Instances only share videos
1445 const query = 'SELECT 1 FROM "videoShare" ' +
1446 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1447 'WHERE "actorFollow"."actorId" = $followerActorId AND "actorFollow"."state" = \'accepted\' AND "videoShare"."videoId" = $videoId ' +
1451 type: QueryTypes.SELECT as QueryTypes.SELECT,
1452 bind: { followerActorId, videoId },
1456 return VideoModel.sequelize.query(query, options)
1457 .then(results => results.length === 1)
1460 static bulkUpdateSupportField (videoChannel: MChannel, t: Transaction) {
1463 channelId: videoChannel.id
1468 return VideoModel.update({ support: videoChannel.support }, options)
1471 static getAllIdsFromChannel (videoChannel: MChannelId): Bluebird<number[]> {
1473 attributes: [ 'id' ],
1475 channelId: videoChannel.id
1479 return VideoModel.findAll(query)
1480 .then(videos => videos.map(v => v.id))
1483 // threshold corresponds to how many video the field should have to be returned
1484 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1485 const serverActor = await getServerActor()
1486 const followerActorId = serverActor.id
1488 const queryOptions: BuildVideosQueryOptions = {
1489 attributes: [ `"${field}"` ],
1490 group: `GROUP BY "${field}"`,
1491 having: `HAVING COUNT("${field}") >= ${threshold}`,
1495 serverAccountId: serverActor.Account.id,
1497 includeLocalVideos: true
1500 const { query, replacements } = buildListQuery(VideoModel, queryOptions)
1502 return this.sequelize.query<any>(query, { replacements, type: QueryTypes.SELECT })
1503 .then(rows => rows.map(r => r[field]))
1506 static buildTrendingQuery (trendingDays: number) {
1510 model: VideoViewModel,
1514 [Op.gte]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1520 private static async getAvailableForApi (
1521 options: BuildVideosQueryOptions,
1523 ): Promise<ResultList<VideoModel>> {
1524 function getCount () {
1525 if (countVideos !== true) return Promise.resolve(undefined)
1527 const countOptions = Object.assign({}, options, { isCount: true })
1528 const { query: queryCount, replacements: replacementsCount } = buildListQuery(VideoModel, countOptions)
1530 return VideoModel.sequelize.query<any>(queryCount, { replacements: replacementsCount, type: QueryTypes.SELECT })
1531 .then(rows => rows.length !== 0 ? rows[0].total : 0)
1534 function getModels () {
1535 if (options.count === 0) return Promise.resolve([])
1537 const { query, replacements, order } = buildListQuery(VideoModel, options)
1538 const queryModels = wrapForAPIResults(query, replacements, options, order)
1540 return VideoModel.sequelize.query<any>(queryModels, { replacements, type: QueryTypes.SELECT, nest: true })
1541 .then(rows => VideoModel.buildAPIResult(rows))
1544 const [ count, rows ] = await Promise.all([ getCount(), getModels() ])
1552 private static buildAPIResult (rows: any[]) {
1553 const videosMemo: { [ id: number ]: VideoModel } = {}
1554 const videoStreamingPlaylistMemo: { [ id: number ]: VideoStreamingPlaylistModel } = {}
1556 const thumbnailsDone = new Set<number>()
1557 const historyDone = new Set<number>()
1558 const videoFilesDone = new Set<number>()
1560 const videos: VideoModel[] = []
1562 const avatarKeys = [ 'id', 'filename', 'fileUrl', 'onDisk', 'createdAt', 'updatedAt' ]
1563 const actorKeys = [ 'id', 'preferredUsername', 'url', 'serverId', 'avatarId' ]
1564 const serverKeys = [ 'id', 'host' ]
1565 const videoFileKeys = [ 'id', 'createdAt', 'updatedAt', 'resolution', 'size', 'extname', 'infoHash', 'fps', 'videoId' ]
1566 const videoStreamingPlaylistKeys = [ 'id' ]
1589 'originallyPublishedAt',
1595 function buildActor (rowActor: any) {
1596 const avatarModel = rowActor.Avatar.id !== null
1597 ? new AvatarModel(pick(rowActor.Avatar, avatarKeys))
1600 const serverModel = rowActor.Server.id !== null
1601 ? new ServerModel(pick(rowActor.Server, serverKeys))
1604 const actorModel = new ActorModel(pick(rowActor, actorKeys))
1605 actorModel.Avatar = avatarModel
1606 actorModel.Server = serverModel
1611 for (const row of rows) {
1612 if (!videosMemo[row.id]) {
1614 const channel = row.VideoChannel
1615 const channelModel = new VideoChannelModel(pick(channel, [ 'id', 'name', 'description', 'actorId' ]))
1616 channelModel.Actor = buildActor(channel.Actor)
1618 const account = row.VideoChannel.Account
1619 const accountModel = new AccountModel(pick(account, [ 'id', 'name' ]))
1620 accountModel.Actor = buildActor(account.Actor)
1622 channelModel.Account = accountModel
1624 const videoModel = new VideoModel(pick(row, videoKeys))
1625 videoModel.VideoChannel = channelModel
1627 videoModel.UserVideoHistories = []
1628 videoModel.Thumbnails = []
1629 videoModel.VideoFiles = []
1630 videoModel.VideoStreamingPlaylists = []
1632 videosMemo[row.id] = videoModel
1633 // Don't take object value to have a sorted array
1634 videos.push(videoModel)
1637 const videoModel = videosMemo[row.id]
1639 if (row.userVideoHistory?.id && !historyDone.has(row.userVideoHistory.id)) {
1640 const historyModel = new UserVideoHistoryModel(pick(row.userVideoHistory, [ 'id', 'currentTime' ]))
1641 videoModel.UserVideoHistories.push(historyModel)
1643 historyDone.add(row.userVideoHistory.id)
1646 if (row.Thumbnails?.id && !thumbnailsDone.has(row.Thumbnails.id)) {
1647 const thumbnailModel = new ThumbnailModel(pick(row.Thumbnails, [ 'id', 'type', 'filename' ]))
1648 videoModel.Thumbnails.push(thumbnailModel)
1650 thumbnailsDone.add(row.Thumbnails.id)
1653 if (row.VideoFiles?.id && !videoFilesDone.has(row.VideoFiles.id)) {
1654 const videoFileModel = new VideoFileModel(pick(row.VideoFiles, videoFileKeys))
1655 videoModel.VideoFiles.push(videoFileModel)
1657 videoFilesDone.add(row.VideoFiles.id)
1660 if (row.VideoFiles?.id && !videoFilesDone.has(row.VideoFiles.id)) {
1661 const videoFileModel = new VideoFileModel(pick(row.VideoFiles, videoFileKeys))
1662 videoModel.VideoFiles.push(videoFileModel)
1664 videoFilesDone.add(row.VideoFiles.id)
1667 if (row.VideoStreamingPlaylists?.id && !videoStreamingPlaylistMemo[row.VideoStreamingPlaylists.id]) {
1668 const streamingPlaylist = new VideoStreamingPlaylistModel(pick(row.VideoStreamingPlaylists, videoStreamingPlaylistKeys))
1669 streamingPlaylist.VideoFiles = []
1671 videoModel.VideoStreamingPlaylists.push(streamingPlaylist)
1673 videoStreamingPlaylistMemo[streamingPlaylist.id] = streamingPlaylist
1676 if (row.VideoStreamingPlaylists?.VideoFiles?.id && !videoFilesDone.has(row.VideoStreamingPlaylists.VideoFiles.id)) {
1677 const streamingPlaylist = videoStreamingPlaylistMemo[row.VideoStreamingPlaylists.id]
1679 const videoFileModel = new VideoFileModel(pick(row.VideoStreamingPlaylists.VideoFiles, videoFileKeys))
1680 streamingPlaylist.VideoFiles.push(videoFileModel)
1682 videoFilesDone.add(row.VideoStreamingPlaylists.VideoFiles.id)
1689 static getCategoryLabel (id: number) {
1690 return VIDEO_CATEGORIES[id] || 'Misc'
1693 static getLicenceLabel (id: number) {
1694 return VIDEO_LICENCES[id] || 'Unknown'
1697 static getLanguageLabel (id: string) {
1698 return VIDEO_LANGUAGES[id] || 'Unknown'
1701 static getPrivacyLabel (id: number) {
1702 return VIDEO_PRIVACIES[id] || 'Unknown'
1705 static getStateLabel (id: number) {
1706 return VIDEO_STATES[id] || 'Unknown'
1710 return !!this.VideoBlacklist
1714 return this.VideoChannel.Account.Actor.Server?.isBlocked() || this.VideoChannel.Account.isBlocked()
1717 getQualityFileBy<T extends MVideoWithFile> (this: T, fun: (files: MVideoFile[], it: (file: MVideoFile) => number) => MVideoFile) {
1718 if (Array.isArray(this.VideoFiles) && this.VideoFiles.length !== 0) {
1719 const file = fun(this.VideoFiles, file => file.resolution)
1721 return Object.assign(file, { Video: this })
1724 // No webtorrent files, try with streaming playlist files
1725 if (Array.isArray(this.VideoStreamingPlaylists) && this.VideoStreamingPlaylists.length !== 0) {
1726 const streamingPlaylistWithVideo = Object.assign(this.VideoStreamingPlaylists[0], { Video: this })
1728 const file = fun(streamingPlaylistWithVideo.VideoFiles, file => file.resolution)
1729 return Object.assign(file, { VideoStreamingPlaylist: streamingPlaylistWithVideo })
1735 getMaxQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1736 return this.getQualityFileBy(maxBy)
1739 getMinQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1740 return this.getQualityFileBy(minBy)
1743 getWebTorrentFile<T extends MVideoWithFile> (this: T, resolution: number): MVideoFileVideo {
1744 if (Array.isArray(this.VideoFiles) === false) return undefined
1746 const file = this.VideoFiles.find(f => f.resolution === resolution)
1747 if (!file) return undefined
1749 return Object.assign(file, { Video: this })
1752 async addAndSaveThumbnail (thumbnail: MThumbnail, transaction: Transaction) {
1753 thumbnail.videoId = this.id
1755 const savedThumbnail = await thumbnail.save({ transaction })
1757 if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = []
1759 // Already have this thumbnail, skip
1760 if (this.Thumbnails.find(t => t.id === savedThumbnail.id)) return
1762 this.Thumbnails.push(savedThumbnail)
1765 generateThumbnailName () {
1766 return this.uuid + '.jpg'
1770 if (Array.isArray(this.Thumbnails) === false) return undefined
1772 return this.Thumbnails.find(t => t.type === ThumbnailType.MINIATURE)
1775 generatePreviewName () {
1776 return this.uuid + '.jpg'
1780 return !!this.getPreview()
1784 if (Array.isArray(this.Thumbnails) === false) return undefined
1786 return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW)
1790 return this.remote === false
1793 getWatchStaticPath () {
1794 return '/videos/watch/' + this.uuid
1797 getEmbedStaticPath () {
1798 return '/videos/embed/' + this.uuid
1801 getMiniatureStaticPath () {
1802 const thumbnail = this.getMiniature()
1803 if (!thumbnail) return null
1805 return join(STATIC_PATHS.THUMBNAILS, thumbnail.filename)
1808 getPreviewStaticPath () {
1809 const preview = this.getPreview()
1810 if (!preview) return null
1812 // We use a local cache, so specify our cache endpoint instead of potential remote URL
1813 return join(LAZY_STATIC_PATHS.PREVIEWS, preview.filename)
1816 toFormattedJSON (this: MVideoFormattable, options?: VideoFormattingJSONOptions): Video {
1817 return videoModelToFormattedJSON(this, options)
1820 toFormattedDetailsJSON (this: MVideoFormattableDetails): VideoDetails {
1821 return videoModelToFormattedDetailsJSON(this)
1824 getFormattedVideoFilesJSON (): VideoFile[] {
1825 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1826 let files: MVideoFileRedundanciesOpt[] = []
1828 if (Array.isArray(this.VideoFiles)) {
1829 files = files.concat(this.VideoFiles)
1832 for (const p of (this.VideoStreamingPlaylists || [])) {
1833 files = files.concat(p.VideoFiles || [])
1836 return videoFilesModelToFormattedJSON(this, baseUrlHttp, baseUrlWs, files)
1839 toActivityPubObject (this: MVideoAP): VideoObject {
1840 return videoModelToActivityPubObject(this)
1843 getTruncatedDescription () {
1844 if (!this.description) return null
1846 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1847 return peertubeTruncate(this.description, { length: maxLength })
1850 getMaxQualityResolution () {
1851 const file = this.getMaxQualityFile()
1852 const videoOrPlaylist = file.getVideoOrStreamingPlaylist()
1853 const originalFilePath = getVideoFilePath(videoOrPlaylist, file)
1855 return getVideoFileResolution(originalFilePath)
1858 getDescriptionAPIPath () {
1859 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1862 getHLSPlaylist (): MStreamingPlaylistFilesVideo {
1863 if (!this.VideoStreamingPlaylists) return undefined
1865 const playlist = this.VideoStreamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
1866 playlist.Video = this
1871 setHLSPlaylist (playlist: MStreamingPlaylist) {
1872 const toAdd = [ playlist ] as [ VideoStreamingPlaylistModel ]
1874 if (Array.isArray(this.VideoStreamingPlaylists) === false || this.VideoStreamingPlaylists.length === 0) {
1875 this.VideoStreamingPlaylists = toAdd
1879 this.VideoStreamingPlaylists = this.VideoStreamingPlaylists
1880 .filter(s => s.type !== VideoStreamingPlaylistType.HLS)
1884 removeFile (videoFile: MVideoFile, isRedundancy = false) {
1885 const filePath = getVideoFilePath(this, videoFile, isRedundancy)
1886 return remove(filePath)
1887 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1890 removeTorrent (videoFile: MVideoFile) {
1891 const torrentPath = getTorrentFilePath(this, videoFile)
1892 return remove(torrentPath)
1893 .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err }))
1896 async removeStreamingPlaylistFiles (streamingPlaylist: MStreamingPlaylist, isRedundancy = false) {
1897 const directoryPath = getHLSDirectory(this, isRedundancy)
1899 await remove(directoryPath)
1901 if (isRedundancy !== true) {
1902 const streamingPlaylistWithFiles = streamingPlaylist as MStreamingPlaylistFilesVideo
1903 streamingPlaylistWithFiles.Video = this
1905 if (!Array.isArray(streamingPlaylistWithFiles.VideoFiles)) {
1906 streamingPlaylistWithFiles.VideoFiles = await streamingPlaylistWithFiles.$get('VideoFiles')
1909 // Remove physical files and torrents
1911 streamingPlaylistWithFiles.VideoFiles.map(file => streamingPlaylistWithFiles.removeTorrent(file))
1917 if (this.isOwned()) return false
1919 return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)
1922 hasPrivacyForFederation () {
1923 return isPrivacyForFederation(this.privacy)
1926 hasStateForFederation () {
1927 return isStateForFederation(this.state)
1930 isNewVideo (newPrivacy: VideoPrivacy) {
1931 return this.hasPrivacyForFederation() === false && isPrivacyForFederation(newPrivacy) === true
1935 this.changed('updatedAt', true)
1941 return this.privacy === VideoPrivacy.PRIVATE || this.privacy === VideoPrivacy.INTERNAL || !!this.VideoBlacklist
1944 setPrivacy (newPrivacy: VideoPrivacy) {
1945 if (this.privacy === VideoPrivacy.PRIVATE && newPrivacy !== VideoPrivacy.PRIVATE) {
1946 this.publishedAt = new Date()
1949 this.privacy = newPrivacy
1953 return this.privacy === VideoPrivacy.PRIVATE ||
1954 this.privacy === VideoPrivacy.UNLISTED ||
1955 this.privacy === VideoPrivacy.INTERNAL
1958 async publishIfNeededAndSave (t: Transaction) {
1959 if (this.state !== VideoState.PUBLISHED) {
1960 this.state = VideoState.PUBLISHED
1961 this.publishedAt = new Date()
1962 await this.save({ transaction: t })
1971 if (this.isOwned()) {
1973 baseUrlHttp: WEBSERVER.URL,
1974 baseUrlWs: WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT
1979 baseUrlHttp: REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host,
1980 baseUrlWs: REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1984 getTrackerUrls (baseUrlHttp: string, baseUrlWs: string) {
1985 return [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1988 getTorrentUrl (videoFile: MVideoFile, baseUrlHttp: string) {
1989 return baseUrlHttp + STATIC_PATHS.TORRENTS + getTorrentFileName(this, videoFile)
1992 getTorrentDownloadUrl (videoFile: MVideoFile, baseUrlHttp: string) {
1993 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + getTorrentFileName(this, videoFile)
1996 getVideoFileUrl (videoFile: MVideoFile, baseUrlHttp: string) {
1997 return baseUrlHttp + STATIC_PATHS.WEBSEED + getVideoFilename(this, videoFile)
2000 getVideoFileMetadataUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2001 const path = '/api/v1/videos/'
2003 return this.isOwned()
2004 ? baseUrlHttp + path + this.uuid + '/metadata/' + videoFile.id
2005 : videoFile.metadataUrl
2008 getVideoRedundancyUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2009 return baseUrlHttp + STATIC_PATHS.REDUNDANCY + getVideoFilename(this, videoFile)
2012 getVideoFileDownloadUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2013 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + getVideoFilename(this, videoFile)
2016 getBandwidthBits (videoFile: MVideoFile) {
2017 return Math.ceil((videoFile.size * 8) / this.duration)