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, 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, VideoRateType } 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'
69 } from '../../initializers/constants'
70 import { sendDeleteVideo } from '../../lib/activitypub/send'
73 MChannelAccountDefault,
76 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 { ActorImageModel } from '../account/actor-image'
103 import { UserModel } from '../account/user'
104 import { UserVideoHistoryModel } from '../account/user-video-history'
105 import { ActorModel } from '../activitypub/actor'
106 import { VideoRedundancyModel } from '../redundancy/video-redundancy'
107 import { ServerModel } from '../server/server'
108 import { TrackerModel } from '../server/tracker'
109 import { VideoTrackerModel } from '../server/video-tracker'
110 import { buildTrigramSearchIndex, buildWhereIdOrUUID, getVideoSort, isOutdated, throwIfNotValid } from '../utils'
111 import { ScheduleVideoUpdateModel } from './schedule-video-update'
112 import { TagModel } from './tag'
113 import { ThumbnailModel } from './thumbnail'
114 import { VideoBlacklistModel } from './video-blacklist'
115 import { VideoCaptionModel } from './video-caption'
116 import { ScopeNames as VideoChannelScopeNames, SummaryOptions, VideoChannelModel } from './video-channel'
117 import { VideoCommentModel } from './video-comment'
118 import { VideoFileModel } from './video-file'
120 videoFilesModelToFormattedJSON,
121 VideoFormattingJSONOptions,
122 videoModelToActivityPubObject,
123 videoModelToFormattedDetailsJSON,
124 videoModelToFormattedJSON
125 } from './video-format-utils'
126 import { VideoImportModel } from './video-import'
127 import { VideoLiveModel } from './video-live'
128 import { VideoPlaylistElementModel } from './video-playlist-element'
129 import { buildListQuery, BuildVideosQueryOptions, wrapForAPIResults } from './video-query-builder'
130 import { VideoShareModel } from './video-share'
131 import { VideoStreamingPlaylistModel } from './video-streaming-playlist'
132 import { VideoTagModel } from './video-tag'
133 import { VideoViewModel } from './video-view'
135 export enum ScopeNames {
136 AVAILABLE_FOR_LIST_IDS = 'AVAILABLE_FOR_LIST_IDS',
138 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
139 WITH_TAGS = 'WITH_TAGS',
140 WITH_TRACKERS = 'WITH_TRACKERS',
141 WITH_WEBTORRENT_FILES = 'WITH_WEBTORRENT_FILES',
142 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
143 WITH_BLACKLISTED = 'WITH_BLACKLISTED',
144 WITH_USER_HISTORY = 'WITH_USER_HISTORY',
145 WITH_STREAMING_PLAYLISTS = 'WITH_STREAMING_PLAYLISTS',
146 WITH_USER_ID = 'WITH_USER_ID',
147 WITH_IMMUTABLE_ATTRIBUTES = 'WITH_IMMUTABLE_ATTRIBUTES',
148 WITH_THUMBNAILS = 'WITH_THUMBNAILS',
149 WITH_LIVE = 'WITH_LIVE'
152 export type ForAPIOptions = {
155 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.videoPlaylistId) {
225 model: VideoPlaylistElementModel.unscoped(),
228 videoPlaylistId: options.videoPlaylistId
233 query.include = include
237 [ScopeNames.WITH_THUMBNAILS]: {
240 model: ThumbnailModel,
245 [ScopeNames.WITH_LIVE]: {
248 model: VideoLiveModel.unscoped(),
253 [ScopeNames.WITH_USER_ID]: {
256 attributes: [ 'accountId' ],
257 model: VideoChannelModel.unscoped(),
261 attributes: [ 'userId' ],
262 model: AccountModel.unscoped(),
269 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
272 model: VideoChannelModel.unscoped(),
277 exclude: [ 'privateKey', 'publicKey' ]
279 model: ActorModel.unscoped(),
283 attributes: [ 'host' ],
284 model: ServerModel.unscoped(),
288 model: ActorImageModel.unscoped(),
295 model: AccountModel.unscoped(),
299 model: ActorModel.unscoped(),
301 exclude: [ 'privateKey', 'publicKey' ]
306 attributes: [ 'host' ],
307 model: ServerModel.unscoped(),
311 model: ActorImageModel.unscoped(),
323 [ScopeNames.WITH_TAGS]: {
324 include: [ TagModel ]
326 [ScopeNames.WITH_TRACKERS]: {
329 attributes: [ 'id', 'url' ],
334 [ScopeNames.WITH_BLACKLISTED]: {
337 attributes: [ 'id', 'reason', 'unfederated' ],
338 model: VideoBlacklistModel,
343 [ScopeNames.WITH_WEBTORRENT_FILES]: (withRedundancies = false) => {
344 let subInclude: any[] = []
346 if (withRedundancies === true) {
349 attributes: [ 'fileUrl' ],
350 model: VideoRedundancyModel.unscoped(),
359 model: VideoFileModel,
367 [ScopeNames.WITH_STREAMING_PLAYLISTS]: (withRedundancies = false) => {
368 const subInclude: IncludeOptions[] = [
370 model: VideoFileModel,
375 if (withRedundancies === true) {
377 attributes: [ 'fileUrl' ],
378 model: VideoRedundancyModel.unscoped(),
386 model: VideoStreamingPlaylistModel.unscoped(),
394 [ScopeNames.WITH_SCHEDULED_UPDATE]: {
397 model: ScheduleVideoUpdateModel.unscoped(),
402 [ScopeNames.WITH_USER_HISTORY]: (userId: number) => {
406 attributes: [ 'currentTime' ],
407 model: UserVideoHistoryModel.unscoped(),
420 buildTrigramSearchIndex('video_name_trigram', 'name'),
422 { fields: [ 'createdAt' ] },
425 { name: 'publishedAt', order: 'DESC' },
426 { name: 'id', order: 'ASC' }
429 { fields: [ 'duration' ] },
432 { name: 'views', order: 'DESC' },
433 { name: 'id', order: 'ASC' }
436 { fields: [ 'channelId' ] },
438 fields: [ 'originallyPublishedAt' ],
440 originallyPublishedAt: {
446 fields: [ 'category' ], // We don't care videos with an unknown category
454 fields: [ 'licence' ], // We don't care videos with an unknown licence
462 fields: [ 'language' ], // We don't care videos with an unknown language
470 fields: [ 'nsfw' ], // Most of the videos are not NSFW
476 fields: [ 'remote' ], // Only index local videos
491 export class VideoModel extends Model {
494 @Default(DataType.UUIDV4)
496 @Column(DataType.UUID)
500 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
506 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category', true))
512 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence', true))
518 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language', true))
519 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
523 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
525 privacy: VideoPrivacy
528 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
534 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description', true))
535 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
540 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support', true))
541 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
545 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
580 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
581 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
586 commentsEnabled: boolean
590 downloadEnabled: boolean
594 waitTranscoding: boolean
598 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
609 @Default(DataType.NOW)
616 originallyPublishedAt: Date
618 @ForeignKey(() => VideoChannelModel)
622 @BelongsTo(() => VideoChannelModel, {
628 VideoChannel: VideoChannelModel
630 @BelongsToMany(() => TagModel, {
631 foreignKey: 'videoId',
632 through: () => VideoTagModel,
637 @BelongsToMany(() => TrackerModel, {
638 foreignKey: 'videoId',
639 through: () => VideoTrackerModel,
642 Trackers: TrackerModel[]
644 @HasMany(() => ThumbnailModel, {
652 Thumbnails: ThumbnailModel[]
654 @HasMany(() => VideoPlaylistElementModel, {
661 VideoPlaylistElements: VideoPlaylistElementModel[]
663 @HasMany(() => VideoAbuseModel, {
670 VideoAbuses: VideoAbuseModel[]
672 @HasMany(() => VideoFileModel, {
680 VideoFiles: VideoFileModel[]
682 @HasMany(() => VideoStreamingPlaylistModel, {
690 VideoStreamingPlaylists: VideoStreamingPlaylistModel[]
692 @HasMany(() => VideoShareModel, {
699 VideoShares: VideoShareModel[]
701 @HasMany(() => AccountVideoRateModel, {
708 AccountVideoRates: AccountVideoRateModel[]
710 @HasMany(() => VideoCommentModel, {
718 VideoComments: VideoCommentModel[]
720 @HasMany(() => VideoViewModel, {
727 VideoViews: VideoViewModel[]
729 @HasMany(() => UserVideoHistoryModel, {
736 UserVideoHistories: UserVideoHistoryModel[]
738 @HasOne(() => ScheduleVideoUpdateModel, {
745 ScheduleVideoUpdate: ScheduleVideoUpdateModel
747 @HasOne(() => VideoBlacklistModel, {
754 VideoBlacklist: VideoBlacklistModel
756 @HasOne(() => VideoLiveModel, {
763 VideoLive: VideoLiveModel
765 @HasOne(() => VideoImportModel, {
772 VideoImport: VideoImportModel
774 @HasMany(() => VideoCaptionModel, {
781 ['separate' as any]: true
783 VideoCaptions: VideoCaptionModel[]
786 static async sendDelete (instance: MVideoAccountLight, options) {
787 if (!instance.isOwned()) return undefined
789 // Lazy load channels
790 if (!instance.VideoChannel) {
791 instance.VideoChannel = await instance.$get('VideoChannel', {
796 transaction: options.transaction
797 }) as MChannelAccountDefault
800 return sendDeleteVideo(instance, options.transaction)
804 static async removeFiles (instance: VideoModel) {
805 const tasks: Promise<any>[] = []
807 logger.info('Removing files of video %s.', instance.url)
809 if (instance.isOwned()) {
810 if (!Array.isArray(instance.VideoFiles)) {
811 instance.VideoFiles = await instance.$get('VideoFiles')
814 // Remove physical files and torrents
815 instance.VideoFiles.forEach(file => {
816 tasks.push(instance.removeFile(file))
817 tasks.push(file.removeTorrent())
820 // Remove playlists file
821 if (!Array.isArray(instance.VideoStreamingPlaylists)) {
822 instance.VideoStreamingPlaylists = await instance.$get('VideoStreamingPlaylists')
825 for (const p of instance.VideoStreamingPlaylists) {
826 tasks.push(instance.removeStreamingPlaylistFiles(p))
830 // Do not wait video deletion because we could be in a transaction
833 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
840 static stopLiveIfNeeded (instance: VideoModel) {
841 if (!instance.isLive) return
843 logger.info('Stopping live of video %s after video deletion.', instance.uuid)
845 return LiveManager.Instance.stopSessionOf(instance.id)
849 static invalidateCache (instance: VideoModel) {
850 ModelCache.Instance.invalidateCache('video', instance.id)
854 static async saveEssentialDataToAbuses (instance: VideoModel, options) {
855 const tasks: Promise<any>[] = []
857 if (!Array.isArray(instance.VideoAbuses)) {
858 instance.VideoAbuses = await instance.$get('VideoAbuses')
860 if (instance.VideoAbuses.length === 0) return undefined
863 logger.info('Saving video abuses details of video %s.', instance.url)
865 if (!instance.Trackers) instance.Trackers = await instance.$get('Trackers', { transaction: options.transaction })
866 const details = instance.toFormattedDetailsJSON()
868 for (const abuse of instance.VideoAbuses) {
869 abuse.deletedVideo = details
870 tasks.push(abuse.save({ transaction: options.transaction }))
875 logger.error('Some errors when saving details of video %s in its abuses before destroy hook.', instance.uuid, { err })
881 static listLocal (): Promise<MVideo[]> {
888 return VideoModel.findAll(query)
891 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
892 function getRawQuery (select: string) {
893 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
894 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
895 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
896 'WHERE "Account"."actorId" = ' + actorId
897 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
898 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
899 'WHERE "VideoShare"."actorId" = ' + actorId
901 return `(${queryVideo}) UNION (${queryVideoShare})`
904 const rawQuery = getRawQuery('"Video"."id"')
905 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
911 order: getVideoSort('-createdAt', [ 'Tags', 'name', 'ASC' ] as any), // FIXME: sequelize typings
914 [Op.in]: Sequelize.literal('(' + rawQuery + ')')
916 [Op.or]: getPrivaciesForFederation()
920 attributes: [ 'filename', 'language', 'fileUrl' ],
921 model: VideoCaptionModel.unscoped(),
925 attributes: [ 'id', 'url' ],
926 model: VideoShareModel.unscoped(),
928 // We only want videos shared by this actor
943 attributes: [ 'id', 'url' ],
944 model: ActorModel.unscoped()
949 model: VideoChannelModel.unscoped(),
953 attributes: [ 'name' ],
954 model: AccountModel.unscoped(),
958 attributes: [ 'id', 'url', 'followersUrl' ],
959 model: ActorModel.unscoped(),
965 attributes: [ 'id', 'url', 'followersUrl' ],
966 model: ActorModel.unscoped(),
972 model: VideoStreamingPlaylistModel.unscoped(),
976 model: VideoFileModel,
981 VideoLiveModel.unscoped(),
987 return Bluebird.all([
988 VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findAll(query),
989 VideoModel.sequelize.query<{ total: string }>(rawCountQuery, { type: QueryTypes.SELECT })
990 ]).then(([ rows, totals ]) => {
991 // totals: totalVideos + totalVideoShares
993 let totalVideoShares = 0
994 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
995 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
997 const total = totalVideos + totalVideoShares
1005 static async listPublishedLiveIds () {
1007 attributes: [ 'id' ],
1010 state: VideoState.PUBLISHED
1014 const result = await VideoModel.findAll(options)
1016 return result.map(v => v.id)
1019 static listUserVideosForApi (options: {
1027 const { accountId, start, count, sort, search, isLive } = options
1029 function buildBaseQuery (): FindOptions {
1030 const where: WhereOptions = {}
1034 [Op.iLike]: '%' + search + '%'
1039 where.isLive = isLive
1046 order: getVideoSort(sort),
1049 model: VideoChannelModel,
1053 model: AccountModel,
1067 const countQuery = buildBaseQuery()
1068 const findQuery = buildBaseQuery()
1070 const findScopes: (string | ScopeOptions)[] = [
1071 ScopeNames.WITH_SCHEDULED_UPDATE,
1072 ScopeNames.WITH_BLACKLISTED,
1073 ScopeNames.WITH_THUMBNAILS
1076 return Promise.all([
1077 VideoModel.count(countQuery),
1078 VideoModel.scope(findScopes).findAll<MVideoForUser>(findQuery)
1079 ]).then(([ count, rows ]) => {
1087 static async listForApi (options: {
1093 filter?: VideoFilter
1096 includeLocalVideos: boolean
1099 categoryOneOf?: number[]
1100 licenceOneOf?: number[]
1101 languageOneOf?: string[]
1102 tagsOneOf?: string[]
1103 tagsAllOf?: string[]
1106 videoChannelId?: number
1108 followerActorId?: number
1110 videoPlaylistId?: number
1112 trendingDays?: number
1114 user?: MUserAccountId
1115 historyOfUser?: MUserId
1117 countVideos?: boolean
1121 if ((options.filter === 'all-local' || options.filter === 'all') && !options.user.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1122 throw new Error('Try to filter all-local but no user has not the see all videos right')
1125 const trendingDays = options.sort.endsWith('trending')
1126 ? CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1128 let trendingAlgorithm
1129 if (options.sort.endsWith('hot')) trendingAlgorithm = 'hot'
1130 if (options.sort.endsWith('best')) trendingAlgorithm = 'best'
1132 const serverActor = await getServerActor()
1134 // followerActorId === null has a meaning, so just check undefined
1135 const followerActorId = options.followerActorId !== undefined
1136 ? options.followerActorId
1139 const queryOptions = {
1140 start: options.start,
1141 count: options.count,
1144 serverAccountId: serverActor.Account.id,
1146 isLive: options.isLive,
1147 categoryOneOf: options.categoryOneOf,
1148 licenceOneOf: options.licenceOneOf,
1149 languageOneOf: options.languageOneOf,
1150 tagsOneOf: options.tagsOneOf,
1151 tagsAllOf: options.tagsAllOf,
1152 filter: options.filter,
1153 withFiles: options.withFiles,
1154 accountId: options.accountId,
1155 videoChannelId: options.videoChannelId,
1156 videoPlaylistId: options.videoPlaylistId,
1157 includeLocalVideos: options.includeLocalVideos,
1159 historyOfUser: options.historyOfUser,
1162 search: options.search
1165 return VideoModel.getAvailableForApi(queryOptions, options.countVideos)
1168 static async searchAndPopulateAccountAndServer (options: {
1169 includeLocalVideos: boolean
1174 startDate?: string // ISO 8601
1175 endDate?: string // ISO 8601
1176 originallyPublishedStartDate?: string
1177 originallyPublishedEndDate?: string
1180 categoryOneOf?: number[]
1181 licenceOneOf?: number[]
1182 languageOneOf?: string[]
1183 tagsOneOf?: string[]
1184 tagsAllOf?: string[]
1185 durationMin?: number // seconds
1186 durationMax?: number // seconds
1187 user?: MUserAccountId
1188 filter?: VideoFilter
1190 const serverActor = await getServerActor()
1192 const queryOptions = {
1193 followerActorId: serverActor.id,
1194 serverAccountId: serverActor.Account.id,
1196 includeLocalVideos: options.includeLocalVideos,
1198 isLive: options.isLive,
1200 categoryOneOf: options.categoryOneOf,
1201 licenceOneOf: options.licenceOneOf,
1202 languageOneOf: options.languageOneOf,
1204 tagsOneOf: options.tagsOneOf,
1205 tagsAllOf: options.tagsAllOf,
1208 filter: options.filter,
1210 start: options.start,
1211 count: options.count,
1214 startDate: options.startDate,
1215 endDate: options.endDate,
1217 originallyPublishedStartDate: options.originallyPublishedStartDate,
1218 originallyPublishedEndDate: options.originallyPublishedEndDate,
1220 durationMin: options.durationMin,
1221 durationMax: options.durationMax,
1223 search: options.search
1226 return VideoModel.getAvailableForApi(queryOptions)
1229 static countLocalLives () {
1235 [Op.ne]: VideoState.LIVE_ENDED
1240 return VideoModel.count(options)
1243 static countVideosUploadedByUserSince (userId: number, since: Date) {
1247 model: VideoChannelModel.unscoped(),
1251 model: AccountModel.unscoped(),
1255 model: UserModel.unscoped(),
1273 return VideoModel.unscoped().count(options)
1276 static countLivesOfAccount (accountId: number) {
1282 [Op.ne]: VideoState.LIVE_ENDED
1288 model: VideoChannelModel.unscoped(),
1296 return VideoModel.count(options)
1299 static load (id: number | string, t?: Transaction): Promise<MVideoThumbnail> {
1300 const where = buildWhereIdOrUUID(id)
1306 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1309 static loadWithBlacklist (id: number | string, t?: Transaction): Promise<MVideoThumbnailBlacklist> {
1310 const where = buildWhereIdOrUUID(id)
1316 return VideoModel.scope([
1317 ScopeNames.WITH_THUMBNAILS,
1318 ScopeNames.WITH_BLACKLISTED
1322 static loadImmutableAttributes (id: number | string, t?: Transaction): Promise<MVideoImmutable> {
1325 where: buildWhereIdOrUUID(id),
1329 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1332 return ModelCache.Instance.doCache({
1333 cacheType: 'load-video-immutable-id',
1340 static loadWithRights (id: number | string, t?: Transaction): Promise<MVideoWithRights> {
1341 const where = buildWhereIdOrUUID(id)
1347 return VideoModel.scope([
1348 ScopeNames.WITH_BLACKLISTED,
1349 ScopeNames.WITH_USER_ID
1353 static loadOnlyId (id: number | string, t?: Transaction): Promise<MVideoIdThumbnail> {
1354 const where = buildWhereIdOrUUID(id)
1357 attributes: [ 'id' ],
1362 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1365 static loadWithFiles (id: number | string, t?: Transaction, logging?: boolean): Promise<MVideoWithAllFiles> {
1366 const where = buildWhereIdOrUUID(id)
1374 return VideoModel.scope([
1375 ScopeNames.WITH_WEBTORRENT_FILES,
1376 ScopeNames.WITH_STREAMING_PLAYLISTS,
1377 ScopeNames.WITH_THUMBNAILS
1381 static loadByUUID (uuid: string): Promise<MVideoThumbnail> {
1388 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1391 static loadByUrl (url: string, transaction?: Transaction): Promise<MVideoThumbnail> {
1392 const query: FindOptions = {
1399 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(query)
1402 static loadByUrlImmutableAttributes (url: string, transaction?: Transaction): Promise<MVideoImmutable> {
1404 const query: FindOptions = {
1411 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1414 return ModelCache.Instance.doCache({
1415 cacheType: 'load-video-immutable-url',
1422 static loadByUrlAndPopulateAccount (url: string, transaction?: Transaction): Promise<MVideoAccountLightBlacklistAllFiles> {
1423 const query: FindOptions = {
1430 return VideoModel.scope([
1431 ScopeNames.WITH_ACCOUNT_DETAILS,
1432 ScopeNames.WITH_WEBTORRENT_FILES,
1433 ScopeNames.WITH_STREAMING_PLAYLISTS,
1434 ScopeNames.WITH_THUMBNAILS,
1435 ScopeNames.WITH_BLACKLISTED
1439 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Transaction, userId?: number): Promise<MVideoFullLight> {
1440 const where = buildWhereIdOrUUID(id)
1443 order: [ [ 'Tags', 'name', 'ASC' ] ] as any,
1448 const scopes: (string | ScopeOptions)[] = [
1449 ScopeNames.WITH_TAGS,
1450 ScopeNames.WITH_BLACKLISTED,
1451 ScopeNames.WITH_ACCOUNT_DETAILS,
1452 ScopeNames.WITH_SCHEDULED_UPDATE,
1453 ScopeNames.WITH_WEBTORRENT_FILES,
1454 ScopeNames.WITH_STREAMING_PLAYLISTS,
1455 ScopeNames.WITH_THUMBNAILS,
1456 ScopeNames.WITH_LIVE
1460 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1468 static loadForGetAPI (parameters: {
1472 }): Promise<MVideoDetails> {
1473 const { id, t, userId } = parameters
1474 const where = buildWhereIdOrUUID(id)
1477 order: [ [ 'Tags', 'name', 'ASC' ] ] as any, // FIXME: sequelize typings
1482 const scopes: (string | ScopeOptions)[] = [
1483 ScopeNames.WITH_TAGS,
1484 ScopeNames.WITH_BLACKLISTED,
1485 ScopeNames.WITH_ACCOUNT_DETAILS,
1486 ScopeNames.WITH_SCHEDULED_UPDATE,
1487 ScopeNames.WITH_THUMBNAILS,
1488 ScopeNames.WITH_LIVE,
1489 ScopeNames.WITH_TRACKERS,
1490 { method: [ ScopeNames.WITH_WEBTORRENT_FILES, true ] },
1491 { method: [ ScopeNames.WITH_STREAMING_PLAYLISTS, true ] }
1495 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1503 static async getStats () {
1504 const totalLocalVideos = await VideoModel.count({
1510 let totalLocalVideoViews = await VideoModel.sum('views', {
1516 // Sequelize could return null...
1517 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1519 const { total: totalVideos } = await VideoModel.listForApi({
1522 sort: '-publishedAt',
1523 nsfw: buildNSFWFilter(),
1524 includeLocalVideos: true,
1530 totalLocalVideoViews,
1535 static incrementViews (id: number, views: number) {
1536 return VideoModel.increment('views', {
1544 static updateRatesOf (videoId: number, type: VideoRateType, t: Transaction) {
1545 const field = type === 'like'
1549 const rawQuery = `UPDATE "video" SET "${field}" = ` +
1551 'SELECT COUNT(id) FROM "accountVideoRate" WHERE "accountVideoRate"."videoId" = "video"."id" AND type = :rateType' +
1553 'WHERE "video"."id" = :videoId'
1555 return AccountVideoRateModel.sequelize.query(rawQuery, {
1557 replacements: { videoId, rateType: type },
1558 type: QueryTypes.UPDATE
1562 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1563 // Instances only share videos
1564 const query = 'SELECT 1 FROM "videoShare" ' +
1565 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1566 'WHERE "actorFollow"."actorId" = $followerActorId AND "actorFollow"."state" = \'accepted\' AND "videoShare"."videoId" = $videoId ' +
1570 type: QueryTypes.SELECT as QueryTypes.SELECT,
1571 bind: { followerActorId, videoId },
1575 return VideoModel.sequelize.query(query, options)
1576 .then(results => results.length === 1)
1579 static bulkUpdateSupportField (videoChannel: MChannel, t: Transaction) {
1582 channelId: videoChannel.id
1587 return VideoModel.update({ support: videoChannel.support }, options)
1590 static getAllIdsFromChannel (videoChannel: MChannelId): Promise<number[]> {
1592 attributes: [ 'id' ],
1594 channelId: videoChannel.id
1598 return VideoModel.findAll(query)
1599 .then(videos => videos.map(v => v.id))
1602 // threshold corresponds to how many video the field should have to be returned
1603 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1604 const serverActor = await getServerActor()
1605 const followerActorId = serverActor.id
1607 const queryOptions: BuildVideosQueryOptions = {
1608 attributes: [ `"${field}"` ],
1609 group: `GROUP BY "${field}"`,
1610 having: `HAVING COUNT("${field}") >= ${threshold}`,
1614 serverAccountId: serverActor.Account.id,
1616 includeLocalVideos: true
1619 const { query, replacements } = buildListQuery(VideoModel, queryOptions)
1621 return this.sequelize.query<any>(query, { replacements, type: QueryTypes.SELECT })
1622 .then(rows => rows.map(r => r[field]))
1625 static buildTrendingQuery (trendingDays: number) {
1629 model: VideoViewModel,
1633 [Op.gte]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1639 private static async getAvailableForApi (
1640 options: BuildVideosQueryOptions,
1642 ): Promise<ResultList<VideoModel>> {
1643 function getCount () {
1644 if (countVideos !== true) return Promise.resolve(undefined)
1646 const countOptions = Object.assign({}, options, { isCount: true })
1647 const { query: queryCount, replacements: replacementsCount } = buildListQuery(VideoModel, countOptions)
1649 return VideoModel.sequelize.query<any>(queryCount, { replacements: replacementsCount, type: QueryTypes.SELECT })
1650 .then(rows => rows.length !== 0 ? rows[0].total : 0)
1653 function getModels () {
1654 if (options.count === 0) return Promise.resolve([])
1656 const { query, replacements, order } = buildListQuery(VideoModel, options)
1657 const queryModels = wrapForAPIResults(query, replacements, options, order)
1659 return VideoModel.sequelize.query<any>(queryModels, { replacements, type: QueryTypes.SELECT, nest: true })
1660 .then(rows => VideoModel.buildAPIResult(rows))
1663 const [ count, rows ] = await Promise.all([ getCount(), getModels() ])
1671 private static buildAPIResult (rows: any[]) {
1672 const videosMemo: { [ id: number ]: VideoModel } = {}
1673 const videoStreamingPlaylistMemo: { [ id: number ]: VideoStreamingPlaylistModel } = {}
1675 const thumbnailsDone = new Set<number>()
1676 const historyDone = new Set<number>()
1677 const videoFilesDone = new Set<number>()
1679 const videos: VideoModel[] = []
1681 const avatarKeys = [ 'id', 'filename', 'fileUrl', 'onDisk', 'createdAt', 'updatedAt' ]
1682 const actorKeys = [ 'id', 'preferredUsername', 'url', 'serverId', 'avatarId' ]
1683 const serverKeys = [ 'id', 'host' ]
1684 const videoFileKeys = [
1698 'videoStreamingPlaylistId'
1700 const videoStreamingPlaylistKeys = [ 'id', 'type', 'playlistUrl' ]
1724 'originallyPublishedAt',
1729 const buildOpts = { raw: true }
1731 function buildActor (rowActor: any) {
1732 const avatarModel = rowActor.Avatar.id !== null
1733 ? new ActorImageModel(pick(rowActor.Avatar, avatarKeys), buildOpts)
1736 const serverModel = rowActor.Server.id !== null
1737 ? new ServerModel(pick(rowActor.Server, serverKeys), buildOpts)
1740 const actorModel = new ActorModel(pick(rowActor, actorKeys), buildOpts)
1741 actorModel.Avatar = avatarModel
1742 actorModel.Server = serverModel
1747 for (const row of rows) {
1748 if (!videosMemo[row.id]) {
1750 const channel = row.VideoChannel
1751 const channelModel = new VideoChannelModel(pick(channel, [ 'id', 'name', 'description', 'actorId' ]), buildOpts)
1752 channelModel.Actor = buildActor(channel.Actor)
1754 const account = row.VideoChannel.Account
1755 const accountModel = new AccountModel(pick(account, [ 'id', 'name' ]), buildOpts)
1756 accountModel.Actor = buildActor(account.Actor)
1758 channelModel.Account = accountModel
1760 const videoModel = new VideoModel(pick(row, videoKeys), buildOpts)
1761 videoModel.VideoChannel = channelModel
1763 videoModel.UserVideoHistories = []
1764 videoModel.Thumbnails = []
1765 videoModel.VideoFiles = []
1766 videoModel.VideoStreamingPlaylists = []
1768 videosMemo[row.id] = videoModel
1769 // Don't take object value to have a sorted array
1770 videos.push(videoModel)
1773 const videoModel = videosMemo[row.id]
1775 if (row.userVideoHistory?.id && !historyDone.has(row.userVideoHistory.id)) {
1776 const historyModel = new UserVideoHistoryModel(pick(row.userVideoHistory, [ 'id', 'currentTime' ]), buildOpts)
1777 videoModel.UserVideoHistories.push(historyModel)
1779 historyDone.add(row.userVideoHistory.id)
1782 if (row.Thumbnails?.id && !thumbnailsDone.has(row.Thumbnails.id)) {
1783 const thumbnailModel = new ThumbnailModel(pick(row.Thumbnails, [ 'id', 'type', 'filename' ]), buildOpts)
1784 videoModel.Thumbnails.push(thumbnailModel)
1786 thumbnailsDone.add(row.Thumbnails.id)
1789 if (row.VideoFiles?.id && !videoFilesDone.has(row.VideoFiles.id)) {
1790 const videoFileModel = new VideoFileModel(pick(row.VideoFiles, videoFileKeys), buildOpts)
1791 videoModel.VideoFiles.push(videoFileModel)
1793 videoFilesDone.add(row.VideoFiles.id)
1796 if (row.VideoStreamingPlaylists?.id && !videoStreamingPlaylistMemo[row.VideoStreamingPlaylists.id]) {
1797 const streamingPlaylist = new VideoStreamingPlaylistModel(pick(row.VideoStreamingPlaylists, videoStreamingPlaylistKeys), buildOpts)
1798 streamingPlaylist.VideoFiles = []
1800 videoModel.VideoStreamingPlaylists.push(streamingPlaylist)
1802 videoStreamingPlaylistMemo[streamingPlaylist.id] = streamingPlaylist
1805 if (row.VideoStreamingPlaylists?.VideoFiles?.id && !videoFilesDone.has(row.VideoStreamingPlaylists.VideoFiles.id)) {
1806 const streamingPlaylist = videoStreamingPlaylistMemo[row.VideoStreamingPlaylists.id]
1808 const videoFileModel = new VideoFileModel(pick(row.VideoStreamingPlaylists.VideoFiles, videoFileKeys), buildOpts)
1809 streamingPlaylist.VideoFiles.push(videoFileModel)
1811 videoFilesDone.add(row.VideoStreamingPlaylists.VideoFiles.id)
1818 static getCategoryLabel (id: number) {
1819 return VIDEO_CATEGORIES[id] || 'Misc'
1822 static getLicenceLabel (id: number) {
1823 return VIDEO_LICENCES[id] || 'Unknown'
1826 static getLanguageLabel (id: string) {
1827 return VIDEO_LANGUAGES[id] || 'Unknown'
1830 static getPrivacyLabel (id: number) {
1831 return VIDEO_PRIVACIES[id] || 'Unknown'
1834 static getStateLabel (id: number) {
1835 return VIDEO_STATES[id] || 'Unknown'
1839 return !!this.VideoBlacklist
1843 return this.VideoChannel.Account.Actor.Server?.isBlocked() || this.VideoChannel.Account.isBlocked()
1846 getQualityFileBy<T extends MVideoWithFile> (this: T, fun: (files: MVideoFile[], it: (file: MVideoFile) => number) => MVideoFile) {
1847 // We first transcode to WebTorrent format, so try this array first
1848 if (Array.isArray(this.VideoFiles) && this.VideoFiles.length !== 0) {
1849 const file = fun(this.VideoFiles, file => file.resolution)
1851 return Object.assign(file, { Video: this })
1854 // No webtorrent files, try with streaming playlist files
1855 if (Array.isArray(this.VideoStreamingPlaylists) && this.VideoStreamingPlaylists.length !== 0) {
1856 const streamingPlaylistWithVideo = Object.assign(this.VideoStreamingPlaylists[0], { Video: this })
1858 const file = fun(streamingPlaylistWithVideo.VideoFiles, file => file.resolution)
1859 return Object.assign(file, { VideoStreamingPlaylist: streamingPlaylistWithVideo })
1865 getMaxQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1866 return this.getQualityFileBy(maxBy)
1869 getMinQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1870 return this.getQualityFileBy(minBy)
1873 getWebTorrentFile<T extends MVideoWithFile> (this: T, resolution: number): MVideoFileVideo {
1874 if (Array.isArray(this.VideoFiles) === false) return undefined
1876 const file = this.VideoFiles.find(f => f.resolution === resolution)
1877 if (!file) return undefined
1879 return Object.assign(file, { Video: this })
1882 hasWebTorrentFiles () {
1883 return Array.isArray(this.VideoFiles) === true && this.VideoFiles.length !== 0
1886 async addAndSaveThumbnail (thumbnail: MThumbnail, transaction: Transaction) {
1887 thumbnail.videoId = this.id
1889 const savedThumbnail = await thumbnail.save({ transaction })
1891 if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = []
1893 // Already have this thumbnail, skip
1894 if (this.Thumbnails.find(t => t.id === savedThumbnail.id)) return
1896 this.Thumbnails.push(savedThumbnail)
1900 if (Array.isArray(this.Thumbnails) === false) return undefined
1902 return this.Thumbnails.find(t => t.type === ThumbnailType.MINIATURE)
1906 return !!this.getPreview()
1910 if (Array.isArray(this.Thumbnails) === false) return undefined
1912 return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW)
1916 return this.remote === false
1919 getWatchStaticPath () {
1920 return '/videos/watch/' + this.uuid
1923 getEmbedStaticPath () {
1924 return '/videos/embed/' + this.uuid
1927 getMiniatureStaticPath () {
1928 const thumbnail = this.getMiniature()
1929 if (!thumbnail) return null
1931 return join(STATIC_PATHS.THUMBNAILS, thumbnail.filename)
1934 getPreviewStaticPath () {
1935 const preview = this.getPreview()
1936 if (!preview) return null
1938 // We use a local cache, so specify our cache endpoint instead of potential remote URL
1939 return join(LAZY_STATIC_PATHS.PREVIEWS, preview.filename)
1942 toFormattedJSON (this: MVideoFormattable, options?: VideoFormattingJSONOptions): Video {
1943 return videoModelToFormattedJSON(this, options)
1946 toFormattedDetailsJSON (this: MVideoFormattableDetails): VideoDetails {
1947 return videoModelToFormattedDetailsJSON(this)
1950 getFormattedVideoFilesJSON (includeMagnet = true): VideoFile[] {
1951 let files: VideoFile[] = []
1953 if (Array.isArray(this.VideoFiles)) {
1954 const result = videoFilesModelToFormattedJSON(this, this.VideoFiles, includeMagnet)
1955 files = files.concat(result)
1958 for (const p of (this.VideoStreamingPlaylists || [])) {
1959 const result = videoFilesModelToFormattedJSON(this, p.VideoFiles, includeMagnet)
1960 files = files.concat(result)
1966 toActivityPubObject (this: MVideoAP): VideoObject {
1967 return videoModelToActivityPubObject(this)
1970 getTruncatedDescription () {
1971 if (!this.description) return null
1973 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1974 return peertubeTruncate(this.description, { length: maxLength })
1977 getMaxQualityResolution () {
1978 const file = this.getMaxQualityFile()
1979 const videoOrPlaylist = file.getVideoOrStreamingPlaylist()
1980 const originalFilePath = getVideoFilePath(videoOrPlaylist, file)
1982 return getVideoFileResolution(originalFilePath)
1985 getDescriptionAPIPath () {
1986 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1989 getHLSPlaylist (): MStreamingPlaylistFilesVideo {
1990 if (!this.VideoStreamingPlaylists) return undefined
1992 const playlist = this.VideoStreamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
1993 playlist.Video = this
1998 setHLSPlaylist (playlist: MStreamingPlaylist) {
1999 const toAdd = [ playlist ] as [ VideoStreamingPlaylistModel ]
2001 if (Array.isArray(this.VideoStreamingPlaylists) === false || this.VideoStreamingPlaylists.length === 0) {
2002 this.VideoStreamingPlaylists = toAdd
2006 this.VideoStreamingPlaylists = this.VideoStreamingPlaylists
2007 .filter(s => s.type !== VideoStreamingPlaylistType.HLS)
2011 removeFile (videoFile: MVideoFile, isRedundancy = false) {
2012 const filePath = getVideoFilePath(this, videoFile, isRedundancy)
2013 return remove(filePath)
2014 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
2017 async removeStreamingPlaylistFiles (streamingPlaylist: MStreamingPlaylist, isRedundancy = false) {
2018 const directoryPath = getHLSDirectory(this, isRedundancy)
2020 await remove(directoryPath)
2022 if (isRedundancy !== true) {
2023 const streamingPlaylistWithFiles = streamingPlaylist as MStreamingPlaylistFilesVideo
2024 streamingPlaylistWithFiles.Video = this
2026 if (!Array.isArray(streamingPlaylistWithFiles.VideoFiles)) {
2027 streamingPlaylistWithFiles.VideoFiles = await streamingPlaylistWithFiles.$get('VideoFiles')
2030 // Remove physical files and torrents
2032 streamingPlaylistWithFiles.VideoFiles.map(file => file.removeTorrent())
2038 if (this.isOwned()) return false
2040 return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)
2043 hasPrivacyForFederation () {
2044 return isPrivacyForFederation(this.privacy)
2047 hasStateForFederation () {
2048 return isStateForFederation(this.state)
2051 isNewVideo (newPrivacy: VideoPrivacy) {
2052 return this.hasPrivacyForFederation() === false && isPrivacyForFederation(newPrivacy) === true
2057 where: { id: this.id }
2060 return VideoModel.update({ updatedAt: new Date() }, options)
2064 return this.privacy === VideoPrivacy.PRIVATE || this.privacy === VideoPrivacy.INTERNAL || !!this.VideoBlacklist
2067 setPrivacy (newPrivacy: VideoPrivacy) {
2068 if (this.privacy === VideoPrivacy.PRIVATE && newPrivacy !== VideoPrivacy.PRIVATE) {
2069 this.publishedAt = new Date()
2072 this.privacy = newPrivacy
2076 return this.privacy === VideoPrivacy.PRIVATE ||
2077 this.privacy === VideoPrivacy.UNLISTED ||
2078 this.privacy === VideoPrivacy.INTERNAL
2081 async publishIfNeededAndSave (t: Transaction) {
2082 if (this.state !== VideoState.PUBLISHED) {
2083 this.state = VideoState.PUBLISHED
2084 this.publishedAt = new Date()
2085 await this.save({ transaction: t })
2093 getBandwidthBits (videoFile: MVideoFile) {
2094 return Math.ceil((videoFile.size * 8) / this.duration)
2098 if (this.isOwned()) {
2100 WEBSERVER.URL + '/tracker/announce',
2101 WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT + '/tracker/socket'
2105 return this.Trackers.map(t => t.url)