1 import * as Bluebird from 'bluebird'
2 import { remove } from 'fs-extra'
3 import { maxBy, minBy } 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'
114 videoFilesModelToFormattedJSON,
115 VideoFormattingJSONOptions,
116 videoModelToActivityPubObject,
117 videoModelToFormattedDetailsJSON,
118 videoModelToFormattedJSON
119 } from './formatter/video-format-utils'
120 import { ScheduleVideoUpdateModel } from './schedule-video-update'
121 import { VideosModelGetQueryBuilder } from './sql/video-model-get-query-builder'
122 import { BuildVideosListQueryOptions, VideosIdListQueryBuilder } from './sql/videos-id-list-query-builder'
123 import { VideosModelListQueryBuilder } from './sql/videos-model-list-query-builder'
124 import { TagModel } from './tag'
125 import { ThumbnailModel } from './thumbnail'
126 import { VideoBlacklistModel } from './video-blacklist'
127 import { VideoCaptionModel } from './video-caption'
128 import { ScopeNames as VideoChannelScopeNames, SummaryOptions, VideoChannelModel } from './video-channel'
129 import { VideoCommentModel } from './video-comment'
130 import { VideoFileModel } from './video-file'
131 import { VideoImportModel } from './video-import'
132 import { VideoLiveModel } from './video-live'
133 import { VideoPlaylistElementModel } from './video-playlist-element'
134 import { VideoShareModel } from './video-share'
135 import { VideoStreamingPlaylistModel } from './video-streaming-playlist'
136 import { VideoTagModel } from './video-tag'
137 import { VideoViewModel } from './video-view'
139 export enum ScopeNames {
140 AVAILABLE_FOR_LIST_IDS = 'AVAILABLE_FOR_LIST_IDS',
142 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
143 WITH_TAGS = 'WITH_TAGS',
144 WITH_TRACKERS = 'WITH_TRACKERS',
145 WITH_WEBTORRENT_FILES = 'WITH_WEBTORRENT_FILES',
146 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
147 WITH_BLACKLISTED = 'WITH_BLACKLISTED',
148 WITH_USER_HISTORY = 'WITH_USER_HISTORY',
149 WITH_STREAMING_PLAYLISTS = 'WITH_STREAMING_PLAYLISTS',
150 WITH_USER_ID = 'WITH_USER_ID',
151 WITH_IMMUTABLE_ATTRIBUTES = 'WITH_IMMUTABLE_ATTRIBUTES',
152 WITH_THUMBNAILS = 'WITH_THUMBNAILS',
153 WITH_LIVE = 'WITH_LIVE'
156 export type ForAPIOptions = {
159 videoPlaylistId?: number
161 withAccountBlockerIds?: number[]
164 export type AvailableForListIDsOptions = {
165 serverAccountId: number
166 followerActorId: number
167 includeLocalVideos: boolean
169 attributesType?: 'none' | 'id' | 'all'
172 categoryOneOf?: number[]
174 licenceOneOf?: number[]
175 languageOneOf?: string[]
182 videoChannelId?: number
184 videoPlaylistId?: number
186 trendingDays?: number
187 user?: MUserAccountId
188 historyOfUser?: MUserId
190 baseWhere?: WhereOptions[]
194 [ScopeNames.WITH_IMMUTABLE_ATTRIBUTES]: {
195 attributes: [ 'id', 'url', 'uuid', 'remote' ]
197 [ScopeNames.FOR_API]: (options: ForAPIOptions) => {
198 const include: Includeable[] = [
200 model: VideoChannelModel.scope({
202 VideoChannelScopeNames.SUMMARY, {
204 withAccountBlockerIds: options.withAccountBlockerIds
211 attributes: [ 'type', 'filename' ],
212 model: ThumbnailModel,
217 const query: FindOptions = {}
227 if (options.videoPlaylistId) {
229 model: VideoPlaylistElementModel.unscoped(),
232 videoPlaylistId: options.videoPlaylistId
237 query.include = include
241 [ScopeNames.WITH_THUMBNAILS]: {
244 model: ThumbnailModel,
249 [ScopeNames.WITH_LIVE]: {
252 model: VideoLiveModel.unscoped(),
257 [ScopeNames.WITH_USER_ID]: {
260 attributes: [ 'accountId' ],
261 model: VideoChannelModel.unscoped(),
265 attributes: [ 'userId' ],
266 model: AccountModel.unscoped(),
273 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
276 model: VideoChannelModel.unscoped(),
281 exclude: [ 'privateKey', 'publicKey' ]
283 model: ActorModel.unscoped(),
287 attributes: [ 'host' ],
288 model: ServerModel.unscoped(),
292 model: ActorImageModel.unscoped(),
299 model: AccountModel.unscoped(),
303 model: ActorModel.unscoped(),
305 exclude: [ 'privateKey', 'publicKey' ]
310 attributes: [ 'host' ],
311 model: ServerModel.unscoped(),
315 model: ActorImageModel.unscoped(),
327 [ScopeNames.WITH_TAGS]: {
328 include: [ TagModel ]
330 [ScopeNames.WITH_TRACKERS]: {
333 attributes: [ 'id', 'url' ],
338 [ScopeNames.WITH_BLACKLISTED]: {
341 attributes: [ 'id', 'reason', 'unfederated' ],
342 model: VideoBlacklistModel,
347 [ScopeNames.WITH_WEBTORRENT_FILES]: (withRedundancies = false) => {
348 let subInclude: any[] = []
350 if (withRedundancies === true) {
353 attributes: [ 'fileUrl' ],
354 model: VideoRedundancyModel.unscoped(),
363 model: VideoFileModel,
371 [ScopeNames.WITH_STREAMING_PLAYLISTS]: (withRedundancies = false) => {
372 const subInclude: IncludeOptions[] = [
374 model: VideoFileModel,
379 if (withRedundancies === true) {
381 attributes: [ 'fileUrl' ],
382 model: VideoRedundancyModel.unscoped(),
390 model: VideoStreamingPlaylistModel.unscoped(),
398 [ScopeNames.WITH_SCHEDULED_UPDATE]: {
401 model: ScheduleVideoUpdateModel.unscoped(),
406 [ScopeNames.WITH_USER_HISTORY]: (userId: number) => {
410 attributes: [ 'currentTime' ],
411 model: UserVideoHistoryModel.unscoped(),
424 buildTrigramSearchIndex('video_name_trigram', 'name'),
426 { fields: [ 'createdAt' ] },
429 { name: 'publishedAt', order: 'DESC' },
430 { name: 'id', order: 'ASC' }
433 { fields: [ 'duration' ] },
436 { name: 'views', order: 'DESC' },
437 { name: 'id', order: 'ASC' }
440 { fields: [ 'channelId' ] },
442 fields: [ 'originallyPublishedAt' ],
444 originallyPublishedAt: {
450 fields: [ 'category' ], // We don't care videos with an unknown category
458 fields: [ 'licence' ], // We don't care videos with an unknown licence
466 fields: [ 'language' ], // We don't care videos with an unknown language
474 fields: [ 'nsfw' ], // Most of the videos are not NSFW
480 fields: [ 'remote' ], // Only index local videos
495 export class VideoModel extends Model<Partial<AttributesOnly<VideoModel>>> {
498 @Default(DataType.UUIDV4)
500 @Column(DataType.UUID)
504 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
510 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category', true))
516 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence', true))
522 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language', true))
523 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
527 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
529 privacy: VideoPrivacy
532 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
538 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description', true))
539 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
544 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support', true))
545 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
549 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
584 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
585 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
590 commentsEnabled: boolean
594 downloadEnabled: boolean
598 waitTranscoding: boolean
602 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
613 @Default(DataType.NOW)
620 originallyPublishedAt: Date
622 @ForeignKey(() => VideoChannelModel)
626 @BelongsTo(() => VideoChannelModel, {
632 VideoChannel: VideoChannelModel
634 @BelongsToMany(() => TagModel, {
635 foreignKey: 'videoId',
636 through: () => VideoTagModel,
641 @BelongsToMany(() => TrackerModel, {
642 foreignKey: 'videoId',
643 through: () => VideoTrackerModel,
646 Trackers: TrackerModel[]
648 @HasMany(() => ThumbnailModel, {
656 Thumbnails: ThumbnailModel[]
658 @HasMany(() => VideoPlaylistElementModel, {
665 VideoPlaylistElements: VideoPlaylistElementModel[]
667 @HasMany(() => VideoAbuseModel, {
674 VideoAbuses: VideoAbuseModel[]
676 @HasMany(() => VideoFileModel, {
684 VideoFiles: VideoFileModel[]
686 @HasMany(() => VideoStreamingPlaylistModel, {
694 VideoStreamingPlaylists: VideoStreamingPlaylistModel[]
696 @HasMany(() => VideoShareModel, {
703 VideoShares: VideoShareModel[]
705 @HasMany(() => AccountVideoRateModel, {
712 AccountVideoRates: AccountVideoRateModel[]
714 @HasMany(() => VideoCommentModel, {
722 VideoComments: VideoCommentModel[]
724 @HasMany(() => VideoViewModel, {
731 VideoViews: VideoViewModel[]
733 @HasMany(() => UserVideoHistoryModel, {
740 UserVideoHistories: UserVideoHistoryModel[]
742 @HasOne(() => ScheduleVideoUpdateModel, {
749 ScheduleVideoUpdate: ScheduleVideoUpdateModel
751 @HasOne(() => VideoBlacklistModel, {
758 VideoBlacklist: VideoBlacklistModel
760 @HasOne(() => VideoLiveModel, {
767 VideoLive: VideoLiveModel
769 @HasOne(() => VideoImportModel, {
776 VideoImport: VideoImportModel
778 @HasMany(() => VideoCaptionModel, {
785 ['separate' as any]: true
787 VideoCaptions: VideoCaptionModel[]
790 static async sendDelete (instance: MVideoAccountLight, options) {
791 if (!instance.isOwned()) return undefined
793 // Lazy load channels
794 if (!instance.VideoChannel) {
795 instance.VideoChannel = await instance.$get('VideoChannel', {
800 transaction: options.transaction
801 }) as MChannelAccountDefault
804 return sendDeleteVideo(instance, options.transaction)
808 static async removeFiles (instance: VideoModel) {
809 const tasks: Promise<any>[] = []
811 logger.info('Removing files of video %s.', instance.url)
813 if (instance.isOwned()) {
814 if (!Array.isArray(instance.VideoFiles)) {
815 instance.VideoFiles = await instance.$get('VideoFiles')
818 // Remove physical files and torrents
819 instance.VideoFiles.forEach(file => {
820 tasks.push(instance.removeFile(file))
821 tasks.push(file.removeTorrent())
824 // Remove playlists file
825 if (!Array.isArray(instance.VideoStreamingPlaylists)) {
826 instance.VideoStreamingPlaylists = await instance.$get('VideoStreamingPlaylists')
829 for (const p of instance.VideoStreamingPlaylists) {
830 tasks.push(instance.removeStreamingPlaylistFiles(p))
834 // Do not wait video deletion because we could be in a transaction
837 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
844 static stopLiveIfNeeded (instance: VideoModel) {
845 if (!instance.isLive) return
847 logger.info('Stopping live of video %s after video deletion.', instance.uuid)
849 return LiveManager.Instance.stopSessionOf(instance.id)
853 static invalidateCache (instance: VideoModel) {
854 ModelCache.Instance.invalidateCache('video', instance.id)
858 static async saveEssentialDataToAbuses (instance: VideoModel, options) {
859 const tasks: Promise<any>[] = []
861 if (!Array.isArray(instance.VideoAbuses)) {
862 instance.VideoAbuses = await instance.$get('VideoAbuses')
864 if (instance.VideoAbuses.length === 0) return undefined
867 logger.info('Saving video abuses details of video %s.', instance.url)
869 if (!instance.Trackers) instance.Trackers = await instance.$get('Trackers', { transaction: options.transaction })
870 const details = instance.toFormattedDetailsJSON()
872 for (const abuse of instance.VideoAbuses) {
873 abuse.deletedVideo = details
874 tasks.push(abuse.save({ transaction: options.transaction }))
879 logger.error('Some errors when saving details of video %s in its abuses before destroy hook.', instance.uuid, { err })
885 static listLocal (): Promise<MVideo[]> {
892 return VideoModel.findAll(query)
895 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
896 function getRawQuery (select: string) {
897 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
898 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
899 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
900 'WHERE "Account"."actorId" = ' + actorId
901 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
902 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
903 'WHERE "VideoShare"."actorId" = ' + actorId
905 return `(${queryVideo}) UNION (${queryVideoShare})`
908 const rawQuery = getRawQuery('"Video"."id"')
909 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
915 order: getVideoSort('-createdAt', [ 'Tags', 'name', 'ASC' ] as any), // FIXME: sequelize typings
918 [Op.in]: Sequelize.literal('(' + rawQuery + ')')
920 [Op.or]: getPrivaciesForFederation()
924 attributes: [ 'filename', 'language', 'fileUrl' ],
925 model: VideoCaptionModel.unscoped(),
929 attributes: [ 'id', 'url' ],
930 model: VideoShareModel.unscoped(),
932 // We only want videos shared by this actor
947 attributes: [ 'id', 'url' ],
948 model: ActorModel.unscoped()
953 model: VideoChannelModel.unscoped(),
957 attributes: [ 'name' ],
958 model: AccountModel.unscoped(),
962 attributes: [ 'id', 'url', 'followersUrl' ],
963 model: ActorModel.unscoped(),
969 attributes: [ 'id', 'url', 'followersUrl' ],
970 model: ActorModel.unscoped(),
976 model: VideoStreamingPlaylistModel.unscoped(),
980 model: VideoFileModel,
985 VideoLiveModel.unscoped(),
991 return Bluebird.all([
992 VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findAll(query),
993 VideoModel.sequelize.query<{ total: string }>(rawCountQuery, { type: QueryTypes.SELECT })
994 ]).then(([ rows, totals ]) => {
995 // totals: totalVideos + totalVideoShares
997 let totalVideoShares = 0
998 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
999 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
1001 const total = totalVideos + totalVideoShares
1009 static async listPublishedLiveUUIDs () {
1011 attributes: [ 'uuid' ],
1015 state: VideoState.PUBLISHED
1019 const result = await VideoModel.findAll(options)
1021 return result.map(v => v.uuid)
1024 static listUserVideosForApi (options: {
1032 const { accountId, start, count, sort, search, isLive } = options
1034 function buildBaseQuery (): FindOptions {
1035 const where: WhereOptions = {}
1039 [Op.iLike]: '%' + search + '%'
1044 where.isLive = isLive
1051 order: getVideoSort(sort),
1054 model: VideoChannelModel,
1058 model: AccountModel,
1072 const countQuery = buildBaseQuery()
1073 const findQuery = buildBaseQuery()
1075 const findScopes: (string | ScopeOptions)[] = [
1076 ScopeNames.WITH_SCHEDULED_UPDATE,
1077 ScopeNames.WITH_BLACKLISTED,
1078 ScopeNames.WITH_THUMBNAILS
1081 return Promise.all([
1082 VideoModel.count(countQuery),
1083 VideoModel.scope(findScopes).findAll<MVideoForUser>(findQuery)
1084 ]).then(([ count, rows ]) => {
1092 static async listForApi (options: {
1098 filter?: VideoFilter
1101 includeLocalVideos: boolean
1104 categoryOneOf?: number[]
1105 licenceOneOf?: number[]
1106 languageOneOf?: string[]
1107 tagsOneOf?: string[]
1108 tagsAllOf?: string[]
1111 videoChannelId?: number
1113 followerActorId?: number
1115 videoPlaylistId?: number
1117 trendingDays?: number
1119 user?: MUserAccountId
1120 historyOfUser?: MUserId
1122 countVideos?: boolean
1126 if ((options.filter === 'all-local' || options.filter === 'all') && !options.user.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1127 throw new Error('Try to filter all-local but no user has not the see all videos right')
1130 const trendingDays = options.sort.endsWith('trending')
1131 ? CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1133 let trendingAlgorithm
1134 if (options.sort.endsWith('hot')) trendingAlgorithm = 'hot'
1135 if (options.sort.endsWith('best')) trendingAlgorithm = 'best'
1137 const serverActor = await getServerActor()
1139 // followerActorId === null has a meaning, so just check undefined
1140 const followerActorId = options.followerActorId !== undefined
1141 ? options.followerActorId
1144 const queryOptions = {
1145 start: options.start,
1146 count: options.count,
1149 serverAccountId: serverActor.Account.id,
1151 isLive: options.isLive,
1152 categoryOneOf: options.categoryOneOf,
1153 licenceOneOf: options.licenceOneOf,
1154 languageOneOf: options.languageOneOf,
1155 tagsOneOf: options.tagsOneOf,
1156 tagsAllOf: options.tagsAllOf,
1157 filter: options.filter,
1158 withFiles: options.withFiles,
1159 accountId: options.accountId,
1160 videoChannelId: options.videoChannelId,
1161 videoPlaylistId: options.videoPlaylistId,
1162 includeLocalVideos: options.includeLocalVideos,
1164 historyOfUser: options.historyOfUser,
1167 search: options.search
1170 return VideoModel.getAvailableForApi(queryOptions, options.countVideos)
1173 static async searchAndPopulateAccountAndServer (options: {
1174 includeLocalVideos: boolean
1179 startDate?: string // ISO 8601
1180 endDate?: string // ISO 8601
1181 originallyPublishedStartDate?: string
1182 originallyPublishedEndDate?: string
1185 categoryOneOf?: number[]
1186 licenceOneOf?: number[]
1187 languageOneOf?: string[]
1188 tagsOneOf?: string[]
1189 tagsAllOf?: string[]
1190 durationMin?: number // seconds
1191 durationMax?: number // seconds
1192 user?: MUserAccountId
1193 filter?: VideoFilter
1195 const serverActor = await getServerActor()
1197 const queryOptions = {
1198 followerActorId: serverActor.id,
1199 serverAccountId: serverActor.Account.id,
1201 includeLocalVideos: options.includeLocalVideos,
1203 isLive: options.isLive,
1205 categoryOneOf: options.categoryOneOf,
1206 licenceOneOf: options.licenceOneOf,
1207 languageOneOf: options.languageOneOf,
1209 tagsOneOf: options.tagsOneOf,
1210 tagsAllOf: options.tagsAllOf,
1213 filter: options.filter,
1215 start: options.start,
1216 count: options.count,
1219 startDate: options.startDate,
1220 endDate: options.endDate,
1222 originallyPublishedStartDate: options.originallyPublishedStartDate,
1223 originallyPublishedEndDate: options.originallyPublishedEndDate,
1225 durationMin: options.durationMin,
1226 durationMax: options.durationMax,
1228 search: options.search
1231 return VideoModel.getAvailableForApi(queryOptions)
1234 static countLocalLives () {
1240 [Op.ne]: VideoState.LIVE_ENDED
1245 return VideoModel.count(options)
1248 static countVideosUploadedByUserSince (userId: number, since: Date) {
1252 model: VideoChannelModel.unscoped(),
1256 model: AccountModel.unscoped(),
1260 model: UserModel.unscoped(),
1278 return VideoModel.unscoped().count(options)
1281 static countLivesOfAccount (accountId: number) {
1287 [Op.ne]: VideoState.LIVE_ENDED
1293 model: VideoChannelModel.unscoped(),
1301 return VideoModel.count(options)
1304 static load (id: number | string, t?: Transaction): Promise<MVideoThumbnail> {
1305 const where = buildWhereIdOrUUID(id)
1311 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1314 static loadWithBlacklist (id: number | string, t?: Transaction): Promise<MVideoThumbnailBlacklist> {
1315 const where = buildWhereIdOrUUID(id)
1321 return VideoModel.scope([
1322 ScopeNames.WITH_THUMBNAILS,
1323 ScopeNames.WITH_BLACKLISTED
1327 static loadImmutableAttributes (id: number | string, t?: Transaction): Promise<MVideoImmutable> {
1330 where: buildWhereIdOrUUID(id),
1334 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1337 return ModelCache.Instance.doCache({
1338 cacheType: 'load-video-immutable-id',
1345 static loadWithRights (id: number | string, t?: Transaction): Promise<MVideoWithRights> {
1346 const where = buildWhereIdOrUUID(id)
1352 return VideoModel.scope([
1353 ScopeNames.WITH_BLACKLISTED,
1354 ScopeNames.WITH_USER_ID
1358 static loadOnlyId (id: number | string, t?: Transaction): Promise<MVideoIdThumbnail> {
1359 const where = buildWhereIdOrUUID(id)
1362 attributes: [ 'id' ],
1367 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1370 static loadWithFiles (id: number | string, t?: Transaction, logging?: boolean): Promise<MVideoWithAllFiles> {
1371 const where = buildWhereIdOrUUID(id)
1379 return VideoModel.scope([
1380 ScopeNames.WITH_WEBTORRENT_FILES,
1381 ScopeNames.WITH_STREAMING_PLAYLISTS,
1382 ScopeNames.WITH_THUMBNAILS
1386 static loadByUUID (uuid: string): Promise<MVideoThumbnail> {
1393 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1396 static loadByUrl (url: string, transaction?: Transaction): Promise<MVideoThumbnail> {
1397 const query: FindOptions = {
1404 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(query)
1407 static loadByUrlImmutableAttributes (url: string, transaction?: Transaction): Promise<MVideoImmutable> {
1409 const query: FindOptions = {
1416 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1419 return ModelCache.Instance.doCache({
1420 cacheType: 'load-video-immutable-url',
1427 static loadByUrlAndPopulateAccount (url: string, transaction?: Transaction): Promise<MVideoAccountLightBlacklistAllFiles> {
1428 const query: FindOptions = {
1435 return VideoModel.scope([
1436 ScopeNames.WITH_ACCOUNT_DETAILS,
1437 ScopeNames.WITH_WEBTORRENT_FILES,
1438 ScopeNames.WITH_STREAMING_PLAYLISTS,
1439 ScopeNames.WITH_THUMBNAILS,
1440 ScopeNames.WITH_BLACKLISTED
1444 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Transaction, userId?: number): Promise<MVideoFullLight> {
1445 const where = buildWhereIdOrUUID(id)
1448 order: [ [ 'Tags', 'name', 'ASC' ] ] as any,
1453 const scopes: (string | ScopeOptions)[] = [
1454 ScopeNames.WITH_TAGS,
1455 ScopeNames.WITH_BLACKLISTED,
1456 ScopeNames.WITH_ACCOUNT_DETAILS,
1457 ScopeNames.WITH_SCHEDULED_UPDATE,
1458 ScopeNames.WITH_WEBTORRENT_FILES,
1459 ScopeNames.WITH_STREAMING_PLAYLISTS,
1460 ScopeNames.WITH_THUMBNAILS,
1461 ScopeNames.WITH_LIVE
1465 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1473 static loadForGetAPI (parameters: {
1475 transaction?: Transaction
1477 }): Promise<MVideoDetails> {
1478 const { id, transaction, userId } = parameters
1479 const queryBuilder = new VideosModelGetQueryBuilder(VideoModel.sequelize)
1481 return queryBuilder.queryVideos({ id, transaction, forGetAPI: true, userId })
1484 static async getStats () {
1485 const totalLocalVideos = await VideoModel.count({
1491 let totalLocalVideoViews = await VideoModel.sum('views', {
1497 // Sequelize could return null...
1498 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1500 const { total: totalVideos } = await VideoModel.listForApi({
1503 sort: '-publishedAt',
1504 nsfw: buildNSFWFilter(),
1505 includeLocalVideos: true,
1511 totalLocalVideoViews,
1516 static incrementViews (id: number, views: number) {
1517 return VideoModel.increment('views', {
1525 static updateRatesOf (videoId: number, type: VideoRateType, t: Transaction) {
1526 const field = type === 'like'
1530 const rawQuery = `UPDATE "video" SET "${field}" = ` +
1532 'SELECT COUNT(id) FROM "accountVideoRate" WHERE "accountVideoRate"."videoId" = "video"."id" AND type = :rateType' +
1534 'WHERE "video"."id" = :videoId'
1536 return AccountVideoRateModel.sequelize.query(rawQuery, {
1538 replacements: { videoId, rateType: type },
1539 type: QueryTypes.UPDATE
1543 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1544 // Instances only share videos
1545 const query = 'SELECT 1 FROM "videoShare" ' +
1546 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1547 'WHERE "actorFollow"."actorId" = $followerActorId AND "actorFollow"."state" = \'accepted\' AND "videoShare"."videoId" = $videoId ' +
1551 type: QueryTypes.SELECT as QueryTypes.SELECT,
1552 bind: { followerActorId, videoId },
1556 return VideoModel.sequelize.query(query, options)
1557 .then(results => results.length === 1)
1560 static bulkUpdateSupportField (videoChannel: MChannel, t: Transaction) {
1563 channelId: videoChannel.id
1568 return VideoModel.update({ support: videoChannel.support }, options)
1571 static getAllIdsFromChannel (videoChannel: MChannelId): Promise<number[]> {
1573 attributes: [ 'id' ],
1575 channelId: videoChannel.id
1579 return VideoModel.findAll(query)
1580 .then(videos => videos.map(v => v.id))
1583 // threshold corresponds to how many video the field should have to be returned
1584 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1585 const serverActor = await getServerActor()
1586 const followerActorId = serverActor.id
1588 const queryOptions: BuildVideosListQueryOptions = {
1589 attributes: [ `"${field}"` ],
1590 group: `GROUP BY "${field}"`,
1591 having: `HAVING COUNT("${field}") >= ${threshold}`,
1595 serverAccountId: serverActor.Account.id,
1597 includeLocalVideos: true
1600 const queryBuilder = new VideosIdListQueryBuilder(VideoModel.sequelize)
1602 return queryBuilder.queryVideoIds(queryOptions)
1603 .then(rows => rows.map(r => r[field]))
1606 static buildTrendingQuery (trendingDays: number) {
1610 model: VideoViewModel,
1614 [Op.gte]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1620 private static async getAvailableForApi (
1621 options: BuildVideosListQueryOptions,
1623 ): Promise<ResultList<VideoModel>> {
1624 function getCount () {
1625 if (countVideos !== true) return Promise.resolve(undefined)
1627 const countOptions = Object.assign({}, options, { isCount: true })
1628 const queryBuilder = new VideosIdListQueryBuilder(VideoModel.sequelize)
1630 return queryBuilder.countVideoIds(countOptions)
1633 function getModels () {
1634 if (options.count === 0) return Promise.resolve([])
1636 const queryBuilder = new VideosModelListQueryBuilder(VideoModel.sequelize)
1638 return queryBuilder.queryVideos(options)
1641 const [ count, rows ] = await Promise.all([ getCount(), getModels() ])
1649 static getCategoryLabel (id: number) {
1650 return VIDEO_CATEGORIES[id] || 'Misc'
1653 static getLicenceLabel (id: number) {
1654 return VIDEO_LICENCES[id] || 'Unknown'
1657 static getLanguageLabel (id: string) {
1658 return VIDEO_LANGUAGES[id] || 'Unknown'
1661 static getPrivacyLabel (id: number) {
1662 return VIDEO_PRIVACIES[id] || 'Unknown'
1665 static getStateLabel (id: number) {
1666 return VIDEO_STATES[id] || 'Unknown'
1670 return !!this.VideoBlacklist
1674 return this.VideoChannel.Account.Actor.Server?.isBlocked() || this.VideoChannel.Account.isBlocked()
1677 getQualityFileBy<T extends MVideoWithFile> (this: T, fun: (files: MVideoFile[], it: (file: MVideoFile) => number) => MVideoFile) {
1678 // We first transcode to WebTorrent format, so try this array first
1679 if (Array.isArray(this.VideoFiles) && this.VideoFiles.length !== 0) {
1680 const file = fun(this.VideoFiles, file => file.resolution)
1682 return Object.assign(file, { Video: this })
1685 // No webtorrent files, try with streaming playlist files
1686 if (Array.isArray(this.VideoStreamingPlaylists) && this.VideoStreamingPlaylists.length !== 0) {
1687 const streamingPlaylistWithVideo = Object.assign(this.VideoStreamingPlaylists[0], { Video: this })
1689 const file = fun(streamingPlaylistWithVideo.VideoFiles, file => file.resolution)
1690 return Object.assign(file, { VideoStreamingPlaylist: streamingPlaylistWithVideo })
1696 getMaxQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1697 return this.getQualityFileBy(maxBy)
1700 getMinQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1701 return this.getQualityFileBy(minBy)
1704 getWebTorrentFile<T extends MVideoWithFile> (this: T, resolution: number): MVideoFileVideo {
1705 if (Array.isArray(this.VideoFiles) === false) return undefined
1707 const file = this.VideoFiles.find(f => f.resolution === resolution)
1708 if (!file) return undefined
1710 return Object.assign(file, { Video: this })
1713 hasWebTorrentFiles () {
1714 return Array.isArray(this.VideoFiles) === true && this.VideoFiles.length !== 0
1717 async addAndSaveThumbnail (thumbnail: MThumbnail, transaction?: Transaction) {
1718 thumbnail.videoId = this.id
1720 const savedThumbnail = await thumbnail.save({ transaction })
1722 if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = []
1724 // Already have this thumbnail, skip
1725 if (this.Thumbnails.find(t => t.id === savedThumbnail.id)) return
1727 this.Thumbnails.push(savedThumbnail)
1731 if (Array.isArray(this.Thumbnails) === false) return undefined
1733 return this.Thumbnails.find(t => t.type === ThumbnailType.MINIATURE)
1737 return !!this.getPreview()
1741 if (Array.isArray(this.Thumbnails) === false) return undefined
1743 return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW)
1747 return this.remote === false
1750 getWatchStaticPath () {
1751 return '/w/' + this.uuid
1754 getEmbedStaticPath () {
1755 return '/videos/embed/' + this.uuid
1758 getMiniatureStaticPath () {
1759 const thumbnail = this.getMiniature()
1760 if (!thumbnail) return null
1762 return join(STATIC_PATHS.THUMBNAILS, thumbnail.filename)
1765 getPreviewStaticPath () {
1766 const preview = this.getPreview()
1767 if (!preview) return null
1769 // We use a local cache, so specify our cache endpoint instead of potential remote URL
1770 return join(LAZY_STATIC_PATHS.PREVIEWS, preview.filename)
1773 toFormattedJSON (this: MVideoFormattable, options?: VideoFormattingJSONOptions): Video {
1774 return videoModelToFormattedJSON(this, options)
1777 toFormattedDetailsJSON (this: MVideoFormattableDetails): VideoDetails {
1778 return videoModelToFormattedDetailsJSON(this)
1781 getFormattedVideoFilesJSON (includeMagnet = true): VideoFile[] {
1782 let files: VideoFile[] = []
1784 if (Array.isArray(this.VideoFiles)) {
1785 const result = videoFilesModelToFormattedJSON(this, this.VideoFiles, includeMagnet)
1786 files = files.concat(result)
1789 for (const p of (this.VideoStreamingPlaylists || [])) {
1790 const result = videoFilesModelToFormattedJSON(this, p.VideoFiles, includeMagnet)
1791 files = files.concat(result)
1797 toActivityPubObject (this: MVideoAP): VideoObject {
1798 return videoModelToActivityPubObject(this)
1801 getTruncatedDescription () {
1802 if (!this.description) return null
1804 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1805 return peertubeTruncate(this.description, { length: maxLength })
1808 getMaxQualityResolution () {
1809 const file = this.getMaxQualityFile()
1810 const videoOrPlaylist = file.getVideoOrStreamingPlaylist()
1811 const originalFilePath = getVideoFilePath(videoOrPlaylist, file)
1813 return getVideoFileResolution(originalFilePath)
1816 getDescriptionAPIPath () {
1817 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1820 getHLSPlaylist (): MStreamingPlaylistFilesVideo {
1821 if (!this.VideoStreamingPlaylists) return undefined
1823 const playlist = this.VideoStreamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
1824 playlist.Video = this
1829 setHLSPlaylist (playlist: MStreamingPlaylist) {
1830 const toAdd = [ playlist ] as [ VideoStreamingPlaylistModel ]
1832 if (Array.isArray(this.VideoStreamingPlaylists) === false || this.VideoStreamingPlaylists.length === 0) {
1833 this.VideoStreamingPlaylists = toAdd
1837 this.VideoStreamingPlaylists = this.VideoStreamingPlaylists
1838 .filter(s => s.type !== VideoStreamingPlaylistType.HLS)
1842 removeFile (videoFile: MVideoFile, isRedundancy = false) {
1843 const filePath = getVideoFilePath(this, videoFile, isRedundancy)
1844 return remove(filePath)
1845 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1848 async removeStreamingPlaylistFiles (streamingPlaylist: MStreamingPlaylist, isRedundancy = false) {
1849 const directoryPath = getHLSDirectory(this, isRedundancy)
1851 await remove(directoryPath)
1853 if (isRedundancy !== true) {
1854 const streamingPlaylistWithFiles = streamingPlaylist as MStreamingPlaylistFilesVideo
1855 streamingPlaylistWithFiles.Video = this
1857 if (!Array.isArray(streamingPlaylistWithFiles.VideoFiles)) {
1858 streamingPlaylistWithFiles.VideoFiles = await streamingPlaylistWithFiles.$get('VideoFiles')
1861 // Remove physical files and torrents
1863 streamingPlaylistWithFiles.VideoFiles.map(file => file.removeTorrent())
1869 if (this.isOwned()) return false
1871 return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)
1874 hasPrivacyForFederation () {
1875 return isPrivacyForFederation(this.privacy)
1878 hasStateForFederation () {
1879 return isStateForFederation(this.state)
1882 isNewVideo (newPrivacy: VideoPrivacy) {
1883 return this.hasPrivacyForFederation() === false && isPrivacyForFederation(newPrivacy) === true
1887 return setAsUpdated('video', this.id)
1891 return this.privacy === VideoPrivacy.PRIVATE || this.privacy === VideoPrivacy.INTERNAL || !!this.VideoBlacklist
1894 setPrivacy (newPrivacy: VideoPrivacy) {
1895 if (this.privacy === VideoPrivacy.PRIVATE && newPrivacy !== VideoPrivacy.PRIVATE) {
1896 this.publishedAt = new Date()
1899 this.privacy = newPrivacy
1903 return this.privacy === VideoPrivacy.PRIVATE ||
1904 this.privacy === VideoPrivacy.UNLISTED ||
1905 this.privacy === VideoPrivacy.INTERNAL
1908 async publishIfNeededAndSave (t: Transaction) {
1909 if (this.state !== VideoState.PUBLISHED) {
1910 this.state = VideoState.PUBLISHED
1911 this.publishedAt = new Date()
1912 await this.save({ transaction: t })
1920 getBandwidthBits (videoFile: MVideoFile) {
1921 return Math.ceil((videoFile.size * 8) / this.duration)
1925 if (this.isOwned()) {
1927 WEBSERVER.URL + '/tracker/announce',
1928 WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT + '/tracker/socket'
1932 return this.Trackers.map(t => t.url)