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'
132 export enum ScopeNames {
133 AVAILABLE_FOR_LIST_IDS = 'AVAILABLE_FOR_LIST_IDS',
135 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
136 WITH_TAGS = 'WITH_TAGS',
137 WITH_WEBTORRENT_FILES = 'WITH_WEBTORRENT_FILES',
138 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
139 WITH_BLACKLISTED = 'WITH_BLACKLISTED',
140 WITH_USER_HISTORY = 'WITH_USER_HISTORY',
141 WITH_STREAMING_PLAYLISTS = 'WITH_STREAMING_PLAYLISTS',
142 WITH_USER_ID = 'WITH_USER_ID',
143 WITH_IMMUTABLE_ATTRIBUTES = 'WITH_IMMUTABLE_ATTRIBUTES',
144 WITH_THUMBNAILS = 'WITH_THUMBNAILS'
147 export type ForAPIOptions = {
150 videoPlaylistId?: number
154 withAccountBlockerIds?: number[]
157 export type AvailableForListIDsOptions = {
158 serverAccountId: number
159 followerActorId: number
160 includeLocalVideos: boolean
162 attributesType?: 'none' | 'id' | 'all'
165 categoryOneOf?: number[]
167 licenceOneOf?: number[]
168 languageOneOf?: string[]
175 videoChannelId?: number
177 videoPlaylistId?: number
179 trendingDays?: number
180 user?: MUserAccountId
181 historyOfUser?: MUserId
183 baseWhere?: WhereOptions[]
187 [ScopeNames.WITH_IMMUTABLE_ATTRIBUTES]: {
188 attributes: [ 'id', 'url', 'uuid', 'remote' ]
190 [ScopeNames.FOR_API]: (options: ForAPIOptions) => {
191 const query: FindOptions = {
194 model: VideoChannelModel.scope({
196 VideoChannelScopeNames.SUMMARY, {
198 withAccountBlockerIds: options.withAccountBlockerIds
205 attributes: [ 'type', 'filename' ],
206 model: ThumbnailModel,
220 if (options.withFiles === true) {
222 model: VideoFileModel,
227 if (options.videoPlaylistId) {
229 model: VideoPlaylistElementModel.unscoped(),
232 videoPlaylistId: options.videoPlaylistId
239 [ScopeNames.WITH_THUMBNAILS]: {
242 model: ThumbnailModel,
247 [ScopeNames.WITH_USER_ID]: {
250 attributes: [ 'accountId' ],
251 model: VideoChannelModel.unscoped(),
255 attributes: [ 'userId' ],
256 model: AccountModel.unscoped(),
263 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
266 model: VideoChannelModel.unscoped(),
271 exclude: [ 'privateKey', 'publicKey' ]
273 model: ActorModel.unscoped(),
277 attributes: [ 'host' ],
278 model: ServerModel.unscoped(),
282 model: AvatarModel.unscoped(),
288 model: AccountModel.unscoped(),
292 model: ActorModel.unscoped(),
294 exclude: [ 'privateKey', 'publicKey' ]
299 attributes: [ 'host' ],
300 model: ServerModel.unscoped(),
304 model: AvatarModel.unscoped(),
315 [ScopeNames.WITH_TAGS]: {
316 include: [ TagModel ]
318 [ScopeNames.WITH_BLACKLISTED]: {
321 attributes: [ 'id', 'reason', 'unfederated' ],
322 model: VideoBlacklistModel,
327 [ScopeNames.WITH_WEBTORRENT_FILES]: (withRedundancies = false) => {
328 let subInclude: any[] = []
330 if (withRedundancies === true) {
333 attributes: [ 'fileUrl' ],
334 model: VideoRedundancyModel.unscoped(),
343 model: VideoFileModel,
344 separate: true, // We may have multiple files, having multiple redundancies so let's separate this join
351 [ScopeNames.WITH_STREAMING_PLAYLISTS]: (withRedundancies = false) => {
352 const subInclude: IncludeOptions[] = [
354 model: VideoFileModel,
359 if (withRedundancies === true) {
361 attributes: [ 'fileUrl' ],
362 model: VideoRedundancyModel.unscoped(),
370 model: VideoStreamingPlaylistModel.unscoped(),
371 separate: true, // We may have multiple streaming playlists, having multiple redundancies so let's separate this join
378 [ScopeNames.WITH_SCHEDULED_UPDATE]: {
381 model: ScheduleVideoUpdateModel.unscoped(),
386 [ScopeNames.WITH_USER_HISTORY]: (userId: number) => {
390 attributes: [ 'currentTime' ],
391 model: UserVideoHistoryModel.unscoped(),
404 buildTrigramSearchIndex('video_name_trigram', 'name'),
406 { fields: [ 'createdAt' ] },
409 { name: 'publishedAt', order: 'DESC' },
410 { name: 'id', order: 'ASC' }
413 { fields: [ 'duration' ] },
414 { fields: [ 'views' ] },
415 { fields: [ 'channelId' ] },
417 fields: [ 'originallyPublishedAt' ],
419 originallyPublishedAt: {
425 fields: [ 'category' ], // We don't care videos with an unknown category
433 fields: [ 'licence' ], // We don't care videos with an unknown licence
441 fields: [ 'language' ], // We don't care videos with an unknown language
449 fields: [ 'nsfw' ], // Most of the videos are not NSFW
455 fields: [ 'remote' ], // Only index local videos
470 export class VideoModel extends Model<VideoModel> {
473 @Default(DataType.UUIDV4)
475 @Column(DataType.UUID)
479 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
485 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category', true))
491 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence', true))
497 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language', true))
498 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
502 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
504 privacy: VideoPrivacy
507 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
513 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description', true))
514 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
519 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support', true))
520 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
524 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
559 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
560 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
565 commentsEnabled: boolean
569 downloadEnabled: boolean
573 waitTranscoding: boolean
577 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
588 @Default(DataType.NOW)
595 originallyPublishedAt: Date
597 @ForeignKey(() => VideoChannelModel)
601 @BelongsTo(() => VideoChannelModel, {
607 VideoChannel: VideoChannelModel
609 @BelongsToMany(() => TagModel, {
610 foreignKey: 'videoId',
611 through: () => VideoTagModel,
616 @HasMany(() => ThumbnailModel, {
624 Thumbnails: ThumbnailModel[]
626 @HasMany(() => VideoPlaylistElementModel, {
633 VideoPlaylistElements: VideoPlaylistElementModel[]
635 @HasMany(() => VideoAbuseModel, {
642 VideoAbuses: VideoAbuseModel[]
644 @HasMany(() => VideoFileModel, {
652 VideoFiles: VideoFileModel[]
654 @HasMany(() => VideoStreamingPlaylistModel, {
662 VideoStreamingPlaylists: VideoStreamingPlaylistModel[]
664 @HasMany(() => VideoShareModel, {
671 VideoShares: VideoShareModel[]
673 @HasMany(() => AccountVideoRateModel, {
680 AccountVideoRates: AccountVideoRateModel[]
682 @HasMany(() => VideoCommentModel, {
690 VideoComments: VideoCommentModel[]
692 @HasMany(() => VideoViewModel, {
699 VideoViews: VideoViewModel[]
701 @HasMany(() => UserVideoHistoryModel, {
708 UserVideoHistories: UserVideoHistoryModel[]
710 @HasOne(() => ScheduleVideoUpdateModel, {
717 ScheduleVideoUpdate: ScheduleVideoUpdateModel
719 @HasOne(() => VideoBlacklistModel, {
726 VideoBlacklist: VideoBlacklistModel
728 @HasOne(() => VideoImportModel, {
735 VideoImport: VideoImportModel
737 @HasMany(() => VideoCaptionModel, {
744 ['separate' as any]: true
746 VideoCaptions: VideoCaptionModel[]
749 static async sendDelete (instance: MVideoAccountLight, options) {
750 if (instance.isOwned()) {
751 if (!instance.VideoChannel) {
752 instance.VideoChannel = await instance.$get('VideoChannel', {
757 transaction: options.transaction
758 }) as MChannelAccountDefault
761 return sendDeleteVideo(instance, options.transaction)
768 static async removeFiles (instance: VideoModel) {
769 const tasks: Promise<any>[] = []
771 logger.info('Removing files of video %s.', instance.url)
773 if (instance.isOwned()) {
774 if (!Array.isArray(instance.VideoFiles)) {
775 instance.VideoFiles = await instance.$get('VideoFiles')
778 // Remove physical files and torrents
779 instance.VideoFiles.forEach(file => {
780 tasks.push(instance.removeFile(file))
781 tasks.push(instance.removeTorrent(file))
784 // Remove playlists file
785 if (!Array.isArray(instance.VideoStreamingPlaylists)) {
786 instance.VideoStreamingPlaylists = await instance.$get('VideoStreamingPlaylists')
789 for (const p of instance.VideoStreamingPlaylists) {
790 tasks.push(instance.removeStreamingPlaylistFiles(p))
794 // Do not wait video deletion because we could be in a transaction
797 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
804 static stopLiveIfNeeded (instance: VideoModel) {
805 if (!instance.isLive) return
807 return LiveManager.Instance.stopSessionOf(instance.id)
811 static invalidateCache (instance: VideoModel) {
812 ModelCache.Instance.invalidateCache('video', instance.id)
816 static async saveEssentialDataToAbuses (instance: VideoModel, options) {
817 const tasks: Promise<any>[] = []
819 if (!Array.isArray(instance.VideoAbuses)) {
820 instance.VideoAbuses = await instance.$get('VideoAbuses')
822 if (instance.VideoAbuses.length === 0) return undefined
825 logger.info('Saving video abuses details of video %s.', instance.url)
827 const details = instance.toFormattedDetailsJSON()
829 for (const abuse of instance.VideoAbuses) {
830 abuse.deletedVideo = details
831 tasks.push(abuse.save({ transaction: options.transaction }))
836 logger.error('Some errors when saving details of video %s in its abuses before destroy hook.', instance.uuid, { err })
842 static listLocal (): Bluebird<MVideoWithAllFiles[]> {
849 return VideoModel.scope([
850 ScopeNames.WITH_WEBTORRENT_FILES,
851 ScopeNames.WITH_STREAMING_PLAYLISTS,
852 ScopeNames.WITH_THUMBNAILS
856 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
857 function getRawQuery (select: string) {
858 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
859 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
860 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
861 'WHERE "Account"."actorId" = ' + actorId
862 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
863 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
864 'WHERE "VideoShare"."actorId" = ' + actorId
866 return `(${queryVideo}) UNION (${queryVideoShare})`
869 const rawQuery = getRawQuery('"Video"."id"')
870 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
876 order: getVideoSort('-createdAt', [ 'Tags', 'name', 'ASC' ] as any), // FIXME: sequelize typings
879 [Op.in]: Sequelize.literal('(' + rawQuery + ')')
881 [Op.or]: getPrivaciesForFederation()
885 attributes: [ 'language', 'fileUrl' ],
886 model: VideoCaptionModel.unscoped(),
890 attributes: [ 'id', 'url' ],
891 model: VideoShareModel.unscoped(),
893 // We only want videos shared by this actor
908 attributes: [ 'id', 'url' ],
909 model: ActorModel.unscoped()
914 model: VideoChannelModel.unscoped(),
918 attributes: [ 'name' ],
919 model: AccountModel.unscoped(),
923 attributes: [ 'id', 'url', 'followersUrl' ],
924 model: ActorModel.unscoped(),
930 attributes: [ 'id', 'url', 'followersUrl' ],
931 model: ActorModel.unscoped(),
941 return Bluebird.all([
942 VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findAll(query),
943 VideoModel.sequelize.query<{ total: string }>(rawCountQuery, { type: QueryTypes.SELECT })
944 ]).then(([ rows, totals ]) => {
945 // totals: totalVideos + totalVideoShares
947 let totalVideoShares = 0
948 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
949 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
951 const total = totalVideos + totalVideoShares
959 static listUserVideosForApi (
966 function buildBaseQuery (): FindOptions {
970 order: getVideoSort(sort),
973 model: VideoChannelModel,
989 baseQuery = Object.assign(baseQuery, {
992 [Op.iLike]: '%' + search + '%'
1001 const countQuery = buildBaseQuery()
1002 const findQuery = buildBaseQuery()
1004 const findScopes: (string | ScopeOptions)[] = [
1005 ScopeNames.WITH_SCHEDULED_UPDATE,
1006 ScopeNames.WITH_BLACKLISTED,
1007 ScopeNames.WITH_THUMBNAILS
1010 return Promise.all([
1011 VideoModel.count(countQuery),
1012 VideoModel.scope(findScopes).findAll<MVideoForUser>(findQuery)
1013 ]).then(([ count, rows ]) => {
1021 static async listForApi (options: {
1026 includeLocalVideos: boolean
1028 categoryOneOf?: number[]
1029 licenceOneOf?: number[]
1030 languageOneOf?: string[]
1031 tagsOneOf?: string[]
1032 tagsAllOf?: string[]
1033 filter?: VideoFilter
1035 videoChannelId?: number
1036 followerActorId?: number
1037 videoPlaylistId?: number
1038 trendingDays?: number
1039 user?: MUserAccountId
1040 historyOfUser?: MUserId
1041 countVideos?: boolean
1043 if (options.filter && options.filter === 'all-local' && !options.user.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1044 throw new Error('Try to filter all-local but no user has not the see all videos right')
1047 const trendingDays = options.sort.endsWith('trending')
1048 ? CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1051 const serverActor = await getServerActor()
1053 // followerActorId === null has a meaning, so just check undefined
1054 const followerActorId = options.followerActorId !== undefined
1055 ? options.followerActorId
1058 const queryOptions = {
1059 start: options.start,
1060 count: options.count,
1063 serverAccountId: serverActor.Account.id,
1065 categoryOneOf: options.categoryOneOf,
1066 licenceOneOf: options.licenceOneOf,
1067 languageOneOf: options.languageOneOf,
1068 tagsOneOf: options.tagsOneOf,
1069 tagsAllOf: options.tagsAllOf,
1070 filter: options.filter,
1071 withFiles: options.withFiles,
1072 accountId: options.accountId,
1073 videoChannelId: options.videoChannelId,
1074 videoPlaylistId: options.videoPlaylistId,
1075 includeLocalVideos: options.includeLocalVideos,
1077 historyOfUser: options.historyOfUser,
1081 return VideoModel.getAvailableForApi(queryOptions, options.countVideos)
1084 static async searchAndPopulateAccountAndServer (options: {
1085 includeLocalVideos: boolean
1090 startDate?: string // ISO 8601
1091 endDate?: string // ISO 8601
1092 originallyPublishedStartDate?: string
1093 originallyPublishedEndDate?: string
1095 categoryOneOf?: number[]
1096 licenceOneOf?: number[]
1097 languageOneOf?: string[]
1098 tagsOneOf?: string[]
1099 tagsAllOf?: string[]
1100 durationMin?: number // seconds
1101 durationMax?: number // seconds
1102 user?: MUserAccountId
1103 filter?: VideoFilter
1105 const serverActor = await getServerActor()
1106 const queryOptions = {
1107 followerActorId: serverActor.id,
1108 serverAccountId: serverActor.Account.id,
1109 includeLocalVideos: options.includeLocalVideos,
1111 categoryOneOf: options.categoryOneOf,
1112 licenceOneOf: options.licenceOneOf,
1113 languageOneOf: options.languageOneOf,
1114 tagsOneOf: options.tagsOneOf,
1115 tagsAllOf: options.tagsAllOf,
1117 filter: options.filter,
1118 start: options.start,
1119 count: options.count,
1121 startDate: options.startDate,
1122 endDate: options.endDate,
1123 originallyPublishedStartDate: options.originallyPublishedStartDate,
1124 originallyPublishedEndDate: options.originallyPublishedEndDate,
1126 durationMin: options.durationMin,
1127 durationMax: options.durationMax,
1129 search: options.search
1132 return VideoModel.getAvailableForApi(queryOptions)
1135 static load (id: number | string, t?: Transaction): Bluebird<MVideoThumbnail> {
1136 const where = buildWhereIdOrUUID(id)
1142 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1145 static loadWithBlacklist (id: number | string, t?: Transaction): Bluebird<MVideoThumbnailBlacklist> {
1146 const where = buildWhereIdOrUUID(id)
1152 return VideoModel.scope([
1153 ScopeNames.WITH_THUMBNAILS,
1154 ScopeNames.WITH_BLACKLISTED
1158 static loadImmutableAttributes (id: number | string, t?: Transaction): Bluebird<MVideoImmutable> {
1161 where: buildWhereIdOrUUID(id),
1165 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1168 return ModelCache.Instance.doCache({
1169 cacheType: 'load-video-immutable-id',
1176 static loadWithRights (id: number | string, t?: Transaction): Bluebird<MVideoWithRights> {
1177 const where = buildWhereIdOrUUID(id)
1183 return VideoModel.scope([
1184 ScopeNames.WITH_BLACKLISTED,
1185 ScopeNames.WITH_USER_ID,
1186 ScopeNames.WITH_THUMBNAILS
1190 static loadOnlyId (id: number | string, t?: Transaction): Bluebird<MVideoIdThumbnail> {
1191 const where = buildWhereIdOrUUID(id)
1194 attributes: [ 'id' ],
1199 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1202 static loadWithFiles (id: number | string, t?: Transaction, logging?: boolean): Bluebird<MVideoWithAllFiles> {
1203 const where = buildWhereIdOrUUID(id)
1211 return VideoModel.scope([
1212 ScopeNames.WITH_WEBTORRENT_FILES,
1213 ScopeNames.WITH_STREAMING_PLAYLISTS,
1214 ScopeNames.WITH_THUMBNAILS
1218 static loadByUUID (uuid: string): Bluebird<MVideoThumbnail> {
1225 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1228 static loadByUrl (url: string, transaction?: Transaction): Bluebird<MVideoThumbnail> {
1229 const query: FindOptions = {
1236 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(query)
1239 static loadByUrlImmutableAttributes (url: string, transaction?: Transaction): Bluebird<MVideoImmutable> {
1241 const query: FindOptions = {
1248 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1251 return ModelCache.Instance.doCache({
1252 cacheType: 'load-video-immutable-url',
1259 static loadByUrlAndPopulateAccount (url: string, transaction?: Transaction): Bluebird<MVideoAccountLightBlacklistAllFiles> {
1260 const query: FindOptions = {
1267 return VideoModel.scope([
1268 ScopeNames.WITH_ACCOUNT_DETAILS,
1269 ScopeNames.WITH_WEBTORRENT_FILES,
1270 ScopeNames.WITH_STREAMING_PLAYLISTS,
1271 ScopeNames.WITH_THUMBNAILS,
1272 ScopeNames.WITH_BLACKLISTED
1276 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Transaction, userId?: number): Bluebird<MVideoFullLight> {
1277 const where = buildWhereIdOrUUID(id)
1280 order: [ [ 'Tags', 'name', 'ASC' ] ] as any,
1285 const scopes: (string | ScopeOptions)[] = [
1286 ScopeNames.WITH_TAGS,
1287 ScopeNames.WITH_BLACKLISTED,
1288 ScopeNames.WITH_ACCOUNT_DETAILS,
1289 ScopeNames.WITH_SCHEDULED_UPDATE,
1290 ScopeNames.WITH_WEBTORRENT_FILES,
1291 ScopeNames.WITH_STREAMING_PLAYLISTS,
1292 ScopeNames.WITH_THUMBNAILS
1296 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1304 static loadForGetAPI (parameters: {
1308 }): Bluebird<MVideoDetails> {
1309 const { id, t, userId } = parameters
1310 const where = buildWhereIdOrUUID(id)
1313 order: [ [ 'Tags', 'name', 'ASC' ] ] as any, // FIXME: sequelize typings
1318 const scopes: (string | ScopeOptions)[] = [
1319 ScopeNames.WITH_TAGS,
1320 ScopeNames.WITH_BLACKLISTED,
1321 ScopeNames.WITH_ACCOUNT_DETAILS,
1322 ScopeNames.WITH_SCHEDULED_UPDATE,
1323 ScopeNames.WITH_THUMBNAILS,
1324 { method: [ ScopeNames.WITH_WEBTORRENT_FILES, true ] },
1325 { method: [ ScopeNames.WITH_STREAMING_PLAYLISTS, true ] }
1329 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1337 static async getStats () {
1338 const totalLocalVideos = await VideoModel.count({
1344 let totalLocalVideoViews = await VideoModel.sum('views', {
1350 // Sequelize could return null...
1351 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1353 const { total: totalVideos } = await VideoModel.listForApi({
1356 sort: '-publishedAt',
1357 nsfw: buildNSFWFilter(),
1358 includeLocalVideos: true,
1364 totalLocalVideoViews,
1369 static incrementViews (id: number, views: number) {
1370 return VideoModel.increment('views', {
1378 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1379 // Instances only share videos
1380 const query = 'SELECT 1 FROM "videoShare" ' +
1381 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1382 'WHERE "actorFollow"."actorId" = $followerActorId AND "actorFollow"."state" = \'accepted\' AND "videoShare"."videoId" = $videoId ' +
1386 type: QueryTypes.SELECT as QueryTypes.SELECT,
1387 bind: { followerActorId, videoId },
1391 return VideoModel.sequelize.query(query, options)
1392 .then(results => results.length === 1)
1395 static bulkUpdateSupportField (videoChannel: MChannel, t: Transaction) {
1398 channelId: videoChannel.id
1403 return VideoModel.update({ support: videoChannel.support }, options)
1406 static getAllIdsFromChannel (videoChannel: MChannelId): Bluebird<number[]> {
1408 attributes: [ 'id' ],
1410 channelId: videoChannel.id
1414 return VideoModel.findAll(query)
1415 .then(videos => videos.map(v => v.id))
1418 // threshold corresponds to how many video the field should have to be returned
1419 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1420 const serverActor = await getServerActor()
1421 const followerActorId = serverActor.id
1423 const queryOptions: BuildVideosQueryOptions = {
1424 attributes: [ `"${field}"` ],
1425 group: `GROUP BY "${field}"`,
1426 having: `HAVING COUNT("${field}") >= ${threshold}`,
1430 serverAccountId: serverActor.Account.id,
1432 includeLocalVideos: true
1435 const { query, replacements } = buildListQuery(VideoModel, queryOptions)
1437 return this.sequelize.query<any>(query, { replacements, type: QueryTypes.SELECT })
1438 .then(rows => rows.map(r => r[field]))
1441 static buildTrendingQuery (trendingDays: number) {
1445 model: VideoViewModel,
1449 [Op.gte]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1455 private static async getAvailableForApi (
1456 options: BuildVideosQueryOptions,
1458 ): Promise<ResultList<VideoModel>> {
1459 function getCount () {
1460 if (countVideos !== true) return Promise.resolve(undefined)
1462 const countOptions = Object.assign({}, options, { isCount: true })
1463 const { query: queryCount, replacements: replacementsCount } = buildListQuery(VideoModel, countOptions)
1465 return VideoModel.sequelize.query<any>(queryCount, { replacements: replacementsCount, type: QueryTypes.SELECT })
1466 .then(rows => rows.length !== 0 ? rows[0].total : 0)
1469 function getModels () {
1470 if (options.count === 0) return Promise.resolve([])
1472 const { query, replacements, order } = buildListQuery(VideoModel, options)
1473 const queryModels = wrapForAPIResults(query, replacements, options, order)
1475 return VideoModel.sequelize.query<any>(queryModels, { replacements, type: QueryTypes.SELECT, nest: true })
1476 .then(rows => VideoModel.buildAPIResult(rows))
1479 const [ count, rows ] = await Promise.all([ getCount(), getModels() ])
1487 private static buildAPIResult (rows: any[]) {
1488 const videosMemo: { [ id: number ]: VideoModel } = {}
1489 const videoStreamingPlaylistMemo: { [ id: number ]: VideoStreamingPlaylistModel } = {}
1491 const thumbnailsDone = new Set<number>()
1492 const historyDone = new Set<number>()
1493 const videoFilesDone = new Set<number>()
1495 const videos: VideoModel[] = []
1497 const avatarKeys = [ 'id', 'filename', 'fileUrl', 'onDisk', 'createdAt', 'updatedAt' ]
1498 const actorKeys = [ 'id', 'preferredUsername', 'url', 'serverId', 'avatarId' ]
1499 const serverKeys = [ 'id', 'host' ]
1500 const videoFileKeys = [ 'id', 'createdAt', 'updatedAt', 'resolution', 'size', 'extname', 'infoHash', 'fps', 'videoId' ]
1501 const videoStreamingPlaylistKeys = [ 'id' ]
1524 'originallyPublishedAt',
1530 function buildActor (rowActor: any) {
1531 const avatarModel = rowActor.Avatar.id !== null
1532 ? new AvatarModel(pick(rowActor.Avatar, avatarKeys))
1535 const serverModel = rowActor.Server.id !== null
1536 ? new ServerModel(pick(rowActor.Server, serverKeys))
1539 const actorModel = new ActorModel(pick(rowActor, actorKeys))
1540 actorModel.Avatar = avatarModel
1541 actorModel.Server = serverModel
1546 for (const row of rows) {
1547 if (!videosMemo[row.id]) {
1549 const channel = row.VideoChannel
1550 const channelModel = new VideoChannelModel(pick(channel, [ 'id', 'name', 'description', 'actorId' ]))
1551 channelModel.Actor = buildActor(channel.Actor)
1553 const account = row.VideoChannel.Account
1554 const accountModel = new AccountModel(pick(account, [ 'id', 'name' ]))
1555 accountModel.Actor = buildActor(account.Actor)
1557 channelModel.Account = accountModel
1559 const videoModel = new VideoModel(pick(row, videoKeys))
1560 videoModel.VideoChannel = channelModel
1562 videoModel.UserVideoHistories = []
1563 videoModel.Thumbnails = []
1564 videoModel.VideoFiles = []
1565 videoModel.VideoStreamingPlaylists = []
1567 videosMemo[row.id] = videoModel
1568 // Don't take object value to have a sorted array
1569 videos.push(videoModel)
1572 const videoModel = videosMemo[row.id]
1574 if (row.userVideoHistory?.id && !historyDone.has(row.userVideoHistory.id)) {
1575 const historyModel = new UserVideoHistoryModel(pick(row.userVideoHistory, [ 'id', 'currentTime' ]))
1576 videoModel.UserVideoHistories.push(historyModel)
1578 historyDone.add(row.userVideoHistory.id)
1581 if (row.Thumbnails?.id && !thumbnailsDone.has(row.Thumbnails.id)) {
1582 const thumbnailModel = new ThumbnailModel(pick(row.Thumbnails, [ 'id', 'type', 'filename' ]))
1583 videoModel.Thumbnails.push(thumbnailModel)
1585 thumbnailsDone.add(row.Thumbnails.id)
1588 if (row.VideoFiles?.id && !videoFilesDone.has(row.VideoFiles.id)) {
1589 const videoFileModel = new VideoFileModel(pick(row.VideoFiles, videoFileKeys))
1590 videoModel.VideoFiles.push(videoFileModel)
1592 videoFilesDone.add(row.VideoFiles.id)
1595 if (row.VideoFiles?.id && !videoFilesDone.has(row.VideoFiles.id)) {
1596 const videoFileModel = new VideoFileModel(pick(row.VideoFiles, videoFileKeys))
1597 videoModel.VideoFiles.push(videoFileModel)
1599 videoFilesDone.add(row.VideoFiles.id)
1602 if (row.VideoStreamingPlaylists?.id && !videoStreamingPlaylistMemo[row.VideoStreamingPlaylists.id]) {
1603 const streamingPlaylist = new VideoStreamingPlaylistModel(pick(row.VideoStreamingPlaylists, videoStreamingPlaylistKeys))
1604 streamingPlaylist.VideoFiles = []
1606 videoModel.VideoStreamingPlaylists.push(streamingPlaylist)
1608 videoStreamingPlaylistMemo[streamingPlaylist.id] = streamingPlaylist
1611 if (row.VideoStreamingPlaylists?.VideoFiles?.id && !videoFilesDone.has(row.VideoStreamingPlaylists.VideoFiles.id)) {
1612 const streamingPlaylist = videoStreamingPlaylistMemo[row.VideoStreamingPlaylists.id]
1614 const videoFileModel = new VideoFileModel(pick(row.VideoStreamingPlaylists.VideoFiles, videoFileKeys))
1615 streamingPlaylist.VideoFiles.push(videoFileModel)
1617 videoFilesDone.add(row.VideoStreamingPlaylists.VideoFiles.id)
1624 static getCategoryLabel (id: number) {
1625 return VIDEO_CATEGORIES[id] || 'Misc'
1628 static getLicenceLabel (id: number) {
1629 return VIDEO_LICENCES[id] || 'Unknown'
1632 static getLanguageLabel (id: string) {
1633 return VIDEO_LANGUAGES[id] || 'Unknown'
1636 static getPrivacyLabel (id: number) {
1637 return VIDEO_PRIVACIES[id] || 'Unknown'
1640 static getStateLabel (id: number) {
1641 return VIDEO_STATES[id] || 'Unknown'
1645 return !!this.VideoBlacklist
1649 return this.VideoChannel.Account.Actor.Server?.isBlocked() || this.VideoChannel.Account.isBlocked()
1652 getQualityFileBy<T extends MVideoWithFile> (this: T, fun: (files: MVideoFile[], it: (file: MVideoFile) => number) => MVideoFile) {
1653 if (Array.isArray(this.VideoFiles) && this.VideoFiles.length !== 0) {
1654 const file = fun(this.VideoFiles, file => file.resolution)
1656 return Object.assign(file, { Video: this })
1659 // No webtorrent files, try with streaming playlist files
1660 if (Array.isArray(this.VideoStreamingPlaylists) && this.VideoStreamingPlaylists.length !== 0) {
1661 const streamingPlaylistWithVideo = Object.assign(this.VideoStreamingPlaylists[0], { Video: this })
1663 const file = fun(streamingPlaylistWithVideo.VideoFiles, file => file.resolution)
1664 return Object.assign(file, { VideoStreamingPlaylist: streamingPlaylistWithVideo })
1670 getMaxQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1671 return this.getQualityFileBy(maxBy)
1674 getMinQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1675 return this.getQualityFileBy(minBy)
1678 getWebTorrentFile<T extends MVideoWithFile> (this: T, resolution: number): MVideoFileVideo {
1679 if (Array.isArray(this.VideoFiles) === false) return undefined
1681 const file = this.VideoFiles.find(f => f.resolution === resolution)
1682 if (!file) return undefined
1684 return Object.assign(file, { Video: this })
1687 async addAndSaveThumbnail (thumbnail: MThumbnail, transaction: Transaction) {
1688 thumbnail.videoId = this.id
1690 const savedThumbnail = await thumbnail.save({ transaction })
1692 if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = []
1694 // Already have this thumbnail, skip
1695 if (this.Thumbnails.find(t => t.id === savedThumbnail.id)) return
1697 this.Thumbnails.push(savedThumbnail)
1700 generateThumbnailName () {
1701 return this.uuid + '.jpg'
1705 if (Array.isArray(this.Thumbnails) === false) return undefined
1707 return this.Thumbnails.find(t => t.type === ThumbnailType.MINIATURE)
1710 generatePreviewName () {
1711 return this.uuid + '.jpg'
1715 return !!this.getPreview()
1719 if (Array.isArray(this.Thumbnails) === false) return undefined
1721 return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW)
1725 return this.remote === false
1728 getWatchStaticPath () {
1729 return '/videos/watch/' + this.uuid
1732 getEmbedStaticPath () {
1733 return '/videos/embed/' + this.uuid
1736 getMiniatureStaticPath () {
1737 const thumbnail = this.getMiniature()
1738 if (!thumbnail) return null
1740 return join(STATIC_PATHS.THUMBNAILS, thumbnail.filename)
1743 getPreviewStaticPath () {
1744 const preview = this.getPreview()
1745 if (!preview) return null
1747 // We use a local cache, so specify our cache endpoint instead of potential remote URL
1748 return join(LAZY_STATIC_PATHS.PREVIEWS, preview.filename)
1751 toFormattedJSON (this: MVideoFormattable, options?: VideoFormattingJSONOptions): Video {
1752 return videoModelToFormattedJSON(this, options)
1755 toFormattedDetailsJSON (this: MVideoFormattableDetails): VideoDetails {
1756 return videoModelToFormattedDetailsJSON(this)
1759 getFormattedVideoFilesJSON (): VideoFile[] {
1760 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1761 let files: MVideoFileRedundanciesOpt[] = []
1763 if (Array.isArray(this.VideoFiles)) {
1764 files = files.concat(this.VideoFiles)
1767 for (const p of (this.VideoStreamingPlaylists || [])) {
1768 files = files.concat(p.VideoFiles || [])
1771 return videoFilesModelToFormattedJSON(this, baseUrlHttp, baseUrlWs, files)
1774 toActivityPubObject (this: MVideoAP): VideoObject {
1775 return videoModelToActivityPubObject(this)
1778 getTruncatedDescription () {
1779 if (!this.description) return null
1781 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1782 return peertubeTruncate(this.description, { length: maxLength })
1785 getMaxQualityResolution () {
1786 const file = this.getMaxQualityFile()
1787 const videoOrPlaylist = file.getVideoOrStreamingPlaylist()
1788 const originalFilePath = getVideoFilePath(videoOrPlaylist, file)
1790 return getVideoFileResolution(originalFilePath)
1793 getDescriptionAPIPath () {
1794 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1797 getHLSPlaylist (): MStreamingPlaylistFilesVideo {
1798 if (!this.VideoStreamingPlaylists) return undefined
1800 const playlist = this.VideoStreamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
1801 playlist.Video = this
1806 setHLSPlaylist (playlist: MStreamingPlaylist) {
1807 const toAdd = [ playlist ] as [ VideoStreamingPlaylistModel ]
1809 if (Array.isArray(this.VideoStreamingPlaylists) === false || this.VideoStreamingPlaylists.length === 0) {
1810 this.VideoStreamingPlaylists = toAdd
1814 this.VideoStreamingPlaylists = this.VideoStreamingPlaylists
1815 .filter(s => s.type !== VideoStreamingPlaylistType.HLS)
1819 removeFile (videoFile: MVideoFile, isRedundancy = false) {
1820 const filePath = getVideoFilePath(this, videoFile, isRedundancy)
1821 return remove(filePath)
1822 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1825 removeTorrent (videoFile: MVideoFile) {
1826 const torrentPath = getTorrentFilePath(this, videoFile)
1827 return remove(torrentPath)
1828 .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err }))
1831 async removeStreamingPlaylistFiles (streamingPlaylist: MStreamingPlaylist, isRedundancy = false) {
1832 const directoryPath = getHLSDirectory(this, isRedundancy)
1834 await remove(directoryPath)
1836 if (isRedundancy !== true) {
1837 const streamingPlaylistWithFiles = streamingPlaylist as MStreamingPlaylistFilesVideo
1838 streamingPlaylistWithFiles.Video = this
1840 if (!Array.isArray(streamingPlaylistWithFiles.VideoFiles)) {
1841 streamingPlaylistWithFiles.VideoFiles = await streamingPlaylistWithFiles.$get('VideoFiles')
1844 // Remove physical files and torrents
1846 streamingPlaylistWithFiles.VideoFiles.map(file => streamingPlaylistWithFiles.removeTorrent(file))
1852 if (this.isOwned()) return false
1854 return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)
1857 hasPrivacyForFederation () {
1858 return isPrivacyForFederation(this.privacy)
1861 isNewVideo (newPrivacy: VideoPrivacy) {
1862 return this.hasPrivacyForFederation() === false && isPrivacyForFederation(newPrivacy) === true
1866 this.changed('updatedAt', true)
1872 return this.privacy === VideoPrivacy.PRIVATE || this.privacy === VideoPrivacy.INTERNAL || !!this.VideoBlacklist
1875 setPrivacy (newPrivacy: VideoPrivacy) {
1876 if (this.privacy === VideoPrivacy.PRIVATE && newPrivacy !== VideoPrivacy.PRIVATE) {
1877 this.publishedAt = new Date()
1880 this.privacy = newPrivacy
1884 return this.privacy === VideoPrivacy.PRIVATE ||
1885 this.privacy === VideoPrivacy.UNLISTED ||
1886 this.privacy === VideoPrivacy.INTERNAL
1889 async publishIfNeededAndSave (t: Transaction) {
1890 if (this.state !== VideoState.PUBLISHED) {
1891 this.state = VideoState.PUBLISHED
1892 this.publishedAt = new Date()
1893 await this.save({ transaction: t })
1902 if (this.isOwned()) {
1904 baseUrlHttp: WEBSERVER.URL,
1905 baseUrlWs: WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT
1910 baseUrlHttp: REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host,
1911 baseUrlWs: REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1915 getTrackerUrls (baseUrlHttp: string, baseUrlWs: string) {
1916 return [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1919 getTorrentUrl (videoFile: MVideoFile, baseUrlHttp: string) {
1920 return baseUrlHttp + STATIC_PATHS.TORRENTS + getTorrentFileName(this, videoFile)
1923 getTorrentDownloadUrl (videoFile: MVideoFile, baseUrlHttp: string) {
1924 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + getTorrentFileName(this, videoFile)
1927 getVideoFileUrl (videoFile: MVideoFile, baseUrlHttp: string) {
1928 return baseUrlHttp + STATIC_PATHS.WEBSEED + getVideoFilename(this, videoFile)
1931 getVideoFileMetadataUrl (videoFile: MVideoFile, baseUrlHttp: string) {
1932 const path = '/api/v1/videos/'
1934 return this.isOwned()
1935 ? baseUrlHttp + path + this.uuid + '/metadata/' + videoFile.id
1936 : videoFile.metadataUrl
1939 getVideoRedundancyUrl (videoFile: MVideoFile, baseUrlHttp: string) {
1940 return baseUrlHttp + STATIC_PATHS.REDUNDANCY + getVideoFilename(this, videoFile)
1943 getVideoFileDownloadUrl (videoFile: MVideoFile, baseUrlHttp: string) {
1944 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + getVideoFilename(this, videoFile)
1947 getBandwidthBits (videoFile: MVideoFile) {
1948 return Math.ceil((videoFile.size * 8) / this.duration)