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 { VideoTorrentObject } 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, 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'
131 export enum ScopeNames {
132 AVAILABLE_FOR_LIST_IDS = 'AVAILABLE_FOR_LIST_IDS',
134 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
135 WITH_TAGS = 'WITH_TAGS',
136 WITH_WEBTORRENT_FILES = 'WITH_WEBTORRENT_FILES',
137 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
138 WITH_BLACKLISTED = 'WITH_BLACKLISTED',
139 WITH_USER_HISTORY = 'WITH_USER_HISTORY',
140 WITH_STREAMING_PLAYLISTS = 'WITH_STREAMING_PLAYLISTS',
141 WITH_USER_ID = 'WITH_USER_ID',
142 WITH_IMMUTABLE_ATTRIBUTES = 'WITH_IMMUTABLE_ATTRIBUTES',
143 WITH_THUMBNAILS = 'WITH_THUMBNAILS'
146 export type ForAPIOptions = {
149 videoPlaylistId?: number
153 withAccountBlockerIds?: number[]
156 export type AvailableForListIDsOptions = {
157 serverAccountId: number
158 followerActorId: number
159 includeLocalVideos: boolean
161 attributesType?: 'none' | 'id' | 'all'
164 categoryOneOf?: number[]
166 licenceOneOf?: number[]
167 languageOneOf?: string[]
174 videoChannelId?: number
176 videoPlaylistId?: number
178 trendingDays?: number
179 user?: MUserAccountId
180 historyOfUser?: MUserId
182 baseWhere?: WhereOptions[]
186 [ScopeNames.WITH_IMMUTABLE_ATTRIBUTES]: {
187 attributes: [ 'id', 'url', 'uuid', 'remote' ]
189 [ScopeNames.FOR_API]: (options: ForAPIOptions) => {
190 const query: FindOptions = {
193 model: VideoChannelModel.scope({
195 VideoChannelScopeNames.SUMMARY, {
197 withAccountBlockerIds: options.withAccountBlockerIds
204 attributes: [ 'type', 'filename' ],
205 model: ThumbnailModel,
219 if (options.withFiles === true) {
221 model: VideoFileModel,
226 if (options.videoPlaylistId) {
228 model: VideoPlaylistElementModel.unscoped(),
231 videoPlaylistId: options.videoPlaylistId
238 [ScopeNames.WITH_THUMBNAILS]: {
241 model: ThumbnailModel,
246 [ScopeNames.WITH_USER_ID]: {
249 attributes: [ 'accountId' ],
250 model: VideoChannelModel.unscoped(),
254 attributes: [ 'userId' ],
255 model: AccountModel.unscoped(),
262 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
265 model: VideoChannelModel.unscoped(),
270 exclude: [ 'privateKey', 'publicKey' ]
272 model: ActorModel.unscoped(),
276 attributes: [ 'host' ],
277 model: ServerModel.unscoped(),
281 model: AvatarModel.unscoped(),
287 model: AccountModel.unscoped(),
291 model: ActorModel.unscoped(),
293 exclude: [ 'privateKey', 'publicKey' ]
298 attributes: [ 'host' ],
299 model: ServerModel.unscoped(),
303 model: AvatarModel.unscoped(),
314 [ScopeNames.WITH_TAGS]: {
315 include: [ TagModel ]
317 [ScopeNames.WITH_BLACKLISTED]: {
320 attributes: [ 'id', 'reason', 'unfederated' ],
321 model: VideoBlacklistModel,
326 [ScopeNames.WITH_WEBTORRENT_FILES]: (withRedundancies = false) => {
327 let subInclude: any[] = []
329 if (withRedundancies === true) {
332 attributes: [ 'fileUrl' ],
333 model: VideoRedundancyModel.unscoped(),
342 model: VideoFileModel,
343 separate: true, // We may have multiple files, having multiple redundancies so let's separate this join
350 [ScopeNames.WITH_STREAMING_PLAYLISTS]: (withRedundancies = false) => {
351 const subInclude: IncludeOptions[] = [
353 model: VideoFileModel,
358 if (withRedundancies === true) {
360 attributes: [ 'fileUrl' ],
361 model: VideoRedundancyModel.unscoped(),
369 model: VideoStreamingPlaylistModel.unscoped(),
370 separate: true, // We may have multiple streaming playlists, having multiple redundancies so let's separate this join
377 [ScopeNames.WITH_SCHEDULED_UPDATE]: {
380 model: ScheduleVideoUpdateModel.unscoped(),
385 [ScopeNames.WITH_USER_HISTORY]: (userId: number) => {
389 attributes: [ 'currentTime' ],
390 model: UserVideoHistoryModel.unscoped(),
403 buildTrigramSearchIndex('video_name_trigram', 'name'),
405 { fields: [ 'createdAt' ] },
408 { name: 'publishedAt', order: 'DESC' },
409 { name: 'id', order: 'ASC' }
412 { fields: [ 'duration' ] },
413 { fields: [ 'views' ] },
414 { fields: [ 'channelId' ] },
416 fields: [ 'originallyPublishedAt' ],
418 originallyPublishedAt: {
424 fields: [ 'category' ], // We don't care videos with an unknown category
432 fields: [ 'licence' ], // We don't care videos with an unknown licence
440 fields: [ 'language' ], // We don't care videos with an unknown language
448 fields: [ 'nsfw' ], // Most of the videos are not NSFW
454 fields: [ 'remote' ], // Only index local videos
469 export class VideoModel extends Model<VideoModel> {
472 @Default(DataType.UUIDV4)
474 @Column(DataType.UUID)
478 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
484 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category', true))
490 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence', true))
496 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language', true))
497 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
501 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
503 privacy: VideoPrivacy
506 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
512 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description', true))
513 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
518 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support', true))
519 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
523 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
553 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
554 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
559 commentsEnabled: boolean
563 downloadEnabled: boolean
567 waitTranscoding: boolean
571 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
582 @Default(DataType.NOW)
589 originallyPublishedAt: Date
591 @ForeignKey(() => VideoChannelModel)
595 @BelongsTo(() => VideoChannelModel, {
601 VideoChannel: VideoChannelModel
603 @BelongsToMany(() => TagModel, {
604 foreignKey: 'videoId',
605 through: () => VideoTagModel,
610 @HasMany(() => ThumbnailModel, {
618 Thumbnails: ThumbnailModel[]
620 @HasMany(() => VideoPlaylistElementModel, {
627 VideoPlaylistElements: VideoPlaylistElementModel[]
629 @HasMany(() => VideoAbuseModel, {
636 VideoAbuses: VideoAbuseModel[]
638 @HasMany(() => VideoFileModel, {
646 VideoFiles: VideoFileModel[]
648 @HasMany(() => VideoStreamingPlaylistModel, {
656 VideoStreamingPlaylists: VideoStreamingPlaylistModel[]
658 @HasMany(() => VideoShareModel, {
665 VideoShares: VideoShareModel[]
667 @HasMany(() => AccountVideoRateModel, {
674 AccountVideoRates: AccountVideoRateModel[]
676 @HasMany(() => VideoCommentModel, {
684 VideoComments: VideoCommentModel[]
686 @HasMany(() => VideoViewModel, {
693 VideoViews: VideoViewModel[]
695 @HasMany(() => UserVideoHistoryModel, {
702 UserVideoHistories: UserVideoHistoryModel[]
704 @HasOne(() => ScheduleVideoUpdateModel, {
711 ScheduleVideoUpdate: ScheduleVideoUpdateModel
713 @HasOne(() => VideoBlacklistModel, {
720 VideoBlacklist: VideoBlacklistModel
722 @HasOne(() => VideoImportModel, {
729 VideoImport: VideoImportModel
731 @HasMany(() => VideoCaptionModel, {
738 ['separate' as any]: true
740 VideoCaptions: VideoCaptionModel[]
743 static async sendDelete (instance: MVideoAccountLight, options) {
744 if (instance.isOwned()) {
745 if (!instance.VideoChannel) {
746 instance.VideoChannel = await instance.$get('VideoChannel', {
751 transaction: options.transaction
752 }) as MChannelAccountDefault
755 return sendDeleteVideo(instance, options.transaction)
762 static async removeFiles (instance: VideoModel) {
763 const tasks: Promise<any>[] = []
765 logger.info('Removing files of video %s.', instance.url)
767 if (instance.isOwned()) {
768 if (!Array.isArray(instance.VideoFiles)) {
769 instance.VideoFiles = await instance.$get('VideoFiles')
772 // Remove physical files and torrents
773 instance.VideoFiles.forEach(file => {
774 tasks.push(instance.removeFile(file))
775 tasks.push(instance.removeTorrent(file))
778 // Remove playlists file
779 if (!Array.isArray(instance.VideoStreamingPlaylists)) {
780 instance.VideoStreamingPlaylists = await instance.$get('VideoStreamingPlaylists')
783 for (const p of instance.VideoStreamingPlaylists) {
784 tasks.push(instance.removeStreamingPlaylistFiles(p))
788 // Do not wait video deletion because we could be in a transaction
791 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
798 static invalidateCache (instance: VideoModel) {
799 ModelCache.Instance.invalidateCache('video', instance.id)
803 static async saveEssentialDataToAbuses (instance: VideoModel, options) {
804 const tasks: Promise<any>[] = []
806 if (!Array.isArray(instance.VideoAbuses)) {
807 instance.VideoAbuses = await instance.$get('VideoAbuses')
809 if (instance.VideoAbuses.length === 0) return undefined
812 logger.info('Saving video abuses details of video %s.', instance.url)
814 const details = instance.toFormattedDetailsJSON()
816 for (const abuse of instance.VideoAbuses) {
817 abuse.deletedVideo = details
818 tasks.push(abuse.save({ transaction: options.transaction }))
823 logger.error('Some errors when saving details of video %s in its abuses before destroy hook.', instance.uuid, { err })
829 static listLocal (): Bluebird<MVideoWithAllFiles[]> {
836 return VideoModel.scope([
837 ScopeNames.WITH_WEBTORRENT_FILES,
838 ScopeNames.WITH_STREAMING_PLAYLISTS,
839 ScopeNames.WITH_THUMBNAILS
843 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
844 function getRawQuery (select: string) {
845 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
846 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
847 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
848 'WHERE "Account"."actorId" = ' + actorId
849 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
850 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
851 'WHERE "VideoShare"."actorId" = ' + actorId
853 return `(${queryVideo}) UNION (${queryVideoShare})`
856 const rawQuery = getRawQuery('"Video"."id"')
857 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
863 order: getVideoSort('-createdAt', [ 'Tags', 'name', 'ASC' ] as any), // FIXME: sequelize typings
866 [Op.in]: Sequelize.literal('(' + rawQuery + ')')
868 [Op.or]: getPrivaciesForFederation()
872 attributes: [ 'language', 'fileUrl' ],
873 model: VideoCaptionModel.unscoped(),
877 attributes: [ 'id', 'url' ],
878 model: VideoShareModel.unscoped(),
880 // We only want videos shared by this actor
895 attributes: [ 'id', 'url' ],
896 model: ActorModel.unscoped()
901 model: VideoChannelModel.unscoped(),
905 attributes: [ 'name' ],
906 model: AccountModel.unscoped(),
910 attributes: [ 'id', 'url', 'followersUrl' ],
911 model: ActorModel.unscoped(),
917 attributes: [ 'id', 'url', 'followersUrl' ],
918 model: ActorModel.unscoped(),
928 return Bluebird.all([
929 VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findAll(query),
930 VideoModel.sequelize.query<{ total: string }>(rawCountQuery, { type: QueryTypes.SELECT })
931 ]).then(([ rows, totals ]) => {
932 // totals: totalVideos + totalVideoShares
934 let totalVideoShares = 0
935 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
936 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
938 const total = totalVideos + totalVideoShares
946 static listUserVideosForApi (
953 function buildBaseQuery (): FindOptions {
957 order: getVideoSort(sort),
960 model: VideoChannelModel,
976 baseQuery = Object.assign(baseQuery, {
979 [Op.iLike]: '%' + search + '%'
988 const countQuery = buildBaseQuery()
989 const findQuery = buildBaseQuery()
991 const findScopes: (string | ScopeOptions)[] = [
992 ScopeNames.WITH_SCHEDULED_UPDATE,
993 ScopeNames.WITH_BLACKLISTED,
994 ScopeNames.WITH_THUMBNAILS
998 VideoModel.count(countQuery),
999 VideoModel.scope(findScopes).findAll<MVideoForUser>(findQuery)
1000 ]).then(([ count, rows ]) => {
1008 static async listForApi (options: {
1013 includeLocalVideos: boolean
1015 categoryOneOf?: number[]
1016 licenceOneOf?: number[]
1017 languageOneOf?: string[]
1018 tagsOneOf?: string[]
1019 tagsAllOf?: string[]
1020 filter?: VideoFilter
1022 videoChannelId?: number
1023 followerActorId?: number
1024 videoPlaylistId?: number
1025 trendingDays?: number
1026 user?: MUserAccountId
1027 historyOfUser?: MUserId
1028 countVideos?: boolean
1030 if (options.filter && options.filter === 'all-local' && !options.user.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1031 throw new Error('Try to filter all-local but no user has not the see all videos right')
1034 const trendingDays = options.sort.endsWith('trending')
1035 ? CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1038 const serverActor = await getServerActor()
1040 // followerActorId === null has a meaning, so just check undefined
1041 const followerActorId = options.followerActorId !== undefined
1042 ? options.followerActorId
1045 const queryOptions = {
1046 start: options.start,
1047 count: options.count,
1050 serverAccountId: serverActor.Account.id,
1052 categoryOneOf: options.categoryOneOf,
1053 licenceOneOf: options.licenceOneOf,
1054 languageOneOf: options.languageOneOf,
1055 tagsOneOf: options.tagsOneOf,
1056 tagsAllOf: options.tagsAllOf,
1057 filter: options.filter,
1058 withFiles: options.withFiles,
1059 accountId: options.accountId,
1060 videoChannelId: options.videoChannelId,
1061 videoPlaylistId: options.videoPlaylistId,
1062 includeLocalVideos: options.includeLocalVideos,
1064 historyOfUser: options.historyOfUser,
1068 return VideoModel.getAvailableForApi(queryOptions, options.countVideos)
1071 static async searchAndPopulateAccountAndServer (options: {
1072 includeLocalVideos: boolean
1077 startDate?: string // ISO 8601
1078 endDate?: string // ISO 8601
1079 originallyPublishedStartDate?: string
1080 originallyPublishedEndDate?: string
1082 categoryOneOf?: number[]
1083 licenceOneOf?: number[]
1084 languageOneOf?: string[]
1085 tagsOneOf?: string[]
1086 tagsAllOf?: string[]
1087 durationMin?: number // seconds
1088 durationMax?: number // seconds
1089 user?: MUserAccountId
1090 filter?: VideoFilter
1092 const serverActor = await getServerActor()
1093 const queryOptions = {
1094 followerActorId: serverActor.id,
1095 serverAccountId: serverActor.Account.id,
1096 includeLocalVideos: options.includeLocalVideos,
1098 categoryOneOf: options.categoryOneOf,
1099 licenceOneOf: options.licenceOneOf,
1100 languageOneOf: options.languageOneOf,
1101 tagsOneOf: options.tagsOneOf,
1102 tagsAllOf: options.tagsAllOf,
1104 filter: options.filter,
1105 start: options.start,
1106 count: options.count,
1108 startDate: options.startDate,
1109 endDate: options.endDate,
1110 originallyPublishedStartDate: options.originallyPublishedStartDate,
1111 originallyPublishedEndDate: options.originallyPublishedEndDate,
1113 durationMin: options.durationMin,
1114 durationMax: options.durationMax,
1116 search: options.search
1119 return VideoModel.getAvailableForApi(queryOptions)
1122 static load (id: number | string, t?: Transaction): Bluebird<MVideoThumbnail> {
1123 const where = buildWhereIdOrUUID(id)
1129 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1132 static loadWithBlacklist (id: number | string, t?: Transaction): Bluebird<MVideoThumbnailBlacklist> {
1133 const where = buildWhereIdOrUUID(id)
1139 return VideoModel.scope([
1140 ScopeNames.WITH_THUMBNAILS,
1141 ScopeNames.WITH_BLACKLISTED
1145 static loadImmutableAttributes (id: number | string, t?: Transaction): Bluebird<MVideoImmutable> {
1148 where: buildWhereIdOrUUID(id),
1152 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1155 return ModelCache.Instance.doCache({
1156 cacheType: 'load-video-immutable-id',
1163 static loadWithRights (id: number | string, t?: Transaction): Bluebird<MVideoWithRights> {
1164 const where = buildWhereIdOrUUID(id)
1170 return VideoModel.scope([
1171 ScopeNames.WITH_BLACKLISTED,
1172 ScopeNames.WITH_USER_ID,
1173 ScopeNames.WITH_THUMBNAILS
1177 static loadOnlyId (id: number | string, t?: Transaction): Bluebird<MVideoIdThumbnail> {
1178 const where = buildWhereIdOrUUID(id)
1181 attributes: [ 'id' ],
1186 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1189 static loadWithFiles (id: number | string, t?: Transaction, logging?: boolean): Bluebird<MVideoWithAllFiles> {
1190 const where = buildWhereIdOrUUID(id)
1198 return VideoModel.scope([
1199 ScopeNames.WITH_WEBTORRENT_FILES,
1200 ScopeNames.WITH_STREAMING_PLAYLISTS,
1201 ScopeNames.WITH_THUMBNAILS
1205 static loadByUUID (uuid: string): Bluebird<MVideoThumbnail> {
1212 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1215 static loadByUrl (url: string, transaction?: Transaction): Bluebird<MVideoThumbnail> {
1216 const query: FindOptions = {
1223 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(query)
1226 static loadByUrlImmutableAttributes (url: string, transaction?: Transaction): Bluebird<MVideoImmutable> {
1228 const query: FindOptions = {
1235 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1238 return ModelCache.Instance.doCache({
1239 cacheType: 'load-video-immutable-url',
1246 static loadByUrlAndPopulateAccount (url: string, transaction?: Transaction): Bluebird<MVideoAccountLightBlacklistAllFiles> {
1247 const query: FindOptions = {
1254 return VideoModel.scope([
1255 ScopeNames.WITH_ACCOUNT_DETAILS,
1256 ScopeNames.WITH_WEBTORRENT_FILES,
1257 ScopeNames.WITH_STREAMING_PLAYLISTS,
1258 ScopeNames.WITH_THUMBNAILS,
1259 ScopeNames.WITH_BLACKLISTED
1263 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Transaction, userId?: number): Bluebird<MVideoFullLight> {
1264 const where = buildWhereIdOrUUID(id)
1267 order: [ [ 'Tags', 'name', 'ASC' ] ] as any,
1272 const scopes: (string | ScopeOptions)[] = [
1273 ScopeNames.WITH_TAGS,
1274 ScopeNames.WITH_BLACKLISTED,
1275 ScopeNames.WITH_ACCOUNT_DETAILS,
1276 ScopeNames.WITH_SCHEDULED_UPDATE,
1277 ScopeNames.WITH_WEBTORRENT_FILES,
1278 ScopeNames.WITH_STREAMING_PLAYLISTS,
1279 ScopeNames.WITH_THUMBNAILS
1283 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1291 static loadForGetAPI (parameters: {
1295 }): Bluebird<MVideoDetails> {
1296 const { id, t, userId } = parameters
1297 const where = buildWhereIdOrUUID(id)
1300 order: [ [ 'Tags', 'name', 'ASC' ] ] as any, // FIXME: sequelize typings
1305 const scopes: (string | ScopeOptions)[] = [
1306 ScopeNames.WITH_TAGS,
1307 ScopeNames.WITH_BLACKLISTED,
1308 ScopeNames.WITH_ACCOUNT_DETAILS,
1309 ScopeNames.WITH_SCHEDULED_UPDATE,
1310 ScopeNames.WITH_THUMBNAILS,
1311 { method: [ ScopeNames.WITH_WEBTORRENT_FILES, true ] },
1312 { method: [ ScopeNames.WITH_STREAMING_PLAYLISTS, true ] }
1316 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1324 static async getStats () {
1325 const totalLocalVideos = await VideoModel.count({
1331 let totalLocalVideoViews = await VideoModel.sum('views', {
1337 // Sequelize could return null...
1338 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1340 const { total: totalVideos } = await VideoModel.listForApi({
1343 sort: '-publishedAt',
1344 nsfw: buildNSFWFilter(),
1345 includeLocalVideos: true,
1351 totalLocalVideoViews,
1356 static incrementViews (id: number, views: number) {
1357 return VideoModel.increment('views', {
1365 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1366 // Instances only share videos
1367 const query = 'SELECT 1 FROM "videoShare" ' +
1368 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1369 'WHERE "actorFollow"."actorId" = $followerActorId AND "actorFollow"."state" = \'accepted\' AND "videoShare"."videoId" = $videoId ' +
1373 type: QueryTypes.SELECT as QueryTypes.SELECT,
1374 bind: { followerActorId, videoId },
1378 return VideoModel.sequelize.query(query, options)
1379 .then(results => results.length === 1)
1382 static bulkUpdateSupportField (videoChannel: MChannel, t: Transaction) {
1385 channelId: videoChannel.id
1390 return VideoModel.update({ support: videoChannel.support }, options)
1393 static getAllIdsFromChannel (videoChannel: MChannelId): Bluebird<number[]> {
1395 attributes: [ 'id' ],
1397 channelId: videoChannel.id
1401 return VideoModel.findAll(query)
1402 .then(videos => videos.map(v => v.id))
1405 // threshold corresponds to how many video the field should have to be returned
1406 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1407 const serverActor = await getServerActor()
1408 const followerActorId = serverActor.id
1410 const queryOptions: BuildVideosQueryOptions = {
1411 attributes: [ `"${field}"` ],
1412 group: `GROUP BY "${field}"`,
1413 having: `HAVING COUNT("${field}") >= ${threshold}`,
1417 serverAccountId: serverActor.Account.id,
1419 includeLocalVideos: true
1422 const { query, replacements } = buildListQuery(VideoModel, queryOptions)
1424 return this.sequelize.query<any>(query, { replacements, type: QueryTypes.SELECT })
1425 .then(rows => rows.map(r => r[field]))
1428 static buildTrendingQuery (trendingDays: number) {
1432 model: VideoViewModel,
1436 [Op.gte]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1442 private static async getAvailableForApi (
1443 options: BuildVideosQueryOptions,
1445 ): Promise<ResultList<VideoModel>> {
1446 function getCount () {
1447 if (countVideos !== true) return Promise.resolve(undefined)
1449 const countOptions = Object.assign({}, options, { isCount: true })
1450 const { query: queryCount, replacements: replacementsCount } = buildListQuery(VideoModel, countOptions)
1452 return VideoModel.sequelize.query<any>(queryCount, { replacements: replacementsCount, type: QueryTypes.SELECT })
1453 .then(rows => rows.length !== 0 ? rows[0].total : 0)
1456 function getModels () {
1457 if (options.count === 0) return Promise.resolve([])
1459 const { query, replacements, order } = buildListQuery(VideoModel, options)
1460 const queryModels = wrapForAPIResults(query, replacements, options, order)
1462 return VideoModel.sequelize.query<any>(queryModels, { replacements, type: QueryTypes.SELECT, nest: true })
1463 .then(rows => VideoModel.buildAPIResult(rows))
1466 const [ count, rows ] = await Promise.all([ getCount(), getModels() ])
1474 private static buildAPIResult (rows: any[]) {
1475 const memo: { [ id: number ]: VideoModel } = {}
1477 const thumbnailsDone = new Set<number>()
1478 const historyDone = new Set<number>()
1479 const videoFilesDone = new Set<number>()
1481 const videos: VideoModel[] = []
1483 const avatarKeys = [ 'id', 'filename', 'fileUrl', 'onDisk', 'createdAt', 'updatedAt' ]
1484 const actorKeys = [ 'id', 'preferredUsername', 'url', 'serverId', 'avatarId' ]
1485 const serverKeys = [ 'id', 'host' ]
1486 const videoFileKeys = [ 'id', 'createdAt', 'updatedAt', 'resolution', 'size', 'extname', 'infoHash', 'fps', 'videoId' ]
1509 'originallyPublishedAt',
1515 function buildActor (rowActor: any) {
1516 const avatarModel = rowActor.Avatar.id !== null
1517 ? new AvatarModel(pick(rowActor.Avatar, avatarKeys))
1520 const serverModel = rowActor.Server.id !== null
1521 ? new ServerModel(pick(rowActor.Server, serverKeys))
1524 const actorModel = new ActorModel(pick(rowActor, actorKeys))
1525 actorModel.Avatar = avatarModel
1526 actorModel.Server = serverModel
1531 for (const row of rows) {
1532 if (!memo[row.id]) {
1534 const channel = row.VideoChannel
1535 const channelModel = new VideoChannelModel(pick(channel, [ 'id', 'name', 'description', 'actorId' ]))
1536 channelModel.Actor = buildActor(channel.Actor)
1538 const account = row.VideoChannel.Account
1539 const accountModel = new AccountModel(pick(account, [ 'id', 'name' ]))
1540 accountModel.Actor = buildActor(account.Actor)
1542 channelModel.Account = accountModel
1544 const videoModel = new VideoModel(pick(row, videoKeys))
1545 videoModel.VideoChannel = channelModel
1547 videoModel.UserVideoHistories = []
1548 videoModel.Thumbnails = []
1549 videoModel.VideoFiles = []
1551 memo[row.id] = videoModel
1552 // Don't take object value to have a sorted array
1553 videos.push(videoModel)
1556 const videoModel = memo[row.id]
1558 if (row.userVideoHistory?.id && !historyDone.has(row.userVideoHistory.id)) {
1559 const historyModel = new UserVideoHistoryModel(pick(row.userVideoHistory, [ 'id', 'currentTime' ]))
1560 videoModel.UserVideoHistories.push(historyModel)
1562 historyDone.add(row.userVideoHistory.id)
1565 if (row.Thumbnails?.id && !thumbnailsDone.has(row.Thumbnails.id)) {
1566 const thumbnailModel = new ThumbnailModel(pick(row.Thumbnails, [ 'id', 'type', 'filename' ]))
1567 videoModel.Thumbnails.push(thumbnailModel)
1569 thumbnailsDone.add(row.Thumbnails.id)
1572 if (row.VideoFiles?.id && !videoFilesDone.has(row.VideoFiles.id)) {
1573 const videoFileModel = new VideoFileModel(pick(row.VideoFiles, videoFileKeys))
1574 videoModel.VideoFiles.push(videoFileModel)
1576 videoFilesDone.add(row.VideoFiles.id)
1583 static getCategoryLabel (id: number) {
1584 return VIDEO_CATEGORIES[id] || 'Misc'
1587 static getLicenceLabel (id: number) {
1588 return VIDEO_LICENCES[id] || 'Unknown'
1591 static getLanguageLabel (id: string) {
1592 return VIDEO_LANGUAGES[id] || 'Unknown'
1595 static getPrivacyLabel (id: number) {
1596 return VIDEO_PRIVACIES[id] || 'Unknown'
1599 static getStateLabel (id: number) {
1600 return VIDEO_STATES[id] || 'Unknown'
1604 return !!this.VideoBlacklist
1608 return this.VideoChannel.Account.Actor.Server?.isBlocked() || this.VideoChannel.Account.isBlocked()
1611 getQualityFileBy<T extends MVideoWithFile> (this: T, fun: (files: MVideoFile[], it: (file: MVideoFile) => number) => MVideoFile) {
1612 if (Array.isArray(this.VideoFiles) && this.VideoFiles.length !== 0) {
1613 const file = fun(this.VideoFiles, file => file.resolution)
1615 return Object.assign(file, { Video: this })
1618 // No webtorrent files, try with streaming playlist files
1619 if (Array.isArray(this.VideoStreamingPlaylists) && this.VideoStreamingPlaylists.length !== 0) {
1620 const streamingPlaylistWithVideo = Object.assign(this.VideoStreamingPlaylists[0], { Video: this })
1622 const file = fun(streamingPlaylistWithVideo.VideoFiles, file => file.resolution)
1623 return Object.assign(file, { VideoStreamingPlaylist: streamingPlaylistWithVideo })
1629 getMaxQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1630 return this.getQualityFileBy(maxBy)
1633 getMinQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1634 return this.getQualityFileBy(minBy)
1637 getWebTorrentFile<T extends MVideoWithFile> (this: T, resolution: number): MVideoFileVideo {
1638 if (Array.isArray(this.VideoFiles) === false) return undefined
1640 const file = this.VideoFiles.find(f => f.resolution === resolution)
1641 if (!file) return undefined
1643 return Object.assign(file, { Video: this })
1646 async addAndSaveThumbnail (thumbnail: MThumbnail, transaction: Transaction) {
1647 thumbnail.videoId = this.id
1649 const savedThumbnail = await thumbnail.save({ transaction })
1651 if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = []
1653 // Already have this thumbnail, skip
1654 if (this.Thumbnails.find(t => t.id === savedThumbnail.id)) return
1656 this.Thumbnails.push(savedThumbnail)
1659 generateThumbnailName () {
1660 return this.uuid + '.jpg'
1664 if (Array.isArray(this.Thumbnails) === false) return undefined
1666 return this.Thumbnails.find(t => t.type === ThumbnailType.MINIATURE)
1669 generatePreviewName () {
1670 return this.uuid + '.jpg'
1674 return !!this.getPreview()
1678 if (Array.isArray(this.Thumbnails) === false) return undefined
1680 return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW)
1684 return this.remote === false
1687 getWatchStaticPath () {
1688 return '/videos/watch/' + this.uuid
1691 getEmbedStaticPath () {
1692 return '/videos/embed/' + this.uuid
1695 getMiniatureStaticPath () {
1696 const thumbnail = this.getMiniature()
1697 if (!thumbnail) return null
1699 return join(STATIC_PATHS.THUMBNAILS, thumbnail.filename)
1702 getPreviewStaticPath () {
1703 const preview = this.getPreview()
1704 if (!preview) return null
1706 // We use a local cache, so specify our cache endpoint instead of potential remote URL
1707 return join(LAZY_STATIC_PATHS.PREVIEWS, preview.filename)
1710 toFormattedJSON (this: MVideoFormattable, options?: VideoFormattingJSONOptions): Video {
1711 return videoModelToFormattedJSON(this, options)
1714 toFormattedDetailsJSON (this: MVideoFormattableDetails): VideoDetails {
1715 return videoModelToFormattedDetailsJSON(this)
1718 getFormattedVideoFilesJSON (): VideoFile[] {
1719 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1720 return videoFilesModelToFormattedJSON(this, baseUrlHttp, baseUrlWs, this.VideoFiles)
1723 toActivityPubObject (this: MVideoAP): VideoTorrentObject {
1724 return videoModelToActivityPubObject(this)
1727 getTruncatedDescription () {
1728 if (!this.description) return null
1730 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1731 return peertubeTruncate(this.description, { length: maxLength })
1734 getMaxQualityResolution () {
1735 const file = this.getMaxQualityFile()
1736 const videoOrPlaylist = file.getVideoOrStreamingPlaylist()
1737 const originalFilePath = getVideoFilePath(videoOrPlaylist, file)
1739 return getVideoFileResolution(originalFilePath)
1742 getDescriptionAPIPath () {
1743 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1746 getHLSPlaylist (): MStreamingPlaylistFilesVideo {
1747 if (!this.VideoStreamingPlaylists) return undefined
1749 const playlist = this.VideoStreamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
1750 playlist.Video = this
1755 setHLSPlaylist (playlist: MStreamingPlaylist) {
1756 const toAdd = [ playlist ] as [ VideoStreamingPlaylistModel ]
1758 if (Array.isArray(this.VideoStreamingPlaylists) === false || this.VideoStreamingPlaylists.length === 0) {
1759 this.VideoStreamingPlaylists = toAdd
1763 this.VideoStreamingPlaylists = this.VideoStreamingPlaylists
1764 .filter(s => s.type !== VideoStreamingPlaylistType.HLS)
1768 removeFile (videoFile: MVideoFile, isRedundancy = false) {
1769 const filePath = getVideoFilePath(this, videoFile, isRedundancy)
1770 return remove(filePath)
1771 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1774 removeTorrent (videoFile: MVideoFile) {
1775 const torrentPath = getTorrentFilePath(this, videoFile)
1776 return remove(torrentPath)
1777 .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err }))
1780 async removeStreamingPlaylistFiles (streamingPlaylist: MStreamingPlaylist, isRedundancy = false) {
1781 const directoryPath = getHLSDirectory(this, isRedundancy)
1783 await remove(directoryPath)
1785 if (isRedundancy !== true) {
1786 const streamingPlaylistWithFiles = streamingPlaylist as MStreamingPlaylistFilesVideo
1787 streamingPlaylistWithFiles.Video = this
1789 if (!Array.isArray(streamingPlaylistWithFiles.VideoFiles)) {
1790 streamingPlaylistWithFiles.VideoFiles = await streamingPlaylistWithFiles.$get('VideoFiles')
1793 // Remove physical files and torrents
1795 streamingPlaylistWithFiles.VideoFiles.map(file => streamingPlaylistWithFiles.removeTorrent(file))
1801 if (this.isOwned()) return false
1803 return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)
1806 hasPrivacyForFederation () {
1807 return isPrivacyForFederation(this.privacy)
1810 isNewVideo (newPrivacy: VideoPrivacy) {
1811 return this.hasPrivacyForFederation() === false && isPrivacyForFederation(newPrivacy) === true
1815 this.changed('updatedAt', true)
1821 return this.privacy === VideoPrivacy.PRIVATE || this.privacy === VideoPrivacy.INTERNAL || !!this.VideoBlacklist
1824 setPrivacy (newPrivacy: VideoPrivacy) {
1825 if (this.privacy === VideoPrivacy.PRIVATE && newPrivacy !== VideoPrivacy.PRIVATE) {
1826 this.publishedAt = new Date()
1829 this.privacy = newPrivacy
1833 return this.privacy === VideoPrivacy.PRIVATE ||
1834 this.privacy === VideoPrivacy.UNLISTED ||
1835 this.privacy === VideoPrivacy.INTERNAL
1838 async publishIfNeededAndSave (t: Transaction) {
1839 if (this.state !== VideoState.PUBLISHED) {
1840 this.state = VideoState.PUBLISHED
1841 this.publishedAt = new Date()
1842 await this.save({ transaction: t })
1851 if (this.isOwned()) {
1853 baseUrlHttp: WEBSERVER.URL,
1854 baseUrlWs: WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT
1859 baseUrlHttp: REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host,
1860 baseUrlWs: REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1864 getTrackerUrls (baseUrlHttp: string, baseUrlWs: string) {
1865 return [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1868 getTorrentUrl (videoFile: MVideoFile, baseUrlHttp: string) {
1869 return baseUrlHttp + STATIC_PATHS.TORRENTS + getTorrentFileName(this, videoFile)
1872 getTorrentDownloadUrl (videoFile: MVideoFile, baseUrlHttp: string) {
1873 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + getTorrentFileName(this, videoFile)
1876 getVideoFileUrl (videoFile: MVideoFile, baseUrlHttp: string) {
1877 return baseUrlHttp + STATIC_PATHS.WEBSEED + getVideoFilename(this, videoFile)
1880 getVideoFileMetadataUrl (videoFile: MVideoFile, baseUrlHttp: string) {
1881 const path = '/api/v1/videos/'
1883 return this.isOwned()
1884 ? baseUrlHttp + path + this.uuid + '/metadata/' + videoFile.id
1885 : videoFile.metadataUrl
1888 getVideoRedundancyUrl (videoFile: MVideoFile, baseUrlHttp: string) {
1889 return baseUrlHttp + STATIC_PATHS.REDUNDANCY + getVideoFilename(this, videoFile)
1892 getVideoFileDownloadUrl (videoFile: MVideoFile, baseUrlHttp: string) {
1893 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + getVideoFilename(this, videoFile)
1896 getBandwidthBits (videoFile: MVideoFile) {
1897 return Math.ceil((videoFile.size * 8) / this.duration)