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 { setAsUpdated } from '@server/helpers/database-utils'
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 { AttributesOnly } from '@shared/core-utils'
35 import { VideoFile } from '@shared/models/videos/video-file.model'
36 import { ResultList, UserRight, VideoPrivacy, VideoState } from '../../../shared'
37 import { VideoObject } from '../../../shared/models/activitypub/objects'
38 import { Video, VideoDetails, VideoRateType } from '../../../shared/models/videos'
39 import { ThumbnailType } from '../../../shared/models/videos/thumbnail.type'
40 import { VideoFilter } from '../../../shared/models/videos/video-query.type'
41 import { VideoStreamingPlaylistType } from '../../../shared/models/videos/video-streaming-playlist.type'
42 import { peertubeTruncate } from '../../helpers/core-utils'
43 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
44 import { isBooleanValid } from '../../helpers/custom-validators/misc'
47 isVideoDescriptionValid,
55 } from '../../helpers/custom-validators/videos'
56 import { getVideoFileResolution } from '../../helpers/ffprobe-utils'
57 import { logger } from '../../helpers/logger'
58 import { CONFIG } from '../../initializers/config'
71 } from '../../initializers/constants'
72 import { sendDeleteVideo } from '../../lib/activitypub/send'
75 MChannelAccountDefault,
78 MStreamingPlaylistFilesVideo,
83 MVideoAccountLightBlacklistAllFiles,
88 MVideoFormattableDetails,
94 MVideoThumbnailBlacklist,
98 } from '../../types/models'
99 import { MThumbnail } from '../../types/models/video/thumbnail'
100 import { MVideoFile, MVideoFileStreamingPlaylistVideo } from '../../types/models/video/video-file'
101 import { VideoAbuseModel } from '../abuse/video-abuse'
102 import { AccountModel } from '../account/account'
103 import { AccountVideoRateModel } from '../account/account-video-rate'
104 import { ActorModel } from '../actor/actor'
105 import { ActorImageModel } from '../actor/actor-image'
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 { UserModel } from '../user/user'
111 import { UserVideoHistoryModel } from '../user/user-video-history'
112 import { buildTrigramSearchIndex, buildWhereIdOrUUID, getVideoSort, isOutdated, throwIfNotValid } from '../utils'
113 import { ScheduleVideoUpdateModel } from './schedule-video-update'
114 import { TagModel } from './tag'
115 import { ThumbnailModel } from './thumbnail'
116 import { VideoBlacklistModel } from './video-blacklist'
117 import { VideoCaptionModel } from './video-caption'
118 import { ScopeNames as VideoChannelScopeNames, SummaryOptions, VideoChannelModel } from './video-channel'
119 import { VideoCommentModel } from './video-comment'
120 import { VideoFileModel } from './video-file'
122 videoFilesModelToFormattedJSON,
123 VideoFormattingJSONOptions,
124 videoModelToActivityPubObject,
125 videoModelToFormattedDetailsJSON,
126 videoModelToFormattedJSON
127 } from './video-format-utils'
128 import { VideoImportModel } from './video-import'
129 import { VideoLiveModel } from './video-live'
130 import { VideoPlaylistElementModel } from './video-playlist-element'
131 import { buildListQuery, BuildVideosQueryOptions, wrapForAPIResults } from './video-query-builder'
132 import { VideoShareModel } from './video-share'
133 import { VideoStreamingPlaylistModel } from './video-streaming-playlist'
134 import { VideoTagModel } from './video-tag'
135 import { VideoViewModel } from './video-view'
137 export enum ScopeNames {
138 AVAILABLE_FOR_LIST_IDS = 'AVAILABLE_FOR_LIST_IDS',
140 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
141 WITH_TAGS = 'WITH_TAGS',
142 WITH_TRACKERS = 'WITH_TRACKERS',
143 WITH_WEBTORRENT_FILES = 'WITH_WEBTORRENT_FILES',
144 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
145 WITH_BLACKLISTED = 'WITH_BLACKLISTED',
146 WITH_USER_HISTORY = 'WITH_USER_HISTORY',
147 WITH_STREAMING_PLAYLISTS = 'WITH_STREAMING_PLAYLISTS',
148 WITH_USER_ID = 'WITH_USER_ID',
149 WITH_IMMUTABLE_ATTRIBUTES = 'WITH_IMMUTABLE_ATTRIBUTES',
150 WITH_THUMBNAILS = 'WITH_THUMBNAILS',
151 WITH_LIVE = 'WITH_LIVE'
154 export type ForAPIOptions = {
157 videoPlaylistId?: number
159 withAccountBlockerIds?: number[]
162 export type AvailableForListIDsOptions = {
163 serverAccountId: number
164 followerActorId: number
165 includeLocalVideos: boolean
167 attributesType?: 'none' | 'id' | 'all'
170 categoryOneOf?: number[]
172 licenceOneOf?: number[]
173 languageOneOf?: string[]
180 videoChannelId?: number
182 videoPlaylistId?: number
184 trendingDays?: number
185 user?: MUserAccountId
186 historyOfUser?: MUserId
188 baseWhere?: WhereOptions[]
192 [ScopeNames.WITH_IMMUTABLE_ATTRIBUTES]: {
193 attributes: [ 'id', 'url', 'uuid', 'remote' ]
195 [ScopeNames.FOR_API]: (options: ForAPIOptions) => {
196 const include: Includeable[] = [
198 model: VideoChannelModel.scope({
200 VideoChannelScopeNames.SUMMARY, {
202 withAccountBlockerIds: options.withAccountBlockerIds
209 attributes: [ 'type', 'filename' ],
210 model: ThumbnailModel,
215 const query: FindOptions = {}
225 if (options.videoPlaylistId) {
227 model: VideoPlaylistElementModel.unscoped(),
230 videoPlaylistId: options.videoPlaylistId
235 query.include = include
239 [ScopeNames.WITH_THUMBNAILS]: {
242 model: ThumbnailModel,
247 [ScopeNames.WITH_LIVE]: {
250 model: VideoLiveModel.unscoped(),
255 [ScopeNames.WITH_USER_ID]: {
258 attributes: [ 'accountId' ],
259 model: VideoChannelModel.unscoped(),
263 attributes: [ 'userId' ],
264 model: AccountModel.unscoped(),
271 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
274 model: VideoChannelModel.unscoped(),
279 exclude: [ 'privateKey', 'publicKey' ]
281 model: ActorModel.unscoped(),
285 attributes: [ 'host' ],
286 model: ServerModel.unscoped(),
290 model: ActorImageModel.unscoped(),
297 model: AccountModel.unscoped(),
301 model: ActorModel.unscoped(),
303 exclude: [ 'privateKey', 'publicKey' ]
308 attributes: [ 'host' ],
309 model: ServerModel.unscoped(),
313 model: ActorImageModel.unscoped(),
325 [ScopeNames.WITH_TAGS]: {
326 include: [ TagModel ]
328 [ScopeNames.WITH_TRACKERS]: {
331 attributes: [ 'id', 'url' ],
336 [ScopeNames.WITH_BLACKLISTED]: {
339 attributes: [ 'id', 'reason', 'unfederated' ],
340 model: VideoBlacklistModel,
345 [ScopeNames.WITH_WEBTORRENT_FILES]: (withRedundancies = false) => {
346 let subInclude: any[] = []
348 if (withRedundancies === true) {
351 attributes: [ 'fileUrl' ],
352 model: VideoRedundancyModel.unscoped(),
361 model: VideoFileModel,
369 [ScopeNames.WITH_STREAMING_PLAYLISTS]: (withRedundancies = false) => {
370 const subInclude: IncludeOptions[] = [
372 model: VideoFileModel,
377 if (withRedundancies === true) {
379 attributes: [ 'fileUrl' ],
380 model: VideoRedundancyModel.unscoped(),
388 model: VideoStreamingPlaylistModel.unscoped(),
396 [ScopeNames.WITH_SCHEDULED_UPDATE]: {
399 model: ScheduleVideoUpdateModel.unscoped(),
404 [ScopeNames.WITH_USER_HISTORY]: (userId: number) => {
408 attributes: [ 'currentTime' ],
409 model: UserVideoHistoryModel.unscoped(),
422 buildTrigramSearchIndex('video_name_trigram', 'name'),
424 { fields: [ 'createdAt' ] },
427 { name: 'publishedAt', order: 'DESC' },
428 { name: 'id', order: 'ASC' }
431 { fields: [ 'duration' ] },
434 { name: 'views', order: 'DESC' },
435 { name: 'id', order: 'ASC' }
438 { fields: [ 'channelId' ] },
440 fields: [ 'originallyPublishedAt' ],
442 originallyPublishedAt: {
448 fields: [ 'category' ], // We don't care videos with an unknown category
456 fields: [ 'licence' ], // We don't care videos with an unknown licence
464 fields: [ 'language' ], // We don't care videos with an unknown language
472 fields: [ 'nsfw' ], // Most of the videos are not NSFW
478 fields: [ 'remote' ], // Only index local videos
493 export class VideoModel extends Model<Partial<AttributesOnly<VideoModel>>> {
496 @Default(DataType.UUIDV4)
498 @Column(DataType.UUID)
502 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
508 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category', true))
514 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence', true))
520 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language', true))
521 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
525 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
527 privacy: VideoPrivacy
530 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
536 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description', true))
537 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
542 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support', true))
543 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
547 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
582 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
583 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
588 commentsEnabled: boolean
592 downloadEnabled: boolean
596 waitTranscoding: boolean
600 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
611 @Default(DataType.NOW)
618 originallyPublishedAt: Date
620 @ForeignKey(() => VideoChannelModel)
624 @BelongsTo(() => VideoChannelModel, {
630 VideoChannel: VideoChannelModel
632 @BelongsToMany(() => TagModel, {
633 foreignKey: 'videoId',
634 through: () => VideoTagModel,
639 @BelongsToMany(() => TrackerModel, {
640 foreignKey: 'videoId',
641 through: () => VideoTrackerModel,
644 Trackers: TrackerModel[]
646 @HasMany(() => ThumbnailModel, {
654 Thumbnails: ThumbnailModel[]
656 @HasMany(() => VideoPlaylistElementModel, {
663 VideoPlaylistElements: VideoPlaylistElementModel[]
665 @HasMany(() => VideoAbuseModel, {
672 VideoAbuses: VideoAbuseModel[]
674 @HasMany(() => VideoFileModel, {
682 VideoFiles: VideoFileModel[]
684 @HasMany(() => VideoStreamingPlaylistModel, {
692 VideoStreamingPlaylists: VideoStreamingPlaylistModel[]
694 @HasMany(() => VideoShareModel, {
701 VideoShares: VideoShareModel[]
703 @HasMany(() => AccountVideoRateModel, {
710 AccountVideoRates: AccountVideoRateModel[]
712 @HasMany(() => VideoCommentModel, {
720 VideoComments: VideoCommentModel[]
722 @HasMany(() => VideoViewModel, {
729 VideoViews: VideoViewModel[]
731 @HasMany(() => UserVideoHistoryModel, {
738 UserVideoHistories: UserVideoHistoryModel[]
740 @HasOne(() => ScheduleVideoUpdateModel, {
747 ScheduleVideoUpdate: ScheduleVideoUpdateModel
749 @HasOne(() => VideoBlacklistModel, {
756 VideoBlacklist: VideoBlacklistModel
758 @HasOne(() => VideoLiveModel, {
765 VideoLive: VideoLiveModel
767 @HasOne(() => VideoImportModel, {
774 VideoImport: VideoImportModel
776 @HasMany(() => VideoCaptionModel, {
783 ['separate' as any]: true
785 VideoCaptions: VideoCaptionModel[]
788 static async sendDelete (instance: MVideoAccountLight, options) {
789 if (!instance.isOwned()) return undefined
791 // Lazy load channels
792 if (!instance.VideoChannel) {
793 instance.VideoChannel = await instance.$get('VideoChannel', {
798 transaction: options.transaction
799 }) as MChannelAccountDefault
802 return sendDeleteVideo(instance, options.transaction)
806 static async removeFiles (instance: VideoModel) {
807 const tasks: Promise<any>[] = []
809 logger.info('Removing files of video %s.', instance.url)
811 if (instance.isOwned()) {
812 if (!Array.isArray(instance.VideoFiles)) {
813 instance.VideoFiles = await instance.$get('VideoFiles')
816 // Remove physical files and torrents
817 instance.VideoFiles.forEach(file => {
818 tasks.push(instance.removeFile(file))
819 tasks.push(file.removeTorrent())
822 // Remove playlists file
823 if (!Array.isArray(instance.VideoStreamingPlaylists)) {
824 instance.VideoStreamingPlaylists = await instance.$get('VideoStreamingPlaylists')
827 for (const p of instance.VideoStreamingPlaylists) {
828 tasks.push(instance.removeStreamingPlaylistFiles(p))
832 // Do not wait video deletion because we could be in a transaction
835 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
842 static stopLiveIfNeeded (instance: VideoModel) {
843 if (!instance.isLive) return
845 logger.info('Stopping live of video %s after video deletion.', instance.uuid)
847 return LiveManager.Instance.stopSessionOf(instance.id)
851 static invalidateCache (instance: VideoModel) {
852 ModelCache.Instance.invalidateCache('video', instance.id)
856 static async saveEssentialDataToAbuses (instance: VideoModel, options) {
857 const tasks: Promise<any>[] = []
859 if (!Array.isArray(instance.VideoAbuses)) {
860 instance.VideoAbuses = await instance.$get('VideoAbuses')
862 if (instance.VideoAbuses.length === 0) return undefined
865 logger.info('Saving video abuses details of video %s.', instance.url)
867 if (!instance.Trackers) instance.Trackers = await instance.$get('Trackers', { transaction: options.transaction })
868 const details = instance.toFormattedDetailsJSON()
870 for (const abuse of instance.VideoAbuses) {
871 abuse.deletedVideo = details
872 tasks.push(abuse.save({ transaction: options.transaction }))
877 logger.error('Some errors when saving details of video %s in its abuses before destroy hook.', instance.uuid, { err })
883 static listLocal (): Promise<MVideo[]> {
890 return VideoModel.findAll(query)
893 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
894 function getRawQuery (select: string) {
895 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
896 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
897 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
898 'WHERE "Account"."actorId" = ' + actorId
899 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
900 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
901 'WHERE "VideoShare"."actorId" = ' + actorId
903 return `(${queryVideo}) UNION (${queryVideoShare})`
906 const rawQuery = getRawQuery('"Video"."id"')
907 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
913 order: getVideoSort('-createdAt', [ 'Tags', 'name', 'ASC' ] as any), // FIXME: sequelize typings
916 [Op.in]: Sequelize.literal('(' + rawQuery + ')')
918 [Op.or]: getPrivaciesForFederation()
922 attributes: [ 'filename', 'language', 'fileUrl' ],
923 model: VideoCaptionModel.unscoped(),
927 attributes: [ 'id', 'url' ],
928 model: VideoShareModel.unscoped(),
930 // We only want videos shared by this actor
945 attributes: [ 'id', 'url' ],
946 model: ActorModel.unscoped()
951 model: VideoChannelModel.unscoped(),
955 attributes: [ 'name' ],
956 model: AccountModel.unscoped(),
960 attributes: [ 'id', 'url', 'followersUrl' ],
961 model: ActorModel.unscoped(),
967 attributes: [ 'id', 'url', 'followersUrl' ],
968 model: ActorModel.unscoped(),
974 model: VideoStreamingPlaylistModel.unscoped(),
978 model: VideoFileModel,
983 VideoLiveModel.unscoped(),
989 return Bluebird.all([
990 VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findAll(query),
991 VideoModel.sequelize.query<{ total: string }>(rawCountQuery, { type: QueryTypes.SELECT })
992 ]).then(([ rows, totals ]) => {
993 // totals: totalVideos + totalVideoShares
995 let totalVideoShares = 0
996 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
997 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
999 const total = totalVideos + totalVideoShares
1007 static async listPublishedLiveUUIDs () {
1009 attributes: [ 'uuid' ],
1013 state: VideoState.PUBLISHED
1017 const result = await VideoModel.findAll(options)
1019 return result.map(v => v.uuid)
1022 static listUserVideosForApi (options: {
1030 const { accountId, start, count, sort, search, isLive } = options
1032 function buildBaseQuery (): FindOptions {
1033 const where: WhereOptions = {}
1037 [Op.iLike]: '%' + search + '%'
1042 where.isLive = isLive
1049 order: getVideoSort(sort),
1052 model: VideoChannelModel,
1056 model: AccountModel,
1070 const countQuery = buildBaseQuery()
1071 const findQuery = buildBaseQuery()
1073 const findScopes: (string | ScopeOptions)[] = [
1074 ScopeNames.WITH_SCHEDULED_UPDATE,
1075 ScopeNames.WITH_BLACKLISTED,
1076 ScopeNames.WITH_THUMBNAILS
1079 return Promise.all([
1080 VideoModel.count(countQuery),
1081 VideoModel.scope(findScopes).findAll<MVideoForUser>(findQuery)
1082 ]).then(([ count, rows ]) => {
1090 static async listForApi (options: {
1096 filter?: VideoFilter
1099 includeLocalVideos: boolean
1102 categoryOneOf?: number[]
1103 licenceOneOf?: number[]
1104 languageOneOf?: string[]
1105 tagsOneOf?: string[]
1106 tagsAllOf?: string[]
1109 videoChannelId?: number
1111 followerActorId?: number
1113 videoPlaylistId?: number
1115 trendingDays?: number
1117 user?: MUserAccountId
1118 historyOfUser?: MUserId
1120 countVideos?: boolean
1124 if ((options.filter === 'all-local' || options.filter === 'all') && !options.user.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1125 throw new Error('Try to filter all-local but no user has not the see all videos right')
1128 const trendingDays = options.sort.endsWith('trending')
1129 ? CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1131 let trendingAlgorithm
1132 if (options.sort.endsWith('hot')) trendingAlgorithm = 'hot'
1133 if (options.sort.endsWith('best')) trendingAlgorithm = 'best'
1135 const serverActor = await getServerActor()
1137 // followerActorId === null has a meaning, so just check undefined
1138 const followerActorId = options.followerActorId !== undefined
1139 ? options.followerActorId
1142 const queryOptions = {
1143 start: options.start,
1144 count: options.count,
1147 serverAccountId: serverActor.Account.id,
1149 isLive: options.isLive,
1150 categoryOneOf: options.categoryOneOf,
1151 licenceOneOf: options.licenceOneOf,
1152 languageOneOf: options.languageOneOf,
1153 tagsOneOf: options.tagsOneOf,
1154 tagsAllOf: options.tagsAllOf,
1155 filter: options.filter,
1156 withFiles: options.withFiles,
1157 accountId: options.accountId,
1158 videoChannelId: options.videoChannelId,
1159 videoPlaylistId: options.videoPlaylistId,
1160 includeLocalVideos: options.includeLocalVideos,
1162 historyOfUser: options.historyOfUser,
1165 search: options.search
1168 return VideoModel.getAvailableForApi(queryOptions, options.countVideos)
1171 static async searchAndPopulateAccountAndServer (options: {
1172 includeLocalVideos: boolean
1177 startDate?: string // ISO 8601
1178 endDate?: string // ISO 8601
1179 originallyPublishedStartDate?: string
1180 originallyPublishedEndDate?: string
1183 categoryOneOf?: number[]
1184 licenceOneOf?: number[]
1185 languageOneOf?: string[]
1186 tagsOneOf?: string[]
1187 tagsAllOf?: string[]
1188 durationMin?: number // seconds
1189 durationMax?: number // seconds
1190 user?: MUserAccountId
1191 filter?: VideoFilter
1193 const serverActor = await getServerActor()
1195 const queryOptions = {
1196 followerActorId: serverActor.id,
1197 serverAccountId: serverActor.Account.id,
1199 includeLocalVideos: options.includeLocalVideos,
1201 isLive: options.isLive,
1203 categoryOneOf: options.categoryOneOf,
1204 licenceOneOf: options.licenceOneOf,
1205 languageOneOf: options.languageOneOf,
1207 tagsOneOf: options.tagsOneOf,
1208 tagsAllOf: options.tagsAllOf,
1211 filter: options.filter,
1213 start: options.start,
1214 count: options.count,
1217 startDate: options.startDate,
1218 endDate: options.endDate,
1220 originallyPublishedStartDate: options.originallyPublishedStartDate,
1221 originallyPublishedEndDate: options.originallyPublishedEndDate,
1223 durationMin: options.durationMin,
1224 durationMax: options.durationMax,
1226 search: options.search
1229 return VideoModel.getAvailableForApi(queryOptions)
1232 static countLocalLives () {
1238 [Op.ne]: VideoState.LIVE_ENDED
1243 return VideoModel.count(options)
1246 static countVideosUploadedByUserSince (userId: number, since: Date) {
1250 model: VideoChannelModel.unscoped(),
1254 model: AccountModel.unscoped(),
1258 model: UserModel.unscoped(),
1276 return VideoModel.unscoped().count(options)
1279 static countLivesOfAccount (accountId: number) {
1285 [Op.ne]: VideoState.LIVE_ENDED
1291 model: VideoChannelModel.unscoped(),
1299 return VideoModel.count(options)
1302 static load (id: number | string, t?: Transaction): Promise<MVideoThumbnail> {
1303 const where = buildWhereIdOrUUID(id)
1309 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1312 static loadWithBlacklist (id: number | string, t?: Transaction): Promise<MVideoThumbnailBlacklist> {
1313 const where = buildWhereIdOrUUID(id)
1319 return VideoModel.scope([
1320 ScopeNames.WITH_THUMBNAILS,
1321 ScopeNames.WITH_BLACKLISTED
1325 static loadImmutableAttributes (id: number | string, t?: Transaction): Promise<MVideoImmutable> {
1328 where: buildWhereIdOrUUID(id),
1332 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1335 return ModelCache.Instance.doCache({
1336 cacheType: 'load-video-immutable-id',
1343 static loadWithRights (id: number | string, t?: Transaction): Promise<MVideoWithRights> {
1344 const where = buildWhereIdOrUUID(id)
1350 return VideoModel.scope([
1351 ScopeNames.WITH_BLACKLISTED,
1352 ScopeNames.WITH_USER_ID
1356 static loadOnlyId (id: number | string, t?: Transaction): Promise<MVideoIdThumbnail> {
1357 const where = buildWhereIdOrUUID(id)
1360 attributes: [ 'id' ],
1365 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1368 static loadWithFiles (id: number | string, t?: Transaction, logging?: boolean): Promise<MVideoWithAllFiles> {
1369 const where = buildWhereIdOrUUID(id)
1377 return VideoModel.scope([
1378 ScopeNames.WITH_WEBTORRENT_FILES,
1379 ScopeNames.WITH_STREAMING_PLAYLISTS,
1380 ScopeNames.WITH_THUMBNAILS
1384 static loadByUUID (uuid: string): Promise<MVideoThumbnail> {
1391 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1394 static loadByUrl (url: string, transaction?: Transaction): Promise<MVideoThumbnail> {
1395 const query: FindOptions = {
1402 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(query)
1405 static loadByUrlImmutableAttributes (url: string, transaction?: Transaction): Promise<MVideoImmutable> {
1407 const query: FindOptions = {
1414 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1417 return ModelCache.Instance.doCache({
1418 cacheType: 'load-video-immutable-url',
1425 static loadByUrlAndPopulateAccount (url: string, transaction?: Transaction): Promise<MVideoAccountLightBlacklistAllFiles> {
1426 const query: FindOptions = {
1433 return VideoModel.scope([
1434 ScopeNames.WITH_ACCOUNT_DETAILS,
1435 ScopeNames.WITH_WEBTORRENT_FILES,
1436 ScopeNames.WITH_STREAMING_PLAYLISTS,
1437 ScopeNames.WITH_THUMBNAILS,
1438 ScopeNames.WITH_BLACKLISTED
1442 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Transaction, userId?: number): Promise<MVideoFullLight> {
1443 const where = buildWhereIdOrUUID(id)
1446 order: [ [ 'Tags', 'name', 'ASC' ] ] as any,
1451 const scopes: (string | ScopeOptions)[] = [
1452 ScopeNames.WITH_TAGS,
1453 ScopeNames.WITH_BLACKLISTED,
1454 ScopeNames.WITH_ACCOUNT_DETAILS,
1455 ScopeNames.WITH_SCHEDULED_UPDATE,
1456 ScopeNames.WITH_WEBTORRENT_FILES,
1457 ScopeNames.WITH_STREAMING_PLAYLISTS,
1458 ScopeNames.WITH_THUMBNAILS,
1459 ScopeNames.WITH_LIVE
1463 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1471 static loadForGetAPI (parameters: {
1475 }): Promise<MVideoDetails> {
1476 const { id, t, userId } = parameters
1477 const where = buildWhereIdOrUUID(id)
1480 order: [ [ 'Tags', 'name', 'ASC' ] ] as any, // FIXME: sequelize typings
1485 const scopes: (string | ScopeOptions)[] = [
1486 ScopeNames.WITH_TAGS,
1487 ScopeNames.WITH_BLACKLISTED,
1488 ScopeNames.WITH_ACCOUNT_DETAILS,
1489 ScopeNames.WITH_SCHEDULED_UPDATE,
1490 ScopeNames.WITH_THUMBNAILS,
1491 ScopeNames.WITH_LIVE,
1492 ScopeNames.WITH_TRACKERS,
1493 { method: [ ScopeNames.WITH_WEBTORRENT_FILES, true ] },
1494 { method: [ ScopeNames.WITH_STREAMING_PLAYLISTS, true ] }
1498 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1506 static async getStats () {
1507 const totalLocalVideos = await VideoModel.count({
1513 let totalLocalVideoViews = await VideoModel.sum('views', {
1519 // Sequelize could return null...
1520 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1522 const { total: totalVideos } = await VideoModel.listForApi({
1525 sort: '-publishedAt',
1526 nsfw: buildNSFWFilter(),
1527 includeLocalVideos: true,
1533 totalLocalVideoViews,
1538 static incrementViews (id: number, views: number) {
1539 return VideoModel.increment('views', {
1547 static updateRatesOf (videoId: number, type: VideoRateType, t: Transaction) {
1548 const field = type === 'like'
1552 const rawQuery = `UPDATE "video" SET "${field}" = ` +
1554 'SELECT COUNT(id) FROM "accountVideoRate" WHERE "accountVideoRate"."videoId" = "video"."id" AND type = :rateType' +
1556 'WHERE "video"."id" = :videoId'
1558 return AccountVideoRateModel.sequelize.query(rawQuery, {
1560 replacements: { videoId, rateType: type },
1561 type: QueryTypes.UPDATE
1565 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1566 // Instances only share videos
1567 const query = 'SELECT 1 FROM "videoShare" ' +
1568 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1569 'WHERE "actorFollow"."actorId" = $followerActorId AND "actorFollow"."state" = \'accepted\' AND "videoShare"."videoId" = $videoId ' +
1573 type: QueryTypes.SELECT as QueryTypes.SELECT,
1574 bind: { followerActorId, videoId },
1578 return VideoModel.sequelize.query(query, options)
1579 .then(results => results.length === 1)
1582 static bulkUpdateSupportField (videoChannel: MChannel, t: Transaction) {
1585 channelId: videoChannel.id
1590 return VideoModel.update({ support: videoChannel.support }, options)
1593 static getAllIdsFromChannel (videoChannel: MChannelId): Promise<number[]> {
1595 attributes: [ 'id' ],
1597 channelId: videoChannel.id
1601 return VideoModel.findAll(query)
1602 .then(videos => videos.map(v => v.id))
1605 // threshold corresponds to how many video the field should have to be returned
1606 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1607 const serverActor = await getServerActor()
1608 const followerActorId = serverActor.id
1610 const queryOptions: BuildVideosQueryOptions = {
1611 attributes: [ `"${field}"` ],
1612 group: `GROUP BY "${field}"`,
1613 having: `HAVING COUNT("${field}") >= ${threshold}`,
1617 serverAccountId: serverActor.Account.id,
1619 includeLocalVideos: true
1622 const { query, replacements } = buildListQuery(VideoModel.sequelize, queryOptions)
1624 return this.sequelize.query<any>(query, { replacements, type: QueryTypes.SELECT })
1625 .then(rows => rows.map(r => r[field]))
1628 static buildTrendingQuery (trendingDays: number) {
1632 model: VideoViewModel,
1636 [Op.gte]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1642 private static async getAvailableForApi (
1643 options: BuildVideosQueryOptions,
1645 ): Promise<ResultList<VideoModel>> {
1646 function getCount () {
1647 if (countVideos !== true) return Promise.resolve(undefined)
1649 const countOptions = Object.assign({}, options, { isCount: true })
1650 const { query: queryCount, replacements: replacementsCount } = buildListQuery(VideoModel.sequelize, countOptions)
1652 return VideoModel.sequelize.query<any>(queryCount, { replacements: replacementsCount, type: QueryTypes.SELECT })
1653 .then(rows => rows.length !== 0 ? rows[0].total : 0)
1656 function getModels () {
1657 if (options.count === 0) return Promise.resolve([])
1659 const { query, replacements, order } = buildListQuery(VideoModel.sequelize, options)
1660 const queryModels = wrapForAPIResults(query, replacements, options, order)
1662 return VideoModel.sequelize.query<any>(queryModels, { replacements, type: QueryTypes.SELECT, nest: true })
1663 .then(rows => VideoModel.buildAPIResult(rows))
1666 const [ count, rows ] = await Promise.all([ getCount(), getModels() ])
1674 private static buildAPIResult (rows: any[]) {
1675 const videosMemo: { [ id: number ]: VideoModel } = {}
1676 const videoStreamingPlaylistMemo: { [ id: number ]: VideoStreamingPlaylistModel } = {}
1678 const thumbnailsDone = new Set<number>()
1679 const historyDone = new Set<number>()
1680 const videoFilesDone = new Set<number>()
1682 const videos: VideoModel[] = []
1684 const avatarKeys = [ 'id', 'filename', 'fileUrl', 'onDisk', 'createdAt', 'updatedAt' ]
1685 const actorKeys = [ 'id', 'preferredUsername', 'url', 'serverId', 'avatarId' ]
1686 const serverKeys = [ 'id', 'host' ]
1687 const videoFileKeys = [
1701 'videoStreamingPlaylistId'
1703 const videoStreamingPlaylistKeys = [ 'id', 'type', 'playlistUrl' ]
1727 'originallyPublishedAt',
1732 const buildOpts = { raw: true }
1734 function buildActor (rowActor: any) {
1735 const avatarModel = rowActor.Avatar.id !== null
1736 ? new ActorImageModel(pick(rowActor.Avatar, avatarKeys), buildOpts)
1739 const serverModel = rowActor.Server.id !== null
1740 ? new ServerModel(pick(rowActor.Server, serverKeys), buildOpts)
1743 const actorModel = new ActorModel(pick(rowActor, actorKeys), buildOpts)
1744 actorModel.Avatar = avatarModel
1745 actorModel.Server = serverModel
1750 for (const row of rows) {
1751 if (!videosMemo[row.id]) {
1753 const channel = row.VideoChannel
1754 const channelModel = new VideoChannelModel(pick(channel, [ 'id', 'name', 'description', 'actorId' ]), buildOpts)
1755 channelModel.Actor = buildActor(channel.Actor)
1757 const account = row.VideoChannel.Account
1758 const accountModel = new AccountModel(pick(account, [ 'id', 'name' ]), buildOpts)
1759 accountModel.Actor = buildActor(account.Actor)
1761 channelModel.Account = accountModel
1763 const videoModel = new VideoModel(pick(row, videoKeys), buildOpts)
1764 videoModel.VideoChannel = channelModel
1766 videoModel.UserVideoHistories = []
1767 videoModel.Thumbnails = []
1768 videoModel.VideoFiles = []
1769 videoModel.VideoStreamingPlaylists = []
1771 videosMemo[row.id] = videoModel
1772 // Don't take object value to have a sorted array
1773 videos.push(videoModel)
1776 const videoModel = videosMemo[row.id]
1778 if (row.userVideoHistory?.id && !historyDone.has(row.userVideoHistory.id)) {
1779 const historyModel = new UserVideoHistoryModel(pick(row.userVideoHistory, [ 'id', 'currentTime' ]), buildOpts)
1780 videoModel.UserVideoHistories.push(historyModel)
1782 historyDone.add(row.userVideoHistory.id)
1785 if (row.Thumbnails?.id && !thumbnailsDone.has(row.Thumbnails.id)) {
1786 const thumbnailModel = new ThumbnailModel(pick(row.Thumbnails, [ 'id', 'type', 'filename' ]), buildOpts)
1787 videoModel.Thumbnails.push(thumbnailModel)
1789 thumbnailsDone.add(row.Thumbnails.id)
1792 if (row.VideoFiles?.id && !videoFilesDone.has(row.VideoFiles.id)) {
1793 const videoFileModel = new VideoFileModel(pick(row.VideoFiles, videoFileKeys), buildOpts)
1794 videoModel.VideoFiles.push(videoFileModel)
1796 videoFilesDone.add(row.VideoFiles.id)
1799 if (row.VideoStreamingPlaylists?.id && !videoStreamingPlaylistMemo[row.VideoStreamingPlaylists.id]) {
1800 const streamingPlaylist = new VideoStreamingPlaylistModel(pick(row.VideoStreamingPlaylists, videoStreamingPlaylistKeys), buildOpts)
1801 streamingPlaylist.VideoFiles = []
1803 videoModel.VideoStreamingPlaylists.push(streamingPlaylist)
1805 videoStreamingPlaylistMemo[streamingPlaylist.id] = streamingPlaylist
1808 if (row.VideoStreamingPlaylists?.VideoFiles?.id && !videoFilesDone.has(row.VideoStreamingPlaylists.VideoFiles.id)) {
1809 const streamingPlaylist = videoStreamingPlaylistMemo[row.VideoStreamingPlaylists.id]
1811 const videoFileModel = new VideoFileModel(pick(row.VideoStreamingPlaylists.VideoFiles, videoFileKeys), buildOpts)
1812 streamingPlaylist.VideoFiles.push(videoFileModel)
1814 videoFilesDone.add(row.VideoStreamingPlaylists.VideoFiles.id)
1821 static getCategoryLabel (id: number) {
1822 return VIDEO_CATEGORIES[id] || 'Misc'
1825 static getLicenceLabel (id: number) {
1826 return VIDEO_LICENCES[id] || 'Unknown'
1829 static getLanguageLabel (id: string) {
1830 return VIDEO_LANGUAGES[id] || 'Unknown'
1833 static getPrivacyLabel (id: number) {
1834 return VIDEO_PRIVACIES[id] || 'Unknown'
1837 static getStateLabel (id: number) {
1838 return VIDEO_STATES[id] || 'Unknown'
1842 return !!this.VideoBlacklist
1846 return this.VideoChannel.Account.Actor.Server?.isBlocked() || this.VideoChannel.Account.isBlocked()
1849 getQualityFileBy<T extends MVideoWithFile> (this: T, fun: (files: MVideoFile[], it: (file: MVideoFile) => number) => MVideoFile) {
1850 // We first transcode to WebTorrent format, so try this array first
1851 if (Array.isArray(this.VideoFiles) && this.VideoFiles.length !== 0) {
1852 const file = fun(this.VideoFiles, file => file.resolution)
1854 return Object.assign(file, { Video: this })
1857 // No webtorrent files, try with streaming playlist files
1858 if (Array.isArray(this.VideoStreamingPlaylists) && this.VideoStreamingPlaylists.length !== 0) {
1859 const streamingPlaylistWithVideo = Object.assign(this.VideoStreamingPlaylists[0], { Video: this })
1861 const file = fun(streamingPlaylistWithVideo.VideoFiles, file => file.resolution)
1862 return Object.assign(file, { VideoStreamingPlaylist: streamingPlaylistWithVideo })
1868 getMaxQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1869 return this.getQualityFileBy(maxBy)
1872 getMinQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1873 return this.getQualityFileBy(minBy)
1876 getWebTorrentFile<T extends MVideoWithFile> (this: T, resolution: number): MVideoFileVideo {
1877 if (Array.isArray(this.VideoFiles) === false) return undefined
1879 const file = this.VideoFiles.find(f => f.resolution === resolution)
1880 if (!file) return undefined
1882 return Object.assign(file, { Video: this })
1885 hasWebTorrentFiles () {
1886 return Array.isArray(this.VideoFiles) === true && this.VideoFiles.length !== 0
1889 async addAndSaveThumbnail (thumbnail: MThumbnail, transaction?: Transaction) {
1890 thumbnail.videoId = this.id
1892 const savedThumbnail = await thumbnail.save({ transaction })
1894 if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = []
1896 // Already have this thumbnail, skip
1897 if (this.Thumbnails.find(t => t.id === savedThumbnail.id)) return
1899 this.Thumbnails.push(savedThumbnail)
1903 if (Array.isArray(this.Thumbnails) === false) return undefined
1905 return this.Thumbnails.find(t => t.type === ThumbnailType.MINIATURE)
1909 return !!this.getPreview()
1913 if (Array.isArray(this.Thumbnails) === false) return undefined
1915 return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW)
1919 return this.remote === false
1922 getWatchStaticPath () {
1923 return '/w/' + this.uuid
1926 getEmbedStaticPath () {
1927 return '/videos/embed/' + this.uuid
1930 getMiniatureStaticPath () {
1931 const thumbnail = this.getMiniature()
1932 if (!thumbnail) return null
1934 return join(STATIC_PATHS.THUMBNAILS, thumbnail.filename)
1937 getPreviewStaticPath () {
1938 const preview = this.getPreview()
1939 if (!preview) return null
1941 // We use a local cache, so specify our cache endpoint instead of potential remote URL
1942 return join(LAZY_STATIC_PATHS.PREVIEWS, preview.filename)
1945 toFormattedJSON (this: MVideoFormattable, options?: VideoFormattingJSONOptions): Video {
1946 return videoModelToFormattedJSON(this, options)
1949 toFormattedDetailsJSON (this: MVideoFormattableDetails): VideoDetails {
1950 return videoModelToFormattedDetailsJSON(this)
1953 getFormattedVideoFilesJSON (includeMagnet = true): VideoFile[] {
1954 let files: VideoFile[] = []
1956 if (Array.isArray(this.VideoFiles)) {
1957 const result = videoFilesModelToFormattedJSON(this, this.VideoFiles, includeMagnet)
1958 files = files.concat(result)
1961 for (const p of (this.VideoStreamingPlaylists || [])) {
1962 const result = videoFilesModelToFormattedJSON(this, p.VideoFiles, includeMagnet)
1963 files = files.concat(result)
1969 toActivityPubObject (this: MVideoAP): VideoObject {
1970 return videoModelToActivityPubObject(this)
1973 getTruncatedDescription () {
1974 if (!this.description) return null
1976 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1977 return peertubeTruncate(this.description, { length: maxLength })
1980 getMaxQualityResolution () {
1981 const file = this.getMaxQualityFile()
1982 const videoOrPlaylist = file.getVideoOrStreamingPlaylist()
1983 const originalFilePath = getVideoFilePath(videoOrPlaylist, file)
1985 return getVideoFileResolution(originalFilePath)
1988 getDescriptionAPIPath () {
1989 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1992 getHLSPlaylist (): MStreamingPlaylistFilesVideo {
1993 if (!this.VideoStreamingPlaylists) return undefined
1995 const playlist = this.VideoStreamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
1996 playlist.Video = this
2001 setHLSPlaylist (playlist: MStreamingPlaylist) {
2002 const toAdd = [ playlist ] as [ VideoStreamingPlaylistModel ]
2004 if (Array.isArray(this.VideoStreamingPlaylists) === false || this.VideoStreamingPlaylists.length === 0) {
2005 this.VideoStreamingPlaylists = toAdd
2009 this.VideoStreamingPlaylists = this.VideoStreamingPlaylists
2010 .filter(s => s.type !== VideoStreamingPlaylistType.HLS)
2014 removeFile (videoFile: MVideoFile, isRedundancy = false) {
2015 const filePath = getVideoFilePath(this, videoFile, isRedundancy)
2016 return remove(filePath)
2017 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
2020 async removeStreamingPlaylistFiles (streamingPlaylist: MStreamingPlaylist, isRedundancy = false) {
2021 const directoryPath = getHLSDirectory(this, isRedundancy)
2023 await remove(directoryPath)
2025 if (isRedundancy !== true) {
2026 const streamingPlaylistWithFiles = streamingPlaylist as MStreamingPlaylistFilesVideo
2027 streamingPlaylistWithFiles.Video = this
2029 if (!Array.isArray(streamingPlaylistWithFiles.VideoFiles)) {
2030 streamingPlaylistWithFiles.VideoFiles = await streamingPlaylistWithFiles.$get('VideoFiles')
2033 // Remove physical files and torrents
2035 streamingPlaylistWithFiles.VideoFiles.map(file => file.removeTorrent())
2041 if (this.isOwned()) return false
2043 return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)
2046 hasPrivacyForFederation () {
2047 return isPrivacyForFederation(this.privacy)
2050 hasStateForFederation () {
2051 return isStateForFederation(this.state)
2054 isNewVideo (newPrivacy: VideoPrivacy) {
2055 return this.hasPrivacyForFederation() === false && isPrivacyForFederation(newPrivacy) === true
2059 return setAsUpdated('video', this.id)
2063 return this.privacy === VideoPrivacy.PRIVATE || this.privacy === VideoPrivacy.INTERNAL || !!this.VideoBlacklist
2066 setPrivacy (newPrivacy: VideoPrivacy) {
2067 if (this.privacy === VideoPrivacy.PRIVATE && newPrivacy !== VideoPrivacy.PRIVATE) {
2068 this.publishedAt = new Date()
2071 this.privacy = newPrivacy
2075 return this.privacy === VideoPrivacy.PRIVATE ||
2076 this.privacy === VideoPrivacy.UNLISTED ||
2077 this.privacy === VideoPrivacy.INTERNAL
2080 async publishIfNeededAndSave (t: Transaction) {
2081 if (this.state !== VideoState.PUBLISHED) {
2082 this.state = VideoState.PUBLISHED
2083 this.publishedAt = new Date()
2084 await this.save({ transaction: t })
2092 getBandwidthBits (videoFile: MVideoFile) {
2093 return Math.ceil((videoFile.size * 8) / this.duration)
2097 if (this.isOwned()) {
2099 WEBSERVER.URL + '/tracker/announce',
2100 WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT + '/tracker/socket'
2104 return this.Trackers.map(t => t.url)