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 { v4 as uuidv4 } from 'uuid'
28 import { buildNSFWFilter } from '@server/helpers/express-utils'
29 import { getPrivaciesForFederation, isPrivacyForFederation, isStateForFederation } from '@server/helpers/video'
30 import { LiveManager } from '@server/lib/live-manager'
31 import { getHLSDirectory, getVideoFilePath } from '@server/lib/video-paths'
32 import { getServerActor } from '@server/models/application/application'
33 import { ModelCache } from '@server/models/model-cache'
34 import { VideoFile } from '@shared/models/videos/video-file.model'
35 import { ResultList, UserRight, VideoPrivacy, VideoState } from '../../../shared'
36 import { VideoObject } from '../../../shared/models/activitypub/objects'
37 import { Video, VideoDetails } from '../../../shared/models/videos'
38 import { ThumbnailType } from '../../../shared/models/videos/thumbnail.type'
39 import { VideoFilter } from '../../../shared/models/videos/video-query.type'
40 import { VideoStreamingPlaylistType } from '../../../shared/models/videos/video-streaming-playlist.type'
41 import { peertubeTruncate } from '../../helpers/core-utils'
42 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
43 import { isBooleanValid } from '../../helpers/custom-validators/misc'
46 isVideoDescriptionValid,
54 } from '../../helpers/custom-validators/videos'
55 import { getVideoFileResolution } from '../../helpers/ffprobe-utils'
56 import { logger } from '../../helpers/logger'
57 import { CONFIG } from '../../initializers/config'
70 } from '../../initializers/constants'
71 import { sendDeleteVideo } from '../../lib/activitypub/send'
74 MChannelAccountDefault,
77 MStreamingPlaylistFilesVideo,
82 MVideoAccountLightBlacklistAllFiles,
87 MVideoFormattableDetails,
93 MVideoThumbnailBlacklist,
97 } from '../../types/models'
98 import { MThumbnail } from '../../types/models/video/thumbnail'
99 import { MVideoFile, 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 { UserModel } from '../account/user'
104 import { UserVideoHistoryModel } from '../account/user-video-history'
105 import { ActorModel } from '../activitypub/actor'
106 import { AvatarModel } from '../avatar/avatar'
107 import { VideoRedundancyModel } from '../redundancy/video-redundancy'
108 import { ServerModel } from '../server/server'
109 import { TrackerModel } from '../server/tracker'
110 import { VideoTrackerModel } from '../server/video-tracker'
111 import { buildTrigramSearchIndex, buildWhereIdOrUUID, getVideoSort, isOutdated, throwIfNotValid } from '../utils'
112 import { ScheduleVideoUpdateModel } from './schedule-video-update'
113 import { TagModel } from './tag'
114 import { ThumbnailModel } from './thumbnail'
115 import { VideoBlacklistModel } from './video-blacklist'
116 import { VideoCaptionModel } from './video-caption'
117 import { ScopeNames as VideoChannelScopeNames, SummaryOptions, VideoChannelModel } from './video-channel'
118 import { VideoCommentModel } from './video-comment'
119 import { VideoFileModel } from './video-file'
121 videoFilesModelToFormattedJSON,
122 VideoFormattingJSONOptions,
123 videoModelToActivityPubObject,
124 videoModelToFormattedDetailsJSON,
125 videoModelToFormattedJSON
126 } from './video-format-utils'
127 import { VideoImportModel } from './video-import'
128 import { VideoLiveModel } from './video-live'
129 import { VideoPlaylistElementModel } from './video-playlist-element'
130 import { buildListQuery, BuildVideosQueryOptions, wrapForAPIResults } from './video-query-builder'
131 import { VideoShareModel } from './video-share'
132 import { VideoStreamingPlaylistModel } from './video-streaming-playlist'
133 import { VideoTagModel } from './video-tag'
134 import { VideoViewModel } from './video-view'
136 export enum ScopeNames {
137 AVAILABLE_FOR_LIST_IDS = 'AVAILABLE_FOR_LIST_IDS',
139 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
140 WITH_TAGS = 'WITH_TAGS',
141 WITH_TRACKERS = 'WITH_TRACKERS',
142 WITH_WEBTORRENT_FILES = 'WITH_WEBTORRENT_FILES',
143 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
144 WITH_BLACKLISTED = 'WITH_BLACKLISTED',
145 WITH_USER_HISTORY = 'WITH_USER_HISTORY',
146 WITH_STREAMING_PLAYLISTS = 'WITH_STREAMING_PLAYLISTS',
147 WITH_USER_ID = 'WITH_USER_ID',
148 WITH_IMMUTABLE_ATTRIBUTES = 'WITH_IMMUTABLE_ATTRIBUTES',
149 WITH_THUMBNAILS = 'WITH_THUMBNAILS',
150 WITH_LIVE = 'WITH_LIVE'
153 export type ForAPIOptions = {
156 videoPlaylistId?: number
158 withAccountBlockerIds?: number[]
161 export type AvailableForListIDsOptions = {
162 serverAccountId: number
163 followerActorId: number
164 includeLocalVideos: boolean
166 attributesType?: 'none' | 'id' | 'all'
169 categoryOneOf?: number[]
171 licenceOneOf?: number[]
172 languageOneOf?: string[]
179 videoChannelId?: number
181 videoPlaylistId?: number
183 trendingDays?: number
184 user?: MUserAccountId
185 historyOfUser?: MUserId
187 baseWhere?: WhereOptions[]
191 [ScopeNames.WITH_IMMUTABLE_ATTRIBUTES]: {
192 attributes: [ 'id', 'url', 'uuid', 'remote' ]
194 [ScopeNames.FOR_API]: (options: ForAPIOptions) => {
195 const include: Includeable[] = [
197 model: VideoChannelModel.scope({
199 VideoChannelScopeNames.SUMMARY, {
201 withAccountBlockerIds: options.withAccountBlockerIds
208 attributes: [ 'type', 'filename' ],
209 model: ThumbnailModel,
214 const query: FindOptions = {}
224 if (options.videoPlaylistId) {
226 model: VideoPlaylistElementModel.unscoped(),
229 videoPlaylistId: options.videoPlaylistId
234 query.include = include
238 [ScopeNames.WITH_THUMBNAILS]: {
241 model: ThumbnailModel,
246 [ScopeNames.WITH_LIVE]: {
249 model: VideoLiveModel.unscoped(),
254 [ScopeNames.WITH_USER_ID]: {
257 attributes: [ 'accountId' ],
258 model: VideoChannelModel.unscoped(),
262 attributes: [ 'userId' ],
263 model: AccountModel.unscoped(),
270 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
273 model: VideoChannelModel.unscoped(),
278 exclude: [ 'privateKey', 'publicKey' ]
280 model: ActorModel.unscoped(),
284 attributes: [ 'host' ],
285 model: ServerModel.unscoped(),
289 model: AvatarModel.unscoped(),
295 model: AccountModel.unscoped(),
299 model: ActorModel.unscoped(),
301 exclude: [ 'privateKey', 'publicKey' ]
306 attributes: [ 'host' ],
307 model: ServerModel.unscoped(),
311 model: AvatarModel.unscoped(),
322 [ScopeNames.WITH_TAGS]: {
323 include: [ TagModel ]
325 [ScopeNames.WITH_TRACKERS]: {
328 attributes: [ 'id', 'url' ],
333 [ScopeNames.WITH_BLACKLISTED]: {
336 attributes: [ 'id', 'reason', 'unfederated' ],
337 model: VideoBlacklistModel,
342 [ScopeNames.WITH_WEBTORRENT_FILES]: (withRedundancies = false) => {
343 let subInclude: any[] = []
345 if (withRedundancies === true) {
348 attributes: [ 'fileUrl' ],
349 model: VideoRedundancyModel.unscoped(),
358 model: VideoFileModel,
365 [ScopeNames.WITH_STREAMING_PLAYLISTS]: (withRedundancies = false) => {
366 const subInclude: IncludeOptions[] = [
368 model: VideoFileModel,
373 if (withRedundancies === true) {
375 attributes: [ 'fileUrl' ],
376 model: VideoRedundancyModel.unscoped(),
384 model: VideoStreamingPlaylistModel.unscoped(),
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 @BelongsToMany(() => TrackerModel, {
630 foreignKey: 'videoId',
631 through: () => VideoTrackerModel,
634 Trackers: TrackerModel[]
636 @HasMany(() => ThumbnailModel, {
644 Thumbnails: ThumbnailModel[]
646 @HasMany(() => VideoPlaylistElementModel, {
653 VideoPlaylistElements: VideoPlaylistElementModel[]
655 @HasMany(() => VideoAbuseModel, {
662 VideoAbuses: VideoAbuseModel[]
664 @HasMany(() => VideoFileModel, {
672 VideoFiles: VideoFileModel[]
674 @HasMany(() => VideoStreamingPlaylistModel, {
682 VideoStreamingPlaylists: VideoStreamingPlaylistModel[]
684 @HasMany(() => VideoShareModel, {
691 VideoShares: VideoShareModel[]
693 @HasMany(() => AccountVideoRateModel, {
700 AccountVideoRates: AccountVideoRateModel[]
702 @HasMany(() => VideoCommentModel, {
710 VideoComments: VideoCommentModel[]
712 @HasMany(() => VideoViewModel, {
719 VideoViews: VideoViewModel[]
721 @HasMany(() => UserVideoHistoryModel, {
728 UserVideoHistories: UserVideoHistoryModel[]
730 @HasOne(() => ScheduleVideoUpdateModel, {
737 ScheduleVideoUpdate: ScheduleVideoUpdateModel
739 @HasOne(() => VideoBlacklistModel, {
746 VideoBlacklist: VideoBlacklistModel
748 @HasOne(() => VideoLiveModel, {
755 VideoLive: VideoLiveModel
757 @HasOne(() => VideoImportModel, {
764 VideoImport: VideoImportModel
766 @HasMany(() => VideoCaptionModel, {
773 ['separate' as any]: true
775 VideoCaptions: VideoCaptionModel[]
778 static async sendDelete (instance: MVideoAccountLight, options) {
779 if (instance.isOwned()) {
780 if (!instance.VideoChannel) {
781 instance.VideoChannel = await instance.$get('VideoChannel', {
786 transaction: options.transaction
787 }) as MChannelAccountDefault
790 return sendDeleteVideo(instance, options.transaction)
797 static async removeFiles (instance: VideoModel) {
798 const tasks: Promise<any>[] = []
800 logger.info('Removing files of video %s.', instance.url)
802 if (instance.isOwned()) {
803 if (!Array.isArray(instance.VideoFiles)) {
804 instance.VideoFiles = await instance.$get('VideoFiles')
807 // Remove physical files and torrents
808 instance.VideoFiles.forEach(file => {
809 tasks.push(instance.removeFile(file))
810 tasks.push(file.removeTorrent())
813 // Remove playlists file
814 if (!Array.isArray(instance.VideoStreamingPlaylists)) {
815 instance.VideoStreamingPlaylists = await instance.$get('VideoStreamingPlaylists')
818 for (const p of instance.VideoStreamingPlaylists) {
819 tasks.push(instance.removeStreamingPlaylistFiles(p))
823 // Do not wait video deletion because we could be in a transaction
826 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
833 static stopLiveIfNeeded (instance: VideoModel) {
834 if (!instance.isLive) return
836 logger.info('Stopping live of video %s after video deletion.', instance.uuid)
838 return LiveManager.Instance.stopSessionOf(instance.id)
842 static invalidateCache (instance: VideoModel) {
843 ModelCache.Instance.invalidateCache('video', instance.id)
847 static async saveEssentialDataToAbuses (instance: VideoModel, options) {
848 const tasks: Promise<any>[] = []
850 if (!Array.isArray(instance.VideoAbuses)) {
851 instance.VideoAbuses = await instance.$get('VideoAbuses')
853 if (instance.VideoAbuses.length === 0) return undefined
856 logger.info('Saving video abuses details of video %s.', instance.url)
858 const details = instance.toFormattedDetailsJSON()
860 for (const abuse of instance.VideoAbuses) {
861 abuse.deletedVideo = details
862 tasks.push(abuse.save({ transaction: options.transaction }))
867 logger.error('Some errors when saving details of video %s in its abuses before destroy hook.', instance.uuid, { err })
873 static listLocal (): Promise<MVideo[]> {
880 return VideoModel.findAll(query)
883 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
884 function getRawQuery (select: string) {
885 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
886 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
887 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
888 'WHERE "Account"."actorId" = ' + actorId
889 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
890 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
891 'WHERE "VideoShare"."actorId" = ' + actorId
893 return `(${queryVideo}) UNION (${queryVideoShare})`
896 const rawQuery = getRawQuery('"Video"."id"')
897 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
903 order: getVideoSort('-createdAt', [ 'Tags', 'name', 'ASC' ] as any), // FIXME: sequelize typings
906 [Op.in]: Sequelize.literal('(' + rawQuery + ')')
908 [Op.or]: getPrivaciesForFederation()
912 attributes: [ 'language', 'fileUrl' ],
913 model: VideoCaptionModel.unscoped(),
917 attributes: [ 'id', 'url' ],
918 model: VideoShareModel.unscoped(),
920 // We only want videos shared by this actor
935 attributes: [ 'id', 'url' ],
936 model: ActorModel.unscoped()
941 model: VideoChannelModel.unscoped(),
945 attributes: [ 'name' ],
946 model: AccountModel.unscoped(),
950 attributes: [ 'id', 'url', 'followersUrl' ],
951 model: ActorModel.unscoped(),
957 attributes: [ 'id', 'url', 'followersUrl' ],
958 model: ActorModel.unscoped(),
964 model: VideoStreamingPlaylistModel.unscoped(),
968 model: VideoFileModel,
973 VideoLiveModel.unscoped(),
979 return Bluebird.all([
980 VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findAll(query),
981 VideoModel.sequelize.query<{ total: string }>(rawCountQuery, { type: QueryTypes.SELECT })
982 ]).then(([ rows, totals ]) => {
983 // totals: totalVideos + totalVideoShares
985 let totalVideoShares = 0
986 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
987 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
989 const total = totalVideos + totalVideoShares
997 static async listPublishedLiveIds () {
999 attributes: [ 'id' ],
1002 state: VideoState.PUBLISHED
1006 const result = await VideoModel.findAll(options)
1008 return result.map(v => v.id)
1011 static listUserVideosForApi (options: {
1018 const { accountId, start, count, sort, search } = options
1020 function buildBaseQuery (): FindOptions {
1024 order: getVideoSort(sort),
1027 model: VideoChannelModel,
1031 model: AccountModel,
1043 baseQuery = Object.assign(baseQuery, {
1046 [Op.iLike]: '%' + search + '%'
1055 const countQuery = buildBaseQuery()
1056 const findQuery = buildBaseQuery()
1058 const findScopes: (string | ScopeOptions)[] = [
1059 ScopeNames.WITH_SCHEDULED_UPDATE,
1060 ScopeNames.WITH_BLACKLISTED,
1061 ScopeNames.WITH_THUMBNAILS
1064 return Promise.all([
1065 VideoModel.count(countQuery),
1066 VideoModel.scope(findScopes).findAll<MVideoForUser>(findQuery)
1067 ]).then(([ count, rows ]) => {
1075 static async listForApi (options: {
1080 includeLocalVideos: boolean
1082 categoryOneOf?: number[]
1083 licenceOneOf?: number[]
1084 languageOneOf?: string[]
1085 tagsOneOf?: string[]
1086 tagsAllOf?: string[]
1087 filter?: VideoFilter
1089 videoChannelId?: number
1090 followerActorId?: number
1091 videoPlaylistId?: number
1092 trendingDays?: number
1093 user?: MUserAccountId
1094 historyOfUser?: MUserId
1095 countVideos?: boolean
1098 if ((options.filter === 'all-local' || options.filter === 'all') && !options.user.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1099 throw new Error('Try to filter all-local but no user has not the see all videos right')
1102 const trendingDays = options.sort.endsWith('trending')
1103 ? CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1105 let trendingAlgorithm
1106 if (options.sort.endsWith('hot')) trendingAlgorithm = 'hot'
1107 if (options.sort.endsWith('best')) trendingAlgorithm = 'best'
1109 const serverActor = await getServerActor()
1111 // followerActorId === null has a meaning, so just check undefined
1112 const followerActorId = options.followerActorId !== undefined
1113 ? options.followerActorId
1116 const queryOptions = {
1117 start: options.start,
1118 count: options.count,
1121 serverAccountId: serverActor.Account.id,
1123 categoryOneOf: options.categoryOneOf,
1124 licenceOneOf: options.licenceOneOf,
1125 languageOneOf: options.languageOneOf,
1126 tagsOneOf: options.tagsOneOf,
1127 tagsAllOf: options.tagsAllOf,
1128 filter: options.filter,
1129 withFiles: options.withFiles,
1130 accountId: options.accountId,
1131 videoChannelId: options.videoChannelId,
1132 videoPlaylistId: options.videoPlaylistId,
1133 includeLocalVideos: options.includeLocalVideos,
1135 historyOfUser: options.historyOfUser,
1138 search: options.search
1141 return VideoModel.getAvailableForApi(queryOptions, options.countVideos)
1144 static async searchAndPopulateAccountAndServer (options: {
1145 includeLocalVideos: boolean
1150 startDate?: string // ISO 8601
1151 endDate?: string // ISO 8601
1152 originallyPublishedStartDate?: string
1153 originallyPublishedEndDate?: string
1155 categoryOneOf?: number[]
1156 licenceOneOf?: number[]
1157 languageOneOf?: string[]
1158 tagsOneOf?: string[]
1159 tagsAllOf?: string[]
1160 durationMin?: number // seconds
1161 durationMax?: number // seconds
1162 user?: MUserAccountId
1163 filter?: VideoFilter
1165 const serverActor = await getServerActor()
1166 const queryOptions = {
1167 followerActorId: serverActor.id,
1168 serverAccountId: serverActor.Account.id,
1169 includeLocalVideos: options.includeLocalVideos,
1171 categoryOneOf: options.categoryOneOf,
1172 licenceOneOf: options.licenceOneOf,
1173 languageOneOf: options.languageOneOf,
1174 tagsOneOf: options.tagsOneOf,
1175 tagsAllOf: options.tagsAllOf,
1177 filter: options.filter,
1178 start: options.start,
1179 count: options.count,
1181 startDate: options.startDate,
1182 endDate: options.endDate,
1183 originallyPublishedStartDate: options.originallyPublishedStartDate,
1184 originallyPublishedEndDate: options.originallyPublishedEndDate,
1186 durationMin: options.durationMin,
1187 durationMax: options.durationMax,
1189 search: options.search
1192 return VideoModel.getAvailableForApi(queryOptions)
1195 static countLocalLives () {
1201 [Op.ne]: VideoState.LIVE_ENDED
1206 return VideoModel.count(options)
1209 static countVideosUploadedByUserSince (userId: number, since: Date) {
1213 model: VideoChannelModel.unscoped(),
1217 model: AccountModel.unscoped(),
1221 model: UserModel.unscoped(),
1239 return VideoModel.unscoped().count(options)
1242 static countLivesOfAccount (accountId: number) {
1248 [Op.ne]: VideoState.LIVE_ENDED
1254 model: VideoChannelModel.unscoped(),
1262 return VideoModel.count(options)
1265 static load (id: number | string, t?: Transaction): Promise<MVideoThumbnail> {
1266 const where = buildWhereIdOrUUID(id)
1272 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1275 static loadWithBlacklist (id: number | string, t?: Transaction): Promise<MVideoThumbnailBlacklist> {
1276 const where = buildWhereIdOrUUID(id)
1282 return VideoModel.scope([
1283 ScopeNames.WITH_THUMBNAILS,
1284 ScopeNames.WITH_BLACKLISTED
1288 static loadImmutableAttributes (id: number | string, t?: Transaction): Promise<MVideoImmutable> {
1291 where: buildWhereIdOrUUID(id),
1295 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1298 return ModelCache.Instance.doCache({
1299 cacheType: 'load-video-immutable-id',
1306 static loadWithRights (id: number | string, t?: Transaction): Promise<MVideoWithRights> {
1307 const where = buildWhereIdOrUUID(id)
1313 return VideoModel.scope([
1314 ScopeNames.WITH_BLACKLISTED,
1315 ScopeNames.WITH_USER_ID,
1316 ScopeNames.WITH_THUMBNAILS
1320 static loadOnlyId (id: number | string, t?: Transaction): Promise<MVideoIdThumbnail> {
1321 const where = buildWhereIdOrUUID(id)
1324 attributes: [ 'id' ],
1329 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1332 static loadWithFiles (id: number | string, t?: Transaction, logging?: boolean): Promise<MVideoWithAllFiles> {
1333 const where = buildWhereIdOrUUID(id)
1341 return VideoModel.scope([
1342 ScopeNames.WITH_WEBTORRENT_FILES,
1343 ScopeNames.WITH_STREAMING_PLAYLISTS,
1344 ScopeNames.WITH_THUMBNAILS
1348 static loadByUUID (uuid: string): Promise<MVideoThumbnail> {
1355 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1358 static loadByUrl (url: string, transaction?: Transaction): Promise<MVideoThumbnail> {
1359 const query: FindOptions = {
1366 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(query)
1369 static loadByUrlImmutableAttributes (url: string, transaction?: Transaction): Promise<MVideoImmutable> {
1371 const query: FindOptions = {
1378 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1381 return ModelCache.Instance.doCache({
1382 cacheType: 'load-video-immutable-url',
1389 static loadByUrlAndPopulateAccount (url: string, transaction?: Transaction): Promise<MVideoAccountLightBlacklistAllFiles> {
1390 const query: FindOptions = {
1397 return VideoModel.scope([
1398 ScopeNames.WITH_ACCOUNT_DETAILS,
1399 ScopeNames.WITH_WEBTORRENT_FILES,
1400 ScopeNames.WITH_STREAMING_PLAYLISTS,
1401 ScopeNames.WITH_THUMBNAILS,
1402 ScopeNames.WITH_BLACKLISTED
1406 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Transaction, userId?: number): Promise<MVideoFullLight> {
1407 const where = buildWhereIdOrUUID(id)
1410 order: [ [ 'Tags', 'name', 'ASC' ] ] as any,
1415 const scopes: (string | ScopeOptions)[] = [
1416 ScopeNames.WITH_TAGS,
1417 ScopeNames.WITH_BLACKLISTED,
1418 ScopeNames.WITH_ACCOUNT_DETAILS,
1419 ScopeNames.WITH_SCHEDULED_UPDATE,
1420 ScopeNames.WITH_WEBTORRENT_FILES,
1421 ScopeNames.WITH_STREAMING_PLAYLISTS,
1422 ScopeNames.WITH_THUMBNAILS,
1423 ScopeNames.WITH_LIVE
1427 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1435 static loadForGetAPI (parameters: {
1439 }): Promise<MVideoDetails> {
1440 const { id, t, userId } = parameters
1441 const where = buildWhereIdOrUUID(id)
1444 order: [ [ 'Tags', 'name', 'ASC' ] ] as any, // FIXME: sequelize typings
1449 const scopes: (string | ScopeOptions)[] = [
1450 ScopeNames.WITH_TAGS,
1451 ScopeNames.WITH_BLACKLISTED,
1452 ScopeNames.WITH_ACCOUNT_DETAILS,
1453 ScopeNames.WITH_SCHEDULED_UPDATE,
1454 ScopeNames.WITH_THUMBNAILS,
1455 ScopeNames.WITH_LIVE,
1456 ScopeNames.WITH_TRACKERS,
1457 { method: [ ScopeNames.WITH_WEBTORRENT_FILES, true ] },
1458 { method: [ ScopeNames.WITH_STREAMING_PLAYLISTS, true ] }
1462 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1470 static async getStats () {
1471 const totalLocalVideos = await VideoModel.count({
1477 let totalLocalVideoViews = await VideoModel.sum('views', {
1483 // Sequelize could return null...
1484 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1486 const { total: totalVideos } = await VideoModel.listForApi({
1489 sort: '-publishedAt',
1490 nsfw: buildNSFWFilter(),
1491 includeLocalVideos: true,
1497 totalLocalVideoViews,
1502 static incrementViews (id: number, views: number) {
1503 return VideoModel.increment('views', {
1511 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1512 // Instances only share videos
1513 const query = 'SELECT 1 FROM "videoShare" ' +
1514 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1515 'WHERE "actorFollow"."actorId" = $followerActorId AND "actorFollow"."state" = \'accepted\' AND "videoShare"."videoId" = $videoId ' +
1519 type: QueryTypes.SELECT as QueryTypes.SELECT,
1520 bind: { followerActorId, videoId },
1524 return VideoModel.sequelize.query(query, options)
1525 .then(results => results.length === 1)
1528 static bulkUpdateSupportField (videoChannel: MChannel, t: Transaction) {
1531 channelId: videoChannel.id
1536 return VideoModel.update({ support: videoChannel.support }, options)
1539 static getAllIdsFromChannel (videoChannel: MChannelId): Promise<number[]> {
1541 attributes: [ 'id' ],
1543 channelId: videoChannel.id
1547 return VideoModel.findAll(query)
1548 .then(videos => videos.map(v => v.id))
1551 // threshold corresponds to how many video the field should have to be returned
1552 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1553 const serverActor = await getServerActor()
1554 const followerActorId = serverActor.id
1556 const queryOptions: BuildVideosQueryOptions = {
1557 attributes: [ `"${field}"` ],
1558 group: `GROUP BY "${field}"`,
1559 having: `HAVING COUNT("${field}") >= ${threshold}`,
1563 serverAccountId: serverActor.Account.id,
1565 includeLocalVideos: true
1568 const { query, replacements } = buildListQuery(VideoModel, queryOptions)
1570 return this.sequelize.query<any>(query, { replacements, type: QueryTypes.SELECT })
1571 .then(rows => rows.map(r => r[field]))
1574 static buildTrendingQuery (trendingDays: number) {
1578 model: VideoViewModel,
1582 [Op.gte]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1588 private static async getAvailableForApi (
1589 options: BuildVideosQueryOptions,
1591 ): Promise<ResultList<VideoModel>> {
1592 function getCount () {
1593 if (countVideos !== true) return Promise.resolve(undefined)
1595 const countOptions = Object.assign({}, options, { isCount: true })
1596 const { query: queryCount, replacements: replacementsCount } = buildListQuery(VideoModel, countOptions)
1598 return VideoModel.sequelize.query<any>(queryCount, { replacements: replacementsCount, type: QueryTypes.SELECT })
1599 .then(rows => rows.length !== 0 ? rows[0].total : 0)
1602 function getModels () {
1603 if (options.count === 0) return Promise.resolve([])
1605 const { query, replacements, order } = buildListQuery(VideoModel, options)
1606 const queryModels = wrapForAPIResults(query, replacements, options, order)
1608 return VideoModel.sequelize.query<any>(queryModels, { replacements, type: QueryTypes.SELECT, nest: true })
1609 .then(rows => VideoModel.buildAPIResult(rows))
1612 const [ count, rows ] = await Promise.all([ getCount(), getModels() ])
1620 private static buildAPIResult (rows: any[]) {
1621 const videosMemo: { [ id: number ]: VideoModel } = {}
1622 const videoStreamingPlaylistMemo: { [ id: number ]: VideoStreamingPlaylistModel } = {}
1624 const thumbnailsDone = new Set<number>()
1625 const historyDone = new Set<number>()
1626 const videoFilesDone = new Set<number>()
1628 const videos: VideoModel[] = []
1630 const avatarKeys = [ 'id', 'filename', 'fileUrl', 'onDisk', 'createdAt', 'updatedAt' ]
1631 const actorKeys = [ 'id', 'preferredUsername', 'url', 'serverId', 'avatarId' ]
1632 const serverKeys = [ 'id', 'host' ]
1633 const videoFileKeys = [
1647 'videoStreamingPlaylistId'
1649 const videoStreamingPlaylistKeys = [ 'id', 'type', 'playlistUrl' ]
1673 'originallyPublishedAt',
1678 const buildOpts = { raw: true }
1680 function buildActor (rowActor: any) {
1681 const avatarModel = rowActor.Avatar.id !== null
1682 ? new AvatarModel(pick(rowActor.Avatar, avatarKeys), buildOpts)
1685 const serverModel = rowActor.Server.id !== null
1686 ? new ServerModel(pick(rowActor.Server, serverKeys), buildOpts)
1689 const actorModel = new ActorModel(pick(rowActor, actorKeys), buildOpts)
1690 actorModel.Avatar = avatarModel
1691 actorModel.Server = serverModel
1696 for (const row of rows) {
1697 if (!videosMemo[row.id]) {
1699 const channel = row.VideoChannel
1700 const channelModel = new VideoChannelModel(pick(channel, [ 'id', 'name', 'description', 'actorId' ]), buildOpts)
1701 channelModel.Actor = buildActor(channel.Actor)
1703 const account = row.VideoChannel.Account
1704 const accountModel = new AccountModel(pick(account, [ 'id', 'name' ]), buildOpts)
1705 accountModel.Actor = buildActor(account.Actor)
1707 channelModel.Account = accountModel
1709 const videoModel = new VideoModel(pick(row, videoKeys), buildOpts)
1710 videoModel.VideoChannel = channelModel
1712 videoModel.UserVideoHistories = []
1713 videoModel.Thumbnails = []
1714 videoModel.VideoFiles = []
1715 videoModel.VideoStreamingPlaylists = []
1717 videosMemo[row.id] = videoModel
1718 // Don't take object value to have a sorted array
1719 videos.push(videoModel)
1722 const videoModel = videosMemo[row.id]
1724 if (row.userVideoHistory?.id && !historyDone.has(row.userVideoHistory.id)) {
1725 const historyModel = new UserVideoHistoryModel(pick(row.userVideoHistory, [ 'id', 'currentTime' ]), buildOpts)
1726 videoModel.UserVideoHistories.push(historyModel)
1728 historyDone.add(row.userVideoHistory.id)
1731 if (row.Thumbnails?.id && !thumbnailsDone.has(row.Thumbnails.id)) {
1732 const thumbnailModel = new ThumbnailModel(pick(row.Thumbnails, [ 'id', 'type', 'filename' ]), buildOpts)
1733 videoModel.Thumbnails.push(thumbnailModel)
1735 thumbnailsDone.add(row.Thumbnails.id)
1738 if (row.VideoFiles?.id && !videoFilesDone.has(row.VideoFiles.id)) {
1739 const videoFileModel = new VideoFileModel(pick(row.VideoFiles, videoFileKeys), buildOpts)
1740 videoModel.VideoFiles.push(videoFileModel)
1742 videoFilesDone.add(row.VideoFiles.id)
1745 if (row.VideoStreamingPlaylists?.id && !videoStreamingPlaylistMemo[row.VideoStreamingPlaylists.id]) {
1746 const streamingPlaylist = new VideoStreamingPlaylistModel(pick(row.VideoStreamingPlaylists, videoStreamingPlaylistKeys), buildOpts)
1747 streamingPlaylist.VideoFiles = []
1749 videoModel.VideoStreamingPlaylists.push(streamingPlaylist)
1751 videoStreamingPlaylistMemo[streamingPlaylist.id] = streamingPlaylist
1754 if (row.VideoStreamingPlaylists?.VideoFiles?.id && !videoFilesDone.has(row.VideoStreamingPlaylists.VideoFiles.id)) {
1755 const streamingPlaylist = videoStreamingPlaylistMemo[row.VideoStreamingPlaylists.id]
1757 const videoFileModel = new VideoFileModel(pick(row.VideoStreamingPlaylists.VideoFiles, videoFileKeys), buildOpts)
1758 streamingPlaylist.VideoFiles.push(videoFileModel)
1760 videoFilesDone.add(row.VideoStreamingPlaylists.VideoFiles.id)
1767 static getCategoryLabel (id: number) {
1768 return VIDEO_CATEGORIES[id] || 'Misc'
1771 static getLicenceLabel (id: number) {
1772 return VIDEO_LICENCES[id] || 'Unknown'
1775 static getLanguageLabel (id: string) {
1776 return VIDEO_LANGUAGES[id] || 'Unknown'
1779 static getPrivacyLabel (id: number) {
1780 return VIDEO_PRIVACIES[id] || 'Unknown'
1783 static getStateLabel (id: number) {
1784 return VIDEO_STATES[id] || 'Unknown'
1788 return !!this.VideoBlacklist
1792 return this.VideoChannel.Account.Actor.Server?.isBlocked() || this.VideoChannel.Account.isBlocked()
1795 getQualityFileBy<T extends MVideoWithFile> (this: T, fun: (files: MVideoFile[], it: (file: MVideoFile) => number) => MVideoFile) {
1796 // We first transcode to WebTorrent format, so try this array first
1797 if (Array.isArray(this.VideoFiles) && this.VideoFiles.length !== 0) {
1798 const file = fun(this.VideoFiles, file => file.resolution)
1800 return Object.assign(file, { Video: this })
1803 // No webtorrent files, try with streaming playlist files
1804 if (Array.isArray(this.VideoStreamingPlaylists) && this.VideoStreamingPlaylists.length !== 0) {
1805 const streamingPlaylistWithVideo = Object.assign(this.VideoStreamingPlaylists[0], { Video: this })
1807 const file = fun(streamingPlaylistWithVideo.VideoFiles, file => file.resolution)
1808 return Object.assign(file, { VideoStreamingPlaylist: streamingPlaylistWithVideo })
1814 getMaxQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1815 return this.getQualityFileBy(maxBy)
1818 getMinQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1819 return this.getQualityFileBy(minBy)
1822 getWebTorrentFile<T extends MVideoWithFile> (this: T, resolution: number): MVideoFileVideo {
1823 if (Array.isArray(this.VideoFiles) === false) return undefined
1825 const file = this.VideoFiles.find(f => f.resolution === resolution)
1826 if (!file) return undefined
1828 return Object.assign(file, { Video: this })
1831 hasWebTorrentFiles () {
1832 return Array.isArray(this.VideoFiles) === true && this.VideoFiles.length !== 0
1835 async addAndSaveThumbnail (thumbnail: MThumbnail, transaction: Transaction) {
1836 thumbnail.videoId = this.id
1838 const savedThumbnail = await thumbnail.save({ transaction })
1840 if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = []
1842 // Already have this thumbnail, skip
1843 if (this.Thumbnails.find(t => t.id === savedThumbnail.id)) return
1845 this.Thumbnails.push(savedThumbnail)
1848 generateThumbnailName () {
1849 return uuidv4() + '.jpg'
1853 if (Array.isArray(this.Thumbnails) === false) return undefined
1855 return this.Thumbnails.find(t => t.type === ThumbnailType.MINIATURE)
1858 generatePreviewName () {
1859 return uuidv4() + '.jpg'
1863 return !!this.getPreview()
1867 if (Array.isArray(this.Thumbnails) === false) return undefined
1869 return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW)
1873 return this.remote === false
1876 getWatchStaticPath () {
1877 return '/videos/watch/' + this.uuid
1880 getEmbedStaticPath () {
1881 return '/videos/embed/' + this.uuid
1884 getMiniatureStaticPath () {
1885 const thumbnail = this.getMiniature()
1886 if (!thumbnail) return null
1888 return join(STATIC_PATHS.THUMBNAILS, thumbnail.filename)
1891 getPreviewStaticPath () {
1892 const preview = this.getPreview()
1893 if (!preview) return null
1895 // We use a local cache, so specify our cache endpoint instead of potential remote URL
1896 return join(LAZY_STATIC_PATHS.PREVIEWS, preview.filename)
1899 toFormattedJSON (this: MVideoFormattable, options?: VideoFormattingJSONOptions): Video {
1900 return videoModelToFormattedJSON(this, options)
1903 toFormattedDetailsJSON (this: MVideoFormattableDetails): VideoDetails {
1904 return videoModelToFormattedDetailsJSON(this)
1907 getFormattedVideoFilesJSON (): VideoFile[] {
1908 let files: VideoFile[] = []
1910 if (Array.isArray(this.VideoFiles)) {
1911 const result = videoFilesModelToFormattedJSON(this, this.VideoFiles)
1912 files = files.concat(result)
1915 for (const p of (this.VideoStreamingPlaylists || [])) {
1916 const result = videoFilesModelToFormattedJSON(this, p.VideoFiles)
1917 files = files.concat(result)
1923 toActivityPubObject (this: MVideoAP): VideoObject {
1924 return videoModelToActivityPubObject(this)
1927 getTruncatedDescription () {
1928 if (!this.description) return null
1930 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1931 return peertubeTruncate(this.description, { length: maxLength })
1934 getMaxQualityResolution () {
1935 const file = this.getMaxQualityFile()
1936 const videoOrPlaylist = file.getVideoOrStreamingPlaylist()
1937 const originalFilePath = getVideoFilePath(videoOrPlaylist, file)
1939 return getVideoFileResolution(originalFilePath)
1942 getDescriptionAPIPath () {
1943 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1946 getHLSPlaylist (): MStreamingPlaylistFilesVideo {
1947 if (!this.VideoStreamingPlaylists) return undefined
1949 const playlist = this.VideoStreamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
1950 playlist.Video = this
1955 setHLSPlaylist (playlist: MStreamingPlaylist) {
1956 const toAdd = [ playlist ] as [ VideoStreamingPlaylistModel ]
1958 if (Array.isArray(this.VideoStreamingPlaylists) === false || this.VideoStreamingPlaylists.length === 0) {
1959 this.VideoStreamingPlaylists = toAdd
1963 this.VideoStreamingPlaylists = this.VideoStreamingPlaylists
1964 .filter(s => s.type !== VideoStreamingPlaylistType.HLS)
1968 removeFile (videoFile: MVideoFile, isRedundancy = false) {
1969 const filePath = getVideoFilePath(this, videoFile, isRedundancy)
1970 return remove(filePath)
1971 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1974 async removeStreamingPlaylistFiles (streamingPlaylist: MStreamingPlaylist, isRedundancy = false) {
1975 const directoryPath = getHLSDirectory(this, isRedundancy)
1977 await remove(directoryPath)
1979 if (isRedundancy !== true) {
1980 const streamingPlaylistWithFiles = streamingPlaylist as MStreamingPlaylistFilesVideo
1981 streamingPlaylistWithFiles.Video = this
1983 if (!Array.isArray(streamingPlaylistWithFiles.VideoFiles)) {
1984 streamingPlaylistWithFiles.VideoFiles = await streamingPlaylistWithFiles.$get('VideoFiles')
1987 // Remove physical files and torrents
1989 streamingPlaylistWithFiles.VideoFiles.map(file => file.removeTorrent())
1995 if (this.isOwned()) return false
1997 return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)
2000 hasPrivacyForFederation () {
2001 return isPrivacyForFederation(this.privacy)
2004 hasStateForFederation () {
2005 return isStateForFederation(this.state)
2008 isNewVideo (newPrivacy: VideoPrivacy) {
2009 return this.hasPrivacyForFederation() === false && isPrivacyForFederation(newPrivacy) === true
2013 this.changed('updatedAt', true)
2019 return this.privacy === VideoPrivacy.PRIVATE || this.privacy === VideoPrivacy.INTERNAL || !!this.VideoBlacklist
2022 setPrivacy (newPrivacy: VideoPrivacy) {
2023 if (this.privacy === VideoPrivacy.PRIVATE && newPrivacy !== VideoPrivacy.PRIVATE) {
2024 this.publishedAt = new Date()
2027 this.privacy = newPrivacy
2031 return this.privacy === VideoPrivacy.PRIVATE ||
2032 this.privacy === VideoPrivacy.UNLISTED ||
2033 this.privacy === VideoPrivacy.INTERNAL
2036 async publishIfNeededAndSave (t: Transaction) {
2037 if (this.state !== VideoState.PUBLISHED) {
2038 this.state = VideoState.PUBLISHED
2039 this.publishedAt = new Date()
2040 await this.save({ transaction: t })
2048 getBandwidthBits (videoFile: MVideoFile) {
2049 return Math.ceil((videoFile.size * 8) / this.duration)
2053 if (this.isOwned()) {
2055 WEBSERVER.URL + '/tracker/announce',
2056 WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT + '/tracker/socket'
2060 return this.Trackers.map(t => t.url)