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, Includeable, 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/ffprobe-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'
132 import { UserModel } from '../account/user'
134 export enum ScopeNames {
135 AVAILABLE_FOR_LIST_IDS = 'AVAILABLE_FOR_LIST_IDS',
137 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
138 WITH_TAGS = 'WITH_TAGS',
139 WITH_WEBTORRENT_FILES = 'WITH_WEBTORRENT_FILES',
140 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
141 WITH_BLACKLISTED = 'WITH_BLACKLISTED',
142 WITH_USER_HISTORY = 'WITH_USER_HISTORY',
143 WITH_STREAMING_PLAYLISTS = 'WITH_STREAMING_PLAYLISTS',
144 WITH_USER_ID = 'WITH_USER_ID',
145 WITH_IMMUTABLE_ATTRIBUTES = 'WITH_IMMUTABLE_ATTRIBUTES',
146 WITH_THUMBNAILS = 'WITH_THUMBNAILS',
147 WITH_LIVE = 'WITH_LIVE'
150 export type ForAPIOptions = {
153 videoPlaylistId?: number
157 withAccountBlockerIds?: number[]
160 export type AvailableForListIDsOptions = {
161 serverAccountId: number
162 followerActorId: number
163 includeLocalVideos: boolean
165 attributesType?: 'none' | 'id' | 'all'
168 categoryOneOf?: number[]
170 licenceOneOf?: number[]
171 languageOneOf?: string[]
178 videoChannelId?: number
180 videoPlaylistId?: number
182 trendingDays?: number
183 user?: MUserAccountId
184 historyOfUser?: MUserId
186 baseWhere?: WhereOptions[]
190 [ScopeNames.WITH_IMMUTABLE_ATTRIBUTES]: {
191 attributes: [ 'id', 'url', 'uuid', 'remote' ]
193 [ScopeNames.FOR_API]: (options: ForAPIOptions) => {
194 const include: Includeable[] = [
196 model: VideoChannelModel.scope({
198 VideoChannelScopeNames.SUMMARY, {
200 withAccountBlockerIds: options.withAccountBlockerIds
207 attributes: [ 'type', 'filename' ],
208 model: ThumbnailModel,
213 const query: FindOptions = {}
223 if (options.withFiles === true) {
225 model: VideoFileModel,
230 if (options.videoPlaylistId) {
232 model: VideoPlaylistElementModel.unscoped(),
235 videoPlaylistId: options.videoPlaylistId
240 query.include = include
244 [ScopeNames.WITH_THUMBNAILS]: {
247 model: ThumbnailModel,
252 [ScopeNames.WITH_LIVE]: {
255 model: VideoLiveModel.unscoped(),
260 [ScopeNames.WITH_USER_ID]: {
263 attributes: [ 'accountId' ],
264 model: VideoChannelModel.unscoped(),
268 attributes: [ 'userId' ],
269 model: AccountModel.unscoped(),
276 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
279 model: VideoChannelModel.unscoped(),
284 exclude: [ 'privateKey', 'publicKey' ]
286 model: ActorModel.unscoped(),
290 attributes: [ 'host' ],
291 model: ServerModel.unscoped(),
295 model: AvatarModel.unscoped(),
301 model: AccountModel.unscoped(),
305 model: ActorModel.unscoped(),
307 exclude: [ 'privateKey', 'publicKey' ]
312 attributes: [ 'host' ],
313 model: ServerModel.unscoped(),
317 model: AvatarModel.unscoped(),
328 [ScopeNames.WITH_TAGS]: {
329 include: [ TagModel ]
331 [ScopeNames.WITH_BLACKLISTED]: {
334 attributes: [ 'id', 'reason', 'unfederated' ],
335 model: VideoBlacklistModel,
340 [ScopeNames.WITH_WEBTORRENT_FILES]: (withRedundancies = false) => {
341 let subInclude: any[] = []
343 if (withRedundancies === true) {
346 attributes: [ 'fileUrl' ],
347 model: VideoRedundancyModel.unscoped(),
356 model: VideoFileModel,
357 separate: true, // We may have multiple files, having multiple redundancies so let's separate this join
364 [ScopeNames.WITH_STREAMING_PLAYLISTS]: (withRedundancies = false) => {
365 const subInclude: IncludeOptions[] = [
367 model: VideoFileModel,
372 if (withRedundancies === true) {
374 attributes: [ 'fileUrl' ],
375 model: VideoRedundancyModel.unscoped(),
383 model: VideoStreamingPlaylistModel.unscoped(),
384 separate: true, // We may have multiple streaming playlists, having multiple redundancies so let's separate this join
391 [ScopeNames.WITH_SCHEDULED_UPDATE]: {
394 model: ScheduleVideoUpdateModel.unscoped(),
399 [ScopeNames.WITH_USER_HISTORY]: (userId: number) => {
403 attributes: [ 'currentTime' ],
404 model: UserVideoHistoryModel.unscoped(),
417 buildTrigramSearchIndex('video_name_trigram', 'name'),
419 { fields: [ 'createdAt' ] },
422 { name: 'publishedAt', order: 'DESC' },
423 { name: 'id', order: 'ASC' }
426 { fields: [ 'duration' ] },
427 { fields: [ 'views' ] },
428 { fields: [ 'channelId' ] },
430 fields: [ 'originallyPublishedAt' ],
432 originallyPublishedAt: {
438 fields: [ 'category' ], // We don't care videos with an unknown category
446 fields: [ 'licence' ], // We don't care videos with an unknown licence
454 fields: [ 'language' ], // We don't care videos with an unknown language
462 fields: [ 'nsfw' ], // Most of the videos are not NSFW
468 fields: [ 'remote' ], // Only index local videos
483 export class VideoModel extends Model {
486 @Default(DataType.UUIDV4)
488 @Column(DataType.UUID)
492 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
498 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category', true))
504 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence', true))
510 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language', true))
511 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
515 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
517 privacy: VideoPrivacy
520 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
526 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description', true))
527 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
532 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support', true))
533 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
537 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
572 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
573 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
578 commentsEnabled: boolean
582 downloadEnabled: boolean
586 waitTranscoding: boolean
590 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
601 @Default(DataType.NOW)
608 originallyPublishedAt: Date
610 @ForeignKey(() => VideoChannelModel)
614 @BelongsTo(() => VideoChannelModel, {
620 VideoChannel: VideoChannelModel
622 @BelongsToMany(() => TagModel, {
623 foreignKey: 'videoId',
624 through: () => VideoTagModel,
629 @HasMany(() => ThumbnailModel, {
637 Thumbnails: ThumbnailModel[]
639 @HasMany(() => VideoPlaylistElementModel, {
646 VideoPlaylistElements: VideoPlaylistElementModel[]
648 @HasMany(() => VideoAbuseModel, {
655 VideoAbuses: VideoAbuseModel[]
657 @HasMany(() => VideoFileModel, {
665 VideoFiles: VideoFileModel[]
667 @HasMany(() => VideoStreamingPlaylistModel, {
675 VideoStreamingPlaylists: VideoStreamingPlaylistModel[]
677 @HasMany(() => VideoShareModel, {
684 VideoShares: VideoShareModel[]
686 @HasMany(() => AccountVideoRateModel, {
693 AccountVideoRates: AccountVideoRateModel[]
695 @HasMany(() => VideoCommentModel, {
703 VideoComments: VideoCommentModel[]
705 @HasMany(() => VideoViewModel, {
712 VideoViews: VideoViewModel[]
714 @HasMany(() => UserVideoHistoryModel, {
721 UserVideoHistories: UserVideoHistoryModel[]
723 @HasOne(() => ScheduleVideoUpdateModel, {
730 ScheduleVideoUpdate: ScheduleVideoUpdateModel
732 @HasOne(() => VideoBlacklistModel, {
739 VideoBlacklist: VideoBlacklistModel
741 @HasOne(() => VideoLiveModel, {
748 VideoLive: VideoLiveModel
750 @HasOne(() => VideoImportModel, {
757 VideoImport: VideoImportModel
759 @HasMany(() => VideoCaptionModel, {
766 ['separate' as any]: true
768 VideoCaptions: VideoCaptionModel[]
771 static async sendDelete (instance: MVideoAccountLight, options) {
772 if (instance.isOwned()) {
773 if (!instance.VideoChannel) {
774 instance.VideoChannel = await instance.$get('VideoChannel', {
779 transaction: options.transaction
780 }) as MChannelAccountDefault
783 return sendDeleteVideo(instance, options.transaction)
790 static async removeFiles (instance: VideoModel) {
791 const tasks: Promise<any>[] = []
793 logger.info('Removing files of video %s.', instance.url)
795 if (instance.isOwned()) {
796 if (!Array.isArray(instance.VideoFiles)) {
797 instance.VideoFiles = await instance.$get('VideoFiles')
800 // Remove physical files and torrents
801 instance.VideoFiles.forEach(file => {
802 tasks.push(instance.removeFile(file))
803 tasks.push(instance.removeTorrent(file))
806 // Remove playlists file
807 if (!Array.isArray(instance.VideoStreamingPlaylists)) {
808 instance.VideoStreamingPlaylists = await instance.$get('VideoStreamingPlaylists')
811 for (const p of instance.VideoStreamingPlaylists) {
812 tasks.push(instance.removeStreamingPlaylistFiles(p))
816 // Do not wait video deletion because we could be in a transaction
819 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
826 static stopLiveIfNeeded (instance: VideoModel) {
827 if (!instance.isLive) return
829 logger.info('Stopping live of video %s after video deletion.', instance.uuid)
831 return LiveManager.Instance.stopSessionOf(instance.id)
835 static invalidateCache (instance: VideoModel) {
836 ModelCache.Instance.invalidateCache('video', instance.id)
840 static async saveEssentialDataToAbuses (instance: VideoModel, options) {
841 const tasks: Promise<any>[] = []
843 if (!Array.isArray(instance.VideoAbuses)) {
844 instance.VideoAbuses = await instance.$get('VideoAbuses')
846 if (instance.VideoAbuses.length === 0) return undefined
849 logger.info('Saving video abuses details of video %s.', instance.url)
851 const details = instance.toFormattedDetailsJSON()
853 for (const abuse of instance.VideoAbuses) {
854 abuse.deletedVideo = details
855 tasks.push(abuse.save({ transaction: options.transaction }))
860 logger.error('Some errors when saving details of video %s in its abuses before destroy hook.', instance.uuid, { err })
866 static listLocal (): Promise<MVideoWithAllFiles[]> {
873 return VideoModel.scope([
874 ScopeNames.WITH_WEBTORRENT_FILES,
875 ScopeNames.WITH_STREAMING_PLAYLISTS,
876 ScopeNames.WITH_THUMBNAILS
880 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
881 function getRawQuery (select: string) {
882 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
883 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
884 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
885 'WHERE "Account"."actorId" = ' + actorId
886 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
887 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
888 'WHERE "VideoShare"."actorId" = ' + actorId
890 return `(${queryVideo}) UNION (${queryVideoShare})`
893 const rawQuery = getRawQuery('"Video"."id"')
894 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
900 order: getVideoSort('-createdAt', [ 'Tags', 'name', 'ASC' ] as any), // FIXME: sequelize typings
903 [Op.in]: Sequelize.literal('(' + rawQuery + ')')
905 [Op.or]: getPrivaciesForFederation()
909 attributes: [ 'language', 'fileUrl' ],
910 model: VideoCaptionModel.unscoped(),
914 attributes: [ 'id', 'url' ],
915 model: VideoShareModel.unscoped(),
917 // We only want videos shared by this actor
932 attributes: [ 'id', 'url' ],
933 model: ActorModel.unscoped()
938 model: VideoChannelModel.unscoped(),
942 attributes: [ 'name' ],
943 model: AccountModel.unscoped(),
947 attributes: [ 'id', 'url', 'followersUrl' ],
948 model: ActorModel.unscoped(),
954 attributes: [ 'id', 'url', 'followersUrl' ],
955 model: ActorModel.unscoped(),
961 model: VideoStreamingPlaylistModel.unscoped(),
965 model: VideoFileModel,
970 VideoLiveModel.unscoped(),
976 return Bluebird.all([
977 VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findAll(query),
978 VideoModel.sequelize.query<{ total: string }>(rawCountQuery, { type: QueryTypes.SELECT })
979 ]).then(([ rows, totals ]) => {
980 // totals: totalVideos + totalVideoShares
982 let totalVideoShares = 0
983 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
984 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
986 const total = totalVideos + totalVideoShares
994 static async listPublishedLiveIds () {
996 attributes: [ 'id' ],
999 state: VideoState.PUBLISHED
1003 const result = await VideoModel.findAll(options)
1005 return result.map(v => v.id)
1008 static listUserVideosForApi (options: {
1015 const { accountId, start, count, sort, search } = options
1017 function buildBaseQuery (): FindOptions {
1021 order: getVideoSort(sort),
1024 model: VideoChannelModel,
1028 model: AccountModel,
1040 baseQuery = Object.assign(baseQuery, {
1043 [Op.iLike]: '%' + search + '%'
1052 const countQuery = buildBaseQuery()
1053 const findQuery = buildBaseQuery()
1055 const findScopes: (string | ScopeOptions)[] = [
1056 ScopeNames.WITH_SCHEDULED_UPDATE,
1057 ScopeNames.WITH_BLACKLISTED,
1058 ScopeNames.WITH_THUMBNAILS
1061 return Promise.all([
1062 VideoModel.count(countQuery),
1063 VideoModel.scope(findScopes).findAll<MVideoForUser>(findQuery)
1064 ]).then(([ count, rows ]) => {
1072 static async listForApi (options: {
1077 includeLocalVideos: boolean
1079 categoryOneOf?: number[]
1080 licenceOneOf?: number[]
1081 languageOneOf?: string[]
1082 tagsOneOf?: string[]
1083 tagsAllOf?: string[]
1084 filter?: VideoFilter
1086 videoChannelId?: number
1087 followerActorId?: number
1088 videoPlaylistId?: number
1089 trendingDays?: number
1090 user?: MUserAccountId
1091 historyOfUser?: MUserId
1092 countVideos?: boolean
1095 if ((options.filter === 'all-local' || options.filter === 'all') && !options.user.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1096 throw new Error('Try to filter all-local but no user has not the see all videos right')
1099 const trendingDays = options.sort.endsWith('trending')
1100 ? CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1103 const serverActor = await getServerActor()
1105 // followerActorId === null has a meaning, so just check undefined
1106 const followerActorId = options.followerActorId !== undefined
1107 ? options.followerActorId
1110 const queryOptions = {
1111 start: options.start,
1112 count: options.count,
1115 serverAccountId: serverActor.Account.id,
1117 categoryOneOf: options.categoryOneOf,
1118 licenceOneOf: options.licenceOneOf,
1119 languageOneOf: options.languageOneOf,
1120 tagsOneOf: options.tagsOneOf,
1121 tagsAllOf: options.tagsAllOf,
1122 filter: options.filter,
1123 withFiles: options.withFiles,
1124 accountId: options.accountId,
1125 videoChannelId: options.videoChannelId,
1126 videoPlaylistId: options.videoPlaylistId,
1127 includeLocalVideos: options.includeLocalVideos,
1129 historyOfUser: options.historyOfUser,
1131 search: options.search
1134 return VideoModel.getAvailableForApi(queryOptions, options.countVideos)
1137 static async searchAndPopulateAccountAndServer (options: {
1138 includeLocalVideos: boolean
1143 startDate?: string // ISO 8601
1144 endDate?: string // ISO 8601
1145 originallyPublishedStartDate?: string
1146 originallyPublishedEndDate?: string
1148 categoryOneOf?: number[]
1149 licenceOneOf?: number[]
1150 languageOneOf?: string[]
1151 tagsOneOf?: string[]
1152 tagsAllOf?: string[]
1153 durationMin?: number // seconds
1154 durationMax?: number // seconds
1155 user?: MUserAccountId
1156 filter?: VideoFilter
1158 const serverActor = await getServerActor()
1159 const queryOptions = {
1160 followerActorId: serverActor.id,
1161 serverAccountId: serverActor.Account.id,
1162 includeLocalVideos: options.includeLocalVideos,
1164 categoryOneOf: options.categoryOneOf,
1165 licenceOneOf: options.licenceOneOf,
1166 languageOneOf: options.languageOneOf,
1167 tagsOneOf: options.tagsOneOf,
1168 tagsAllOf: options.tagsAllOf,
1170 filter: options.filter,
1171 start: options.start,
1172 count: options.count,
1174 startDate: options.startDate,
1175 endDate: options.endDate,
1176 originallyPublishedStartDate: options.originallyPublishedStartDate,
1177 originallyPublishedEndDate: options.originallyPublishedEndDate,
1179 durationMin: options.durationMin,
1180 durationMax: options.durationMax,
1182 search: options.search
1185 return VideoModel.getAvailableForApi(queryOptions)
1188 static countLocalLives () {
1194 [Op.ne]: VideoState.LIVE_ENDED
1199 return VideoModel.count(options)
1202 static countVideosUploadedByUserSince (userId: number, since: Date) {
1206 model: VideoChannelModel.unscoped(),
1210 model: AccountModel.unscoped(),
1214 model: UserModel.unscoped(),
1232 return VideoModel.unscoped().count(options)
1235 static countLivesOfAccount (accountId: number) {
1241 [Op.ne]: VideoState.LIVE_ENDED
1247 model: VideoChannelModel.unscoped(),
1255 return VideoModel.count(options)
1258 static load (id: number | string, t?: Transaction): Promise<MVideoThumbnail> {
1259 const where = buildWhereIdOrUUID(id)
1265 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1268 static loadWithBlacklist (id: number | string, t?: Transaction): Promise<MVideoThumbnailBlacklist> {
1269 const where = buildWhereIdOrUUID(id)
1275 return VideoModel.scope([
1276 ScopeNames.WITH_THUMBNAILS,
1277 ScopeNames.WITH_BLACKLISTED
1281 static loadImmutableAttributes (id: number | string, t?: Transaction): Promise<MVideoImmutable> {
1284 where: buildWhereIdOrUUID(id),
1288 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1291 return ModelCache.Instance.doCache({
1292 cacheType: 'load-video-immutable-id',
1299 static loadWithRights (id: number | string, t?: Transaction): Promise<MVideoWithRights> {
1300 const where = buildWhereIdOrUUID(id)
1306 return VideoModel.scope([
1307 ScopeNames.WITH_BLACKLISTED,
1308 ScopeNames.WITH_USER_ID,
1309 ScopeNames.WITH_THUMBNAILS
1313 static loadOnlyId (id: number | string, t?: Transaction): Promise<MVideoIdThumbnail> {
1314 const where = buildWhereIdOrUUID(id)
1317 attributes: [ 'id' ],
1322 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1325 static loadWithFiles (id: number | string, t?: Transaction, logging?: boolean): Promise<MVideoWithAllFiles> {
1326 const where = buildWhereIdOrUUID(id)
1334 return VideoModel.scope([
1335 ScopeNames.WITH_WEBTORRENT_FILES,
1336 ScopeNames.WITH_STREAMING_PLAYLISTS,
1337 ScopeNames.WITH_THUMBNAILS
1341 static loadByUUID (uuid: string): Promise<MVideoThumbnail> {
1348 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1351 static loadByUrl (url: string, transaction?: Transaction): Promise<MVideoThumbnail> {
1352 const query: FindOptions = {
1359 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(query)
1362 static loadByUrlImmutableAttributes (url: string, transaction?: Transaction): Promise<MVideoImmutable> {
1364 const query: FindOptions = {
1371 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1374 return ModelCache.Instance.doCache({
1375 cacheType: 'load-video-immutable-url',
1382 static loadByUrlAndPopulateAccount (url: string, transaction?: Transaction): Promise<MVideoAccountLightBlacklistAllFiles> {
1383 const query: FindOptions = {
1390 return VideoModel.scope([
1391 ScopeNames.WITH_ACCOUNT_DETAILS,
1392 ScopeNames.WITH_WEBTORRENT_FILES,
1393 ScopeNames.WITH_STREAMING_PLAYLISTS,
1394 ScopeNames.WITH_THUMBNAILS,
1395 ScopeNames.WITH_BLACKLISTED
1399 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Transaction, userId?: number): Promise<MVideoFullLight> {
1400 const where = buildWhereIdOrUUID(id)
1403 order: [ [ 'Tags', 'name', 'ASC' ] ] as any,
1408 const scopes: (string | ScopeOptions)[] = [
1409 ScopeNames.WITH_TAGS,
1410 ScopeNames.WITH_BLACKLISTED,
1411 ScopeNames.WITH_ACCOUNT_DETAILS,
1412 ScopeNames.WITH_SCHEDULED_UPDATE,
1413 ScopeNames.WITH_WEBTORRENT_FILES,
1414 ScopeNames.WITH_STREAMING_PLAYLISTS,
1415 ScopeNames.WITH_THUMBNAILS,
1416 ScopeNames.WITH_LIVE
1420 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1428 static loadForGetAPI (parameters: {
1432 }): Promise<MVideoDetails> {
1433 const { id, t, userId } = parameters
1434 const where = buildWhereIdOrUUID(id)
1437 order: [ [ 'Tags', 'name', 'ASC' ] ] as any, // FIXME: sequelize typings
1442 const scopes: (string | ScopeOptions)[] = [
1443 ScopeNames.WITH_TAGS,
1444 ScopeNames.WITH_BLACKLISTED,
1445 ScopeNames.WITH_ACCOUNT_DETAILS,
1446 ScopeNames.WITH_SCHEDULED_UPDATE,
1447 ScopeNames.WITH_THUMBNAILS,
1448 ScopeNames.WITH_LIVE,
1449 { method: [ ScopeNames.WITH_WEBTORRENT_FILES, true ] },
1450 { method: [ ScopeNames.WITH_STREAMING_PLAYLISTS, true ] }
1454 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1462 static async getStats () {
1463 const totalLocalVideos = await VideoModel.count({
1469 let totalLocalVideoViews = await VideoModel.sum('views', {
1475 // Sequelize could return null...
1476 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1478 const { total: totalVideos } = await VideoModel.listForApi({
1481 sort: '-publishedAt',
1482 nsfw: buildNSFWFilter(),
1483 includeLocalVideos: true,
1489 totalLocalVideoViews,
1494 static incrementViews (id: number, views: number) {
1495 return VideoModel.increment('views', {
1503 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1504 // Instances only share videos
1505 const query = 'SELECT 1 FROM "videoShare" ' +
1506 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1507 'WHERE "actorFollow"."actorId" = $followerActorId AND "actorFollow"."state" = \'accepted\' AND "videoShare"."videoId" = $videoId ' +
1511 type: QueryTypes.SELECT as QueryTypes.SELECT,
1512 bind: { followerActorId, videoId },
1516 return VideoModel.sequelize.query(query, options)
1517 .then(results => results.length === 1)
1520 static bulkUpdateSupportField (videoChannel: MChannel, t: Transaction) {
1523 channelId: videoChannel.id
1528 return VideoModel.update({ support: videoChannel.support }, options)
1531 static getAllIdsFromChannel (videoChannel: MChannelId): Promise<number[]> {
1533 attributes: [ 'id' ],
1535 channelId: videoChannel.id
1539 return VideoModel.findAll(query)
1540 .then(videos => videos.map(v => v.id))
1543 // threshold corresponds to how many video the field should have to be returned
1544 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1545 const serverActor = await getServerActor()
1546 const followerActorId = serverActor.id
1548 const queryOptions: BuildVideosQueryOptions = {
1549 attributes: [ `"${field}"` ],
1550 group: `GROUP BY "${field}"`,
1551 having: `HAVING COUNT("${field}") >= ${threshold}`,
1555 serverAccountId: serverActor.Account.id,
1557 includeLocalVideos: true
1560 const { query, replacements } = buildListQuery(VideoModel, queryOptions)
1562 return this.sequelize.query<any>(query, { replacements, type: QueryTypes.SELECT })
1563 .then(rows => rows.map(r => r[field]))
1566 static buildTrendingQuery (trendingDays: number) {
1570 model: VideoViewModel,
1574 [Op.gte]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1580 private static async getAvailableForApi (
1581 options: BuildVideosQueryOptions,
1583 ): Promise<ResultList<VideoModel>> {
1584 function getCount () {
1585 if (countVideos !== true) return Promise.resolve(undefined)
1587 const countOptions = Object.assign({}, options, { isCount: true })
1588 const { query: queryCount, replacements: replacementsCount } = buildListQuery(VideoModel, countOptions)
1590 return VideoModel.sequelize.query<any>(queryCount, { replacements: replacementsCount, type: QueryTypes.SELECT })
1591 .then(rows => rows.length !== 0 ? rows[0].total : 0)
1594 function getModels () {
1595 if (options.count === 0) return Promise.resolve([])
1597 const { query, replacements, order } = buildListQuery(VideoModel, options)
1598 const queryModels = wrapForAPIResults(query, replacements, options, order)
1600 return VideoModel.sequelize.query<any>(queryModels, { replacements, type: QueryTypes.SELECT, nest: true })
1601 .then(rows => VideoModel.buildAPIResult(rows))
1604 const [ count, rows ] = await Promise.all([ getCount(), getModels() ])
1612 private static buildAPIResult (rows: any[]) {
1613 const videosMemo: { [ id: number ]: VideoModel } = {}
1614 const videoStreamingPlaylistMemo: { [ id: number ]: VideoStreamingPlaylistModel } = {}
1616 const thumbnailsDone = new Set<number>()
1617 const historyDone = new Set<number>()
1618 const videoFilesDone = new Set<number>()
1620 const videos: VideoModel[] = []
1622 const avatarKeys = [ 'id', 'filename', 'fileUrl', 'onDisk', 'createdAt', 'updatedAt' ]
1623 const actorKeys = [ 'id', 'preferredUsername', 'url', 'serverId', 'avatarId' ]
1624 const serverKeys = [ 'id', 'host' ]
1625 const videoFileKeys = [ 'id', 'createdAt', 'updatedAt', 'resolution', 'size', 'extname', 'infoHash', 'fps', 'videoId' ]
1626 const videoStreamingPlaylistKeys = [ 'id' ]
1650 'originallyPublishedAt',
1656 function buildActor (rowActor: any) {
1657 const avatarModel = rowActor.Avatar.id !== null
1658 ? new AvatarModel(pick(rowActor.Avatar, avatarKeys))
1661 const serverModel = rowActor.Server.id !== null
1662 ? new ServerModel(pick(rowActor.Server, serverKeys))
1665 const actorModel = new ActorModel(pick(rowActor, actorKeys))
1666 actorModel.Avatar = avatarModel
1667 actorModel.Server = serverModel
1672 for (const row of rows) {
1673 if (!videosMemo[row.id]) {
1675 const channel = row.VideoChannel
1676 const channelModel = new VideoChannelModel(pick(channel, [ 'id', 'name', 'description', 'actorId' ]))
1677 channelModel.Actor = buildActor(channel.Actor)
1679 const account = row.VideoChannel.Account
1680 const accountModel = new AccountModel(pick(account, [ 'id', 'name' ]))
1681 accountModel.Actor = buildActor(account.Actor)
1683 channelModel.Account = accountModel
1685 const videoModel = new VideoModel(pick(row, videoKeys))
1686 videoModel.VideoChannel = channelModel
1688 videoModel.UserVideoHistories = []
1689 videoModel.Thumbnails = []
1690 videoModel.VideoFiles = []
1691 videoModel.VideoStreamingPlaylists = []
1693 videosMemo[row.id] = videoModel
1694 // Don't take object value to have a sorted array
1695 videos.push(videoModel)
1698 const videoModel = videosMemo[row.id]
1700 if (row.userVideoHistory?.id && !historyDone.has(row.userVideoHistory.id)) {
1701 const historyModel = new UserVideoHistoryModel(pick(row.userVideoHistory, [ 'id', 'currentTime' ]))
1702 videoModel.UserVideoHistories.push(historyModel)
1704 historyDone.add(row.userVideoHistory.id)
1707 if (row.Thumbnails?.id && !thumbnailsDone.has(row.Thumbnails.id)) {
1708 const thumbnailModel = new ThumbnailModel(pick(row.Thumbnails, [ 'id', 'type', 'filename' ]))
1709 videoModel.Thumbnails.push(thumbnailModel)
1711 thumbnailsDone.add(row.Thumbnails.id)
1714 if (row.VideoFiles?.id && !videoFilesDone.has(row.VideoFiles.id)) {
1715 const videoFileModel = new VideoFileModel(pick(row.VideoFiles, videoFileKeys))
1716 videoModel.VideoFiles.push(videoFileModel)
1718 videoFilesDone.add(row.VideoFiles.id)
1721 if (row.VideoStreamingPlaylists?.id && !videoStreamingPlaylistMemo[row.VideoStreamingPlaylists.id]) {
1722 const streamingPlaylist = new VideoStreamingPlaylistModel(pick(row.VideoStreamingPlaylists, videoStreamingPlaylistKeys))
1723 streamingPlaylist.VideoFiles = []
1725 videoModel.VideoStreamingPlaylists.push(streamingPlaylist)
1727 videoStreamingPlaylistMemo[streamingPlaylist.id] = streamingPlaylist
1730 if (row.VideoStreamingPlaylists?.VideoFiles?.id && !videoFilesDone.has(row.VideoStreamingPlaylists.VideoFiles.id)) {
1731 const streamingPlaylist = videoStreamingPlaylistMemo[row.VideoStreamingPlaylists.id]
1733 const videoFileModel = new VideoFileModel(pick(row.VideoStreamingPlaylists.VideoFiles, videoFileKeys))
1734 streamingPlaylist.VideoFiles.push(videoFileModel)
1736 videoFilesDone.add(row.VideoStreamingPlaylists.VideoFiles.id)
1743 static getCategoryLabel (id: number) {
1744 return VIDEO_CATEGORIES[id] || 'Misc'
1747 static getLicenceLabel (id: number) {
1748 return VIDEO_LICENCES[id] || 'Unknown'
1751 static getLanguageLabel (id: string) {
1752 return VIDEO_LANGUAGES[id] || 'Unknown'
1755 static getPrivacyLabel (id: number) {
1756 return VIDEO_PRIVACIES[id] || 'Unknown'
1759 static getStateLabel (id: number) {
1760 return VIDEO_STATES[id] || 'Unknown'
1764 return !!this.VideoBlacklist
1768 return this.VideoChannel.Account.Actor.Server?.isBlocked() || this.VideoChannel.Account.isBlocked()
1771 getQualityFileBy<T extends MVideoWithFile> (this: T, fun: (files: MVideoFile[], it: (file: MVideoFile) => number) => MVideoFile) {
1772 // We first transcode to WebTorrent format, so try this array first
1773 if (Array.isArray(this.VideoFiles) && this.VideoFiles.length !== 0) {
1774 const file = fun(this.VideoFiles, file => file.resolution)
1776 return Object.assign(file, { Video: this })
1779 // No webtorrent files, try with streaming playlist files
1780 if (Array.isArray(this.VideoStreamingPlaylists) && this.VideoStreamingPlaylists.length !== 0) {
1781 const streamingPlaylistWithVideo = Object.assign(this.VideoStreamingPlaylists[0], { Video: this })
1783 const file = fun(streamingPlaylistWithVideo.VideoFiles, file => file.resolution)
1784 return Object.assign(file, { VideoStreamingPlaylist: streamingPlaylistWithVideo })
1790 getMaxQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1791 return this.getQualityFileBy(maxBy)
1794 getMinQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1795 return this.getQualityFileBy(minBy)
1798 getWebTorrentFile<T extends MVideoWithFile> (this: T, resolution: number): MVideoFileVideo {
1799 if (Array.isArray(this.VideoFiles) === false) return undefined
1801 const file = this.VideoFiles.find(f => f.resolution === resolution)
1802 if (!file) return undefined
1804 return Object.assign(file, { Video: this })
1807 async addAndSaveThumbnail (thumbnail: MThumbnail, transaction: Transaction) {
1808 thumbnail.videoId = this.id
1810 const savedThumbnail = await thumbnail.save({ transaction })
1812 if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = []
1814 // Already have this thumbnail, skip
1815 if (this.Thumbnails.find(t => t.id === savedThumbnail.id)) return
1817 this.Thumbnails.push(savedThumbnail)
1820 generateThumbnailName () {
1821 return this.uuid + '.jpg'
1825 if (Array.isArray(this.Thumbnails) === false) return undefined
1827 return this.Thumbnails.find(t => t.type === ThumbnailType.MINIATURE)
1830 generatePreviewName () {
1831 return this.uuid + '.jpg'
1835 return !!this.getPreview()
1839 if (Array.isArray(this.Thumbnails) === false) return undefined
1841 return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW)
1845 return this.remote === false
1848 getWatchStaticPath () {
1849 return '/videos/watch/' + this.uuid
1852 getEmbedStaticPath () {
1853 return '/videos/embed/' + this.uuid
1856 getMiniatureStaticPath () {
1857 const thumbnail = this.getMiniature()
1858 if (!thumbnail) return null
1860 return join(STATIC_PATHS.THUMBNAILS, thumbnail.filename)
1863 getPreviewStaticPath () {
1864 const preview = this.getPreview()
1865 if (!preview) return null
1867 // We use a local cache, so specify our cache endpoint instead of potential remote URL
1868 return join(LAZY_STATIC_PATHS.PREVIEWS, preview.filename)
1871 toFormattedJSON (this: MVideoFormattable, options?: VideoFormattingJSONOptions): Video {
1872 return videoModelToFormattedJSON(this, options)
1875 toFormattedDetailsJSON (this: MVideoFormattableDetails): VideoDetails {
1876 return videoModelToFormattedDetailsJSON(this)
1879 getFormattedVideoFilesJSON (): VideoFile[] {
1880 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1881 let files: MVideoFileRedundanciesOpt[] = []
1883 if (Array.isArray(this.VideoFiles)) {
1884 files = files.concat(this.VideoFiles)
1887 for (const p of (this.VideoStreamingPlaylists || [])) {
1888 files = files.concat(p.VideoFiles || [])
1891 return videoFilesModelToFormattedJSON(this, baseUrlHttp, baseUrlWs, files)
1894 toActivityPubObject (this: MVideoAP): VideoObject {
1895 return videoModelToActivityPubObject(this)
1898 getTruncatedDescription () {
1899 if (!this.description) return null
1901 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1902 return peertubeTruncate(this.description, { length: maxLength })
1905 getMaxQualityResolution () {
1906 const file = this.getMaxQualityFile()
1907 const videoOrPlaylist = file.getVideoOrStreamingPlaylist()
1908 const originalFilePath = getVideoFilePath(videoOrPlaylist, file)
1910 return getVideoFileResolution(originalFilePath)
1913 getDescriptionAPIPath () {
1914 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1917 getHLSPlaylist (): MStreamingPlaylistFilesVideo {
1918 if (!this.VideoStreamingPlaylists) return undefined
1920 const playlist = this.VideoStreamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
1921 playlist.Video = this
1926 setHLSPlaylist (playlist: MStreamingPlaylist) {
1927 const toAdd = [ playlist ] as [ VideoStreamingPlaylistModel ]
1929 if (Array.isArray(this.VideoStreamingPlaylists) === false || this.VideoStreamingPlaylists.length === 0) {
1930 this.VideoStreamingPlaylists = toAdd
1934 this.VideoStreamingPlaylists = this.VideoStreamingPlaylists
1935 .filter(s => s.type !== VideoStreamingPlaylistType.HLS)
1939 removeFile (videoFile: MVideoFile, isRedundancy = false) {
1940 const filePath = getVideoFilePath(this, videoFile, isRedundancy)
1941 return remove(filePath)
1942 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1945 removeTorrent (videoFile: MVideoFile) {
1946 const torrentPath = getTorrentFilePath(this, videoFile)
1947 return remove(torrentPath)
1948 .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err }))
1951 async removeStreamingPlaylistFiles (streamingPlaylist: MStreamingPlaylist, isRedundancy = false) {
1952 const directoryPath = getHLSDirectory(this, isRedundancy)
1954 await remove(directoryPath)
1956 if (isRedundancy !== true) {
1957 const streamingPlaylistWithFiles = streamingPlaylist as MStreamingPlaylistFilesVideo
1958 streamingPlaylistWithFiles.Video = this
1960 if (!Array.isArray(streamingPlaylistWithFiles.VideoFiles)) {
1961 streamingPlaylistWithFiles.VideoFiles = await streamingPlaylistWithFiles.$get('VideoFiles')
1964 // Remove physical files and torrents
1966 streamingPlaylistWithFiles.VideoFiles.map(file => streamingPlaylistWithFiles.removeTorrent(file))
1972 if (this.isOwned()) return false
1974 return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)
1977 hasPrivacyForFederation () {
1978 return isPrivacyForFederation(this.privacy)
1981 hasStateForFederation () {
1982 return isStateForFederation(this.state)
1985 isNewVideo (newPrivacy: VideoPrivacy) {
1986 return this.hasPrivacyForFederation() === false && isPrivacyForFederation(newPrivacy) === true
1990 this.changed('updatedAt', true)
1996 return this.privacy === VideoPrivacy.PRIVATE || this.privacy === VideoPrivacy.INTERNAL || !!this.VideoBlacklist
1999 setPrivacy (newPrivacy: VideoPrivacy) {
2000 if (this.privacy === VideoPrivacy.PRIVATE && newPrivacy !== VideoPrivacy.PRIVATE) {
2001 this.publishedAt = new Date()
2004 this.privacy = newPrivacy
2008 return this.privacy === VideoPrivacy.PRIVATE ||
2009 this.privacy === VideoPrivacy.UNLISTED ||
2010 this.privacy === VideoPrivacy.INTERNAL
2013 async publishIfNeededAndSave (t: Transaction) {
2014 if (this.state !== VideoState.PUBLISHED) {
2015 this.state = VideoState.PUBLISHED
2016 this.publishedAt = new Date()
2017 await this.save({ transaction: t })
2026 if (this.isOwned()) {
2028 baseUrlHttp: WEBSERVER.URL,
2029 baseUrlWs: WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT
2034 baseUrlHttp: REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host,
2035 baseUrlWs: REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
2039 getTrackerUrls (baseUrlHttp: string, baseUrlWs: string) {
2040 return [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
2043 getTorrentUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2044 return baseUrlHttp + STATIC_PATHS.TORRENTS + getTorrentFileName(this, videoFile)
2047 getTorrentDownloadUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2048 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + getTorrentFileName(this, videoFile)
2051 getVideoFileUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2052 return baseUrlHttp + STATIC_PATHS.WEBSEED + getVideoFilename(this, videoFile)
2055 getVideoFileMetadataUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2056 const path = '/api/v1/videos/'
2058 return this.isOwned()
2059 ? baseUrlHttp + path + this.uuid + '/metadata/' + videoFile.id
2060 : videoFile.metadataUrl
2063 getVideoRedundancyUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2064 return baseUrlHttp + STATIC_PATHS.REDUNDANCY + getVideoFilename(this, videoFile)
2067 getVideoFileDownloadUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2068 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + getVideoFilename(this, videoFile)
2071 getBandwidthBits (videoFile: MVideoFile) {
2072 return Math.ceil((videoFile.size * 8) / this.duration)