1 import * as Bluebird from 'bluebird'
2 import { remove } from 'fs-extra'
3 import { maxBy, minBy, pick } from 'lodash'
4 import { join } from 'path'
5 import { FindOptions, Includeable, IncludeOptions, Op, QueryTypes, ScopeOptions, Sequelize, Transaction, WhereOptions } from 'sequelize'
26 } from 'sequelize-typescript'
27 import { buildNSFWFilter } from '@server/helpers/express-utils'
28 import { getPrivaciesForFederation, isPrivacyForFederation, isStateForFederation } from '@server/helpers/video'
29 import { LiveManager } from '@server/lib/live-manager'
30 import { getHLSDirectory, getTorrentFileName, getTorrentFilePath, getVideoFilename, getVideoFilePath } from '@server/lib/video-paths'
31 import { getServerActor } from '@server/models/application/application'
32 import { ModelCache } from '@server/models/model-cache'
33 import { VideoFile } from '@shared/models/videos/video-file.model'
34 import { ResultList, UserRight, VideoPrivacy, VideoState } from '../../../shared'
35 import { VideoObject } from '../../../shared/models/activitypub/objects'
36 import { Video, VideoDetails } from '../../../shared/models/videos'
37 import { ThumbnailType } from '../../../shared/models/videos/thumbnail.type'
38 import { VideoFilter } from '../../../shared/models/videos/video-query.type'
39 import { VideoStreamingPlaylistType } from '../../../shared/models/videos/video-streaming-playlist.type'
40 import { peertubeTruncate } from '../../helpers/core-utils'
41 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
42 import { isBooleanValid } from '../../helpers/custom-validators/misc'
45 isVideoDescriptionValid,
53 } from '../../helpers/custom-validators/videos'
54 import { getVideoFileResolution } from '../../helpers/ffprobe-utils'
55 import { logger } from '../../helpers/logger'
56 import { CONFIG } from '../../initializers/config'
63 STATIC_DOWNLOAD_PATHS,
71 } from '../../initializers/constants'
72 import { sendDeleteVideo } from '../../lib/activitypub/send'
75 MChannelAccountDefault,
78 MStreamingPlaylistFilesVideo,
82 MVideoAccountLightBlacklistAllFiles,
87 MVideoFormattableDetails,
93 MVideoThumbnailBlacklist,
97 } from '../../types/models'
98 import { MThumbnail } from '../../types/models/video/thumbnail'
99 import { MVideoFile, 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 { buildTrigramSearchIndex, buildWhereIdOrUUID, getVideoSort, isOutdated, throwIfNotValid } from '../utils'
110 import { ScheduleVideoUpdateModel } from './schedule-video-update'
111 import { TagModel } from './tag'
112 import { ThumbnailModel } from './thumbnail'
113 import { VideoBlacklistModel } from './video-blacklist'
114 import { VideoCaptionModel } from './video-caption'
115 import { ScopeNames as VideoChannelScopeNames, SummaryOptions, VideoChannelModel } from './video-channel'
116 import { VideoCommentModel } from './video-comment'
117 import { VideoFileModel } from './video-file'
119 videoFilesModelToFormattedJSON,
120 VideoFormattingJSONOptions,
121 videoModelToActivityPubObject,
122 videoModelToFormattedDetailsJSON,
123 videoModelToFormattedJSON
124 } from './video-format-utils'
125 import { VideoImportModel } from './video-import'
126 import { VideoLiveModel } from './video-live'
127 import { VideoPlaylistElementModel } from './video-playlist-element'
128 import { buildListQuery, BuildVideosQueryOptions, wrapForAPIResults } from './video-query-builder'
129 import { VideoShareModel } from './video-share'
130 import { VideoStreamingPlaylistModel } from './video-streaming-playlist'
131 import { VideoTagModel } from './video-tag'
132 import { VideoViewModel } from './video-view'
134 export enum ScopeNames {
135 AVAILABLE_FOR_LIST_IDS = 'AVAILABLE_FOR_LIST_IDS',
137 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
138 WITH_TAGS = 'WITH_TAGS',
139 WITH_WEBTORRENT_FILES = 'WITH_WEBTORRENT_FILES',
140 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
141 WITH_BLACKLISTED = 'WITH_BLACKLISTED',
142 WITH_USER_HISTORY = 'WITH_USER_HISTORY',
143 WITH_STREAMING_PLAYLISTS = 'WITH_STREAMING_PLAYLISTS',
144 WITH_USER_ID = 'WITH_USER_ID',
145 WITH_IMMUTABLE_ATTRIBUTES = 'WITH_IMMUTABLE_ATTRIBUTES',
146 WITH_THUMBNAILS = 'WITH_THUMBNAILS',
147 WITH_LIVE = 'WITH_LIVE'
150 export type ForAPIOptions = {
153 videoPlaylistId?: number
155 withAccountBlockerIds?: number[]
158 export type AvailableForListIDsOptions = {
159 serverAccountId: number
160 followerActorId: number
161 includeLocalVideos: boolean
163 attributesType?: 'none' | 'id' | 'all'
166 categoryOneOf?: number[]
168 licenceOneOf?: number[]
169 languageOneOf?: string[]
176 videoChannelId?: number
178 videoPlaylistId?: number
180 trendingDays?: number
181 user?: MUserAccountId
182 historyOfUser?: MUserId
184 baseWhere?: WhereOptions[]
188 [ScopeNames.WITH_IMMUTABLE_ATTRIBUTES]: {
189 attributes: [ 'id', 'url', 'uuid', 'remote' ]
191 [ScopeNames.FOR_API]: (options: ForAPIOptions) => {
192 const include: Includeable[] = [
194 model: VideoChannelModel.scope({
196 VideoChannelScopeNames.SUMMARY, {
198 withAccountBlockerIds: options.withAccountBlockerIds
205 attributes: [ 'type', 'filename' ],
206 model: ThumbnailModel,
211 const query: FindOptions = {}
221 if (options.videoPlaylistId) {
223 model: VideoPlaylistElementModel.unscoped(),
226 videoPlaylistId: options.videoPlaylistId
231 query.include = include
235 [ScopeNames.WITH_THUMBNAILS]: {
238 model: ThumbnailModel,
243 [ScopeNames.WITH_LIVE]: {
246 model: VideoLiveModel.unscoped(),
251 [ScopeNames.WITH_USER_ID]: {
254 attributes: [ 'accountId' ],
255 model: VideoChannelModel.unscoped(),
259 attributes: [ 'userId' ],
260 model: AccountModel.unscoped(),
267 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
270 model: VideoChannelModel.unscoped(),
275 exclude: [ 'privateKey', 'publicKey' ]
277 model: ActorModel.unscoped(),
281 attributes: [ 'host' ],
282 model: ServerModel.unscoped(),
286 model: AvatarModel.unscoped(),
292 model: AccountModel.unscoped(),
296 model: ActorModel.unscoped(),
298 exclude: [ 'privateKey', 'publicKey' ]
303 attributes: [ 'host' ],
304 model: ServerModel.unscoped(),
308 model: AvatarModel.unscoped(),
319 [ScopeNames.WITH_TAGS]: {
320 include: [ TagModel ]
322 [ScopeNames.WITH_BLACKLISTED]: {
325 attributes: [ 'id', 'reason', 'unfederated' ],
326 model: VideoBlacklistModel,
331 [ScopeNames.WITH_WEBTORRENT_FILES]: (withRedundancies = false) => {
332 let subInclude: any[] = []
334 if (withRedundancies === true) {
337 attributes: [ 'fileUrl' ],
338 model: VideoRedundancyModel.unscoped(),
347 model: VideoFileModel,
348 separate: true, // We may have multiple files, having multiple redundancies so let's separate this join
355 [ScopeNames.WITH_STREAMING_PLAYLISTS]: (withRedundancies = false) => {
356 const subInclude: IncludeOptions[] = [
358 model: VideoFileModel,
363 if (withRedundancies === true) {
365 attributes: [ 'fileUrl' ],
366 model: VideoRedundancyModel.unscoped(),
374 model: VideoStreamingPlaylistModel.unscoped(),
375 separate: true, // We may have multiple streaming playlists, having multiple redundancies so let's separate this join
382 [ScopeNames.WITH_SCHEDULED_UPDATE]: {
385 model: ScheduleVideoUpdateModel.unscoped(),
390 [ScopeNames.WITH_USER_HISTORY]: (userId: number) => {
394 attributes: [ 'currentTime' ],
395 model: UserVideoHistoryModel.unscoped(),
408 buildTrigramSearchIndex('video_name_trigram', 'name'),
410 { fields: [ 'createdAt' ] },
413 { name: 'publishedAt', order: 'DESC' },
414 { name: 'id', order: 'ASC' }
417 { fields: [ 'duration' ] },
418 { fields: [ 'views' ] },
419 { fields: [ 'channelId' ] },
421 fields: [ 'originallyPublishedAt' ],
423 originallyPublishedAt: {
429 fields: [ 'category' ], // We don't care videos with an unknown category
437 fields: [ 'licence' ], // We don't care videos with an unknown licence
445 fields: [ 'language' ], // We don't care videos with an unknown language
453 fields: [ 'nsfw' ], // Most of the videos are not NSFW
459 fields: [ 'remote' ], // Only index local videos
474 export class VideoModel extends Model {
477 @Default(DataType.UUIDV4)
479 @Column(DataType.UUID)
483 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
489 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category', true))
495 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence', true))
501 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language', true))
502 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
506 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
508 privacy: VideoPrivacy
511 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
517 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description', true))
518 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
523 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support', true))
524 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
528 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
563 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
564 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
569 commentsEnabled: boolean
573 downloadEnabled: boolean
577 waitTranscoding: boolean
581 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
592 @Default(DataType.NOW)
599 originallyPublishedAt: Date
601 @ForeignKey(() => VideoChannelModel)
605 @BelongsTo(() => VideoChannelModel, {
611 VideoChannel: VideoChannelModel
613 @BelongsToMany(() => TagModel, {
614 foreignKey: 'videoId',
615 through: () => VideoTagModel,
620 @HasMany(() => ThumbnailModel, {
628 Thumbnails: ThumbnailModel[]
630 @HasMany(() => VideoPlaylistElementModel, {
637 VideoPlaylistElements: VideoPlaylistElementModel[]
639 @HasMany(() => VideoAbuseModel, {
646 VideoAbuses: VideoAbuseModel[]
648 @HasMany(() => VideoFileModel, {
656 VideoFiles: VideoFileModel[]
658 @HasMany(() => VideoStreamingPlaylistModel, {
666 VideoStreamingPlaylists: VideoStreamingPlaylistModel[]
668 @HasMany(() => VideoShareModel, {
675 VideoShares: VideoShareModel[]
677 @HasMany(() => AccountVideoRateModel, {
684 AccountVideoRates: AccountVideoRateModel[]
686 @HasMany(() => VideoCommentModel, {
694 VideoComments: VideoCommentModel[]
696 @HasMany(() => VideoViewModel, {
703 VideoViews: VideoViewModel[]
705 @HasMany(() => UserVideoHistoryModel, {
712 UserVideoHistories: UserVideoHistoryModel[]
714 @HasOne(() => ScheduleVideoUpdateModel, {
721 ScheduleVideoUpdate: ScheduleVideoUpdateModel
723 @HasOne(() => VideoBlacklistModel, {
730 VideoBlacklist: VideoBlacklistModel
732 @HasOne(() => VideoLiveModel, {
739 VideoLive: VideoLiveModel
741 @HasOne(() => VideoImportModel, {
748 VideoImport: VideoImportModel
750 @HasMany(() => VideoCaptionModel, {
757 ['separate' as any]: true
759 VideoCaptions: VideoCaptionModel[]
762 static async sendDelete (instance: MVideoAccountLight, options) {
763 if (instance.isOwned()) {
764 if (!instance.VideoChannel) {
765 instance.VideoChannel = await instance.$get('VideoChannel', {
770 transaction: options.transaction
771 }) as MChannelAccountDefault
774 return sendDeleteVideo(instance, options.transaction)
781 static async removeFiles (instance: VideoModel) {
782 const tasks: Promise<any>[] = []
784 logger.info('Removing files of video %s.', instance.url)
786 if (instance.isOwned()) {
787 if (!Array.isArray(instance.VideoFiles)) {
788 instance.VideoFiles = await instance.$get('VideoFiles')
791 // Remove physical files and torrents
792 instance.VideoFiles.forEach(file => {
793 tasks.push(instance.removeFile(file))
794 tasks.push(instance.removeTorrent(file))
797 // Remove playlists file
798 if (!Array.isArray(instance.VideoStreamingPlaylists)) {
799 instance.VideoStreamingPlaylists = await instance.$get('VideoStreamingPlaylists')
802 for (const p of instance.VideoStreamingPlaylists) {
803 tasks.push(instance.removeStreamingPlaylistFiles(p))
807 // Do not wait video deletion because we could be in a transaction
810 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
817 static stopLiveIfNeeded (instance: VideoModel) {
818 if (!instance.isLive) return
820 logger.info('Stopping live of video %s after video deletion.', instance.uuid)
822 return LiveManager.Instance.stopSessionOf(instance.id)
826 static invalidateCache (instance: VideoModel) {
827 ModelCache.Instance.invalidateCache('video', instance.id)
831 static async saveEssentialDataToAbuses (instance: VideoModel, options) {
832 const tasks: Promise<any>[] = []
834 if (!Array.isArray(instance.VideoAbuses)) {
835 instance.VideoAbuses = await instance.$get('VideoAbuses')
837 if (instance.VideoAbuses.length === 0) return undefined
840 logger.info('Saving video abuses details of video %s.', instance.url)
842 const details = instance.toFormattedDetailsJSON()
844 for (const abuse of instance.VideoAbuses) {
845 abuse.deletedVideo = details
846 tasks.push(abuse.save({ transaction: options.transaction }))
851 logger.error('Some errors when saving details of video %s in its abuses before destroy hook.', instance.uuid, { err })
857 static listLocal (): Promise<MVideoWithAllFiles[]> {
864 return VideoModel.scope([
865 ScopeNames.WITH_WEBTORRENT_FILES,
866 ScopeNames.WITH_STREAMING_PLAYLISTS,
867 ScopeNames.WITH_THUMBNAILS
871 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
872 function getRawQuery (select: string) {
873 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
874 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
875 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
876 'WHERE "Account"."actorId" = ' + actorId
877 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
878 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
879 'WHERE "VideoShare"."actorId" = ' + actorId
881 return `(${queryVideo}) UNION (${queryVideoShare})`
884 const rawQuery = getRawQuery('"Video"."id"')
885 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
891 order: getVideoSort('-createdAt', [ 'Tags', 'name', 'ASC' ] as any), // FIXME: sequelize typings
894 [Op.in]: Sequelize.literal('(' + rawQuery + ')')
896 [Op.or]: getPrivaciesForFederation()
900 attributes: [ 'language', 'fileUrl' ],
901 model: VideoCaptionModel.unscoped(),
905 attributes: [ 'id', 'url' ],
906 model: VideoShareModel.unscoped(),
908 // We only want videos shared by this actor
923 attributes: [ 'id', 'url' ],
924 model: ActorModel.unscoped()
929 model: VideoChannelModel.unscoped(),
933 attributes: [ 'name' ],
934 model: AccountModel.unscoped(),
938 attributes: [ 'id', 'url', 'followersUrl' ],
939 model: ActorModel.unscoped(),
945 attributes: [ 'id', 'url', 'followersUrl' ],
946 model: ActorModel.unscoped(),
952 model: VideoStreamingPlaylistModel.unscoped(),
956 model: VideoFileModel,
961 VideoLiveModel.unscoped(),
967 return Bluebird.all([
968 VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findAll(query),
969 VideoModel.sequelize.query<{ total: string }>(rawCountQuery, { type: QueryTypes.SELECT })
970 ]).then(([ rows, totals ]) => {
971 // totals: totalVideos + totalVideoShares
973 let totalVideoShares = 0
974 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
975 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
977 const total = totalVideos + totalVideoShares
985 static async listPublishedLiveIds () {
987 attributes: [ 'id' ],
990 state: VideoState.PUBLISHED
994 const result = await VideoModel.findAll(options)
996 return result.map(v => v.id)
999 static listUserVideosForApi (options: {
1006 const { accountId, start, count, sort, search } = options
1008 function buildBaseQuery (): FindOptions {
1012 order: getVideoSort(sort),
1015 model: VideoChannelModel,
1019 model: AccountModel,
1031 baseQuery = Object.assign(baseQuery, {
1034 [Op.iLike]: '%' + search + '%'
1043 const countQuery = buildBaseQuery()
1044 const findQuery = buildBaseQuery()
1046 const findScopes: (string | ScopeOptions)[] = [
1047 ScopeNames.WITH_SCHEDULED_UPDATE,
1048 ScopeNames.WITH_BLACKLISTED,
1049 ScopeNames.WITH_THUMBNAILS
1052 return Promise.all([
1053 VideoModel.count(countQuery),
1054 VideoModel.scope(findScopes).findAll<MVideoForUser>(findQuery)
1055 ]).then(([ count, rows ]) => {
1063 static async listForApi (options: {
1068 includeLocalVideos: boolean
1070 categoryOneOf?: number[]
1071 licenceOneOf?: number[]
1072 languageOneOf?: string[]
1073 tagsOneOf?: string[]
1074 tagsAllOf?: string[]
1075 filter?: VideoFilter
1077 videoChannelId?: number
1078 followerActorId?: number
1079 videoPlaylistId?: number
1080 trendingDays?: number
1081 user?: MUserAccountId
1082 historyOfUser?: MUserId
1083 countVideos?: boolean
1086 if ((options.filter === 'all-local' || options.filter === 'all') && !options.user.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1087 throw new Error('Try to filter all-local but no user has not the see all videos right')
1090 const trendingDays = options.sort.endsWith('trending')
1091 ? CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1093 const hot = options.sort.endsWith('hot')
1095 const serverActor = await getServerActor()
1097 // followerActorId === null has a meaning, so just check undefined
1098 const followerActorId = options.followerActorId !== undefined
1099 ? options.followerActorId
1102 const queryOptions = {
1103 start: options.start,
1104 count: options.count,
1107 serverAccountId: serverActor.Account.id,
1109 categoryOneOf: options.categoryOneOf,
1110 licenceOneOf: options.licenceOneOf,
1111 languageOneOf: options.languageOneOf,
1112 tagsOneOf: options.tagsOneOf,
1113 tagsAllOf: options.tagsAllOf,
1114 filter: options.filter,
1115 withFiles: options.withFiles,
1116 accountId: options.accountId,
1117 videoChannelId: options.videoChannelId,
1118 videoPlaylistId: options.videoPlaylistId,
1119 includeLocalVideos: options.includeLocalVideos,
1121 historyOfUser: options.historyOfUser,
1124 search: options.search
1127 return VideoModel.getAvailableForApi(queryOptions, options.countVideos)
1130 static async searchAndPopulateAccountAndServer (options: {
1131 includeLocalVideos: boolean
1136 startDate?: string // ISO 8601
1137 endDate?: string // ISO 8601
1138 originallyPublishedStartDate?: string
1139 originallyPublishedEndDate?: string
1141 categoryOneOf?: number[]
1142 licenceOneOf?: number[]
1143 languageOneOf?: string[]
1144 tagsOneOf?: string[]
1145 tagsAllOf?: string[]
1146 durationMin?: number // seconds
1147 durationMax?: number // seconds
1148 user?: MUserAccountId
1149 filter?: VideoFilter
1151 const serverActor = await getServerActor()
1152 const queryOptions = {
1153 followerActorId: serverActor.id,
1154 serverAccountId: serverActor.Account.id,
1155 includeLocalVideos: options.includeLocalVideos,
1157 categoryOneOf: options.categoryOneOf,
1158 licenceOneOf: options.licenceOneOf,
1159 languageOneOf: options.languageOneOf,
1160 tagsOneOf: options.tagsOneOf,
1161 tagsAllOf: options.tagsAllOf,
1163 filter: options.filter,
1164 start: options.start,
1165 count: options.count,
1167 startDate: options.startDate,
1168 endDate: options.endDate,
1169 originallyPublishedStartDate: options.originallyPublishedStartDate,
1170 originallyPublishedEndDate: options.originallyPublishedEndDate,
1172 durationMin: options.durationMin,
1173 durationMax: options.durationMax,
1175 search: options.search
1178 return VideoModel.getAvailableForApi(queryOptions)
1181 static countLocalLives () {
1187 [Op.ne]: VideoState.LIVE_ENDED
1192 return VideoModel.count(options)
1195 static countVideosUploadedByUserSince (userId: number, since: Date) {
1199 model: VideoChannelModel.unscoped(),
1203 model: AccountModel.unscoped(),
1207 model: UserModel.unscoped(),
1225 return VideoModel.unscoped().count(options)
1228 static countLivesOfAccount (accountId: number) {
1234 [Op.ne]: VideoState.LIVE_ENDED
1240 model: VideoChannelModel.unscoped(),
1248 return VideoModel.count(options)
1251 static load (id: number | string, t?: Transaction): Promise<MVideoThumbnail> {
1252 const where = buildWhereIdOrUUID(id)
1258 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1261 static loadWithBlacklist (id: number | string, t?: Transaction): Promise<MVideoThumbnailBlacklist> {
1262 const where = buildWhereIdOrUUID(id)
1268 return VideoModel.scope([
1269 ScopeNames.WITH_THUMBNAILS,
1270 ScopeNames.WITH_BLACKLISTED
1274 static loadImmutableAttributes (id: number | string, t?: Transaction): Promise<MVideoImmutable> {
1277 where: buildWhereIdOrUUID(id),
1281 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1284 return ModelCache.Instance.doCache({
1285 cacheType: 'load-video-immutable-id',
1292 static loadWithRights (id: number | string, t?: Transaction): Promise<MVideoWithRights> {
1293 const where = buildWhereIdOrUUID(id)
1299 return VideoModel.scope([
1300 ScopeNames.WITH_BLACKLISTED,
1301 ScopeNames.WITH_USER_ID,
1302 ScopeNames.WITH_THUMBNAILS
1306 static loadOnlyId (id: number | string, t?: Transaction): Promise<MVideoIdThumbnail> {
1307 const where = buildWhereIdOrUUID(id)
1310 attributes: [ 'id' ],
1315 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1318 static loadWithFiles (id: number | string, t?: Transaction, logging?: boolean): Promise<MVideoWithAllFiles> {
1319 const where = buildWhereIdOrUUID(id)
1327 return VideoModel.scope([
1328 ScopeNames.WITH_WEBTORRENT_FILES,
1329 ScopeNames.WITH_STREAMING_PLAYLISTS,
1330 ScopeNames.WITH_THUMBNAILS
1334 static loadByUUID (uuid: string): Promise<MVideoThumbnail> {
1341 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1344 static loadByUrl (url: string, transaction?: Transaction): Promise<MVideoThumbnail> {
1345 const query: FindOptions = {
1352 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(query)
1355 static loadByUrlImmutableAttributes (url: string, transaction?: Transaction): Promise<MVideoImmutable> {
1357 const query: FindOptions = {
1364 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1367 return ModelCache.Instance.doCache({
1368 cacheType: 'load-video-immutable-url',
1375 static loadByUrlAndPopulateAccount (url: string, transaction?: Transaction): Promise<MVideoAccountLightBlacklistAllFiles> {
1376 const query: FindOptions = {
1383 return VideoModel.scope([
1384 ScopeNames.WITH_ACCOUNT_DETAILS,
1385 ScopeNames.WITH_WEBTORRENT_FILES,
1386 ScopeNames.WITH_STREAMING_PLAYLISTS,
1387 ScopeNames.WITH_THUMBNAILS,
1388 ScopeNames.WITH_BLACKLISTED
1392 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Transaction, userId?: number): Promise<MVideoFullLight> {
1393 const where = buildWhereIdOrUUID(id)
1396 order: [ [ 'Tags', 'name', 'ASC' ] ] as any,
1401 const scopes: (string | ScopeOptions)[] = [
1402 ScopeNames.WITH_TAGS,
1403 ScopeNames.WITH_BLACKLISTED,
1404 ScopeNames.WITH_ACCOUNT_DETAILS,
1405 ScopeNames.WITH_SCHEDULED_UPDATE,
1406 ScopeNames.WITH_WEBTORRENT_FILES,
1407 ScopeNames.WITH_STREAMING_PLAYLISTS,
1408 ScopeNames.WITH_THUMBNAILS,
1409 ScopeNames.WITH_LIVE
1413 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1421 static loadForGetAPI (parameters: {
1425 }): Promise<MVideoDetails> {
1426 const { id, t, userId } = parameters
1427 const where = buildWhereIdOrUUID(id)
1430 order: [ [ 'Tags', 'name', 'ASC' ] ] as any, // FIXME: sequelize typings
1435 const scopes: (string | ScopeOptions)[] = [
1436 ScopeNames.WITH_TAGS,
1437 ScopeNames.WITH_BLACKLISTED,
1438 ScopeNames.WITH_ACCOUNT_DETAILS,
1439 ScopeNames.WITH_SCHEDULED_UPDATE,
1440 ScopeNames.WITH_THUMBNAILS,
1441 ScopeNames.WITH_LIVE,
1442 { method: [ ScopeNames.WITH_WEBTORRENT_FILES, true ] },
1443 { method: [ ScopeNames.WITH_STREAMING_PLAYLISTS, true ] }
1447 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1455 static async getStats () {
1456 const totalLocalVideos = await VideoModel.count({
1462 let totalLocalVideoViews = await VideoModel.sum('views', {
1468 // Sequelize could return null...
1469 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1471 const { total: totalVideos } = await VideoModel.listForApi({
1474 sort: '-publishedAt',
1475 nsfw: buildNSFWFilter(),
1476 includeLocalVideos: true,
1482 totalLocalVideoViews,
1487 static incrementViews (id: number, views: number) {
1488 return VideoModel.increment('views', {
1496 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1497 // Instances only share videos
1498 const query = 'SELECT 1 FROM "videoShare" ' +
1499 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1500 'WHERE "actorFollow"."actorId" = $followerActorId AND "actorFollow"."state" = \'accepted\' AND "videoShare"."videoId" = $videoId ' +
1504 type: QueryTypes.SELECT as QueryTypes.SELECT,
1505 bind: { followerActorId, videoId },
1509 return VideoModel.sequelize.query(query, options)
1510 .then(results => results.length === 1)
1513 static bulkUpdateSupportField (videoChannel: MChannel, t: Transaction) {
1516 channelId: videoChannel.id
1521 return VideoModel.update({ support: videoChannel.support }, options)
1524 static getAllIdsFromChannel (videoChannel: MChannelId): Promise<number[]> {
1526 attributes: [ 'id' ],
1528 channelId: videoChannel.id
1532 return VideoModel.findAll(query)
1533 .then(videos => videos.map(v => v.id))
1536 // threshold corresponds to how many video the field should have to be returned
1537 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1538 const serverActor = await getServerActor()
1539 const followerActorId = serverActor.id
1541 const queryOptions: BuildVideosQueryOptions = {
1542 attributes: [ `"${field}"` ],
1543 group: `GROUP BY "${field}"`,
1544 having: `HAVING COUNT("${field}") >= ${threshold}`,
1548 serverAccountId: serverActor.Account.id,
1550 includeLocalVideos: true
1553 const { query, replacements } = buildListQuery(VideoModel, queryOptions)
1555 return this.sequelize.query<any>(query, { replacements, type: QueryTypes.SELECT })
1556 .then(rows => rows.map(r => r[field]))
1559 static buildTrendingQuery (trendingDays: number) {
1563 model: VideoViewModel,
1567 [Op.gte]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1573 private static async getAvailableForApi (
1574 options: BuildVideosQueryOptions,
1576 ): Promise<ResultList<VideoModel>> {
1577 function getCount () {
1578 if (countVideos !== true) return Promise.resolve(undefined)
1580 const countOptions = Object.assign({}, options, { isCount: true })
1581 const { query: queryCount, replacements: replacementsCount } = buildListQuery(VideoModel, countOptions)
1583 return VideoModel.sequelize.query<any>(queryCount, { replacements: replacementsCount, type: QueryTypes.SELECT })
1584 .then(rows => rows.length !== 0 ? rows[0].total : 0)
1587 function getModels () {
1588 if (options.count === 0) return Promise.resolve([])
1590 const { query, replacements, order } = buildListQuery(VideoModel, options)
1591 const queryModels = wrapForAPIResults(query, replacements, options, order)
1593 return VideoModel.sequelize.query<any>(queryModels, { replacements, type: QueryTypes.SELECT, nest: true })
1594 .then(rows => VideoModel.buildAPIResult(rows))
1597 const [ count, rows ] = await Promise.all([ getCount(), getModels() ])
1605 private static buildAPIResult (rows: any[]) {
1606 const videosMemo: { [ id: number ]: VideoModel } = {}
1607 const videoStreamingPlaylistMemo: { [ id: number ]: VideoStreamingPlaylistModel } = {}
1609 const thumbnailsDone = new Set<number>()
1610 const historyDone = new Set<number>()
1611 const videoFilesDone = new Set<number>()
1613 const videos: VideoModel[] = []
1615 const avatarKeys = [ 'id', 'filename', 'fileUrl', 'onDisk', 'createdAt', 'updatedAt' ]
1616 const actorKeys = [ 'id', 'preferredUsername', 'url', 'serverId', 'avatarId' ]
1617 const serverKeys = [ 'id', 'host' ]
1618 const videoFileKeys = [
1628 'videoStreamingPlaylistId'
1630 const videoStreamingPlaylistKeys = [ 'id', 'type', 'playlistUrl' ]
1654 'originallyPublishedAt',
1660 function buildActor (rowActor: any) {
1661 const avatarModel = rowActor.Avatar.id !== null
1662 ? new AvatarModel(pick(rowActor.Avatar, avatarKeys))
1665 const serverModel = rowActor.Server.id !== null
1666 ? new ServerModel(pick(rowActor.Server, serverKeys))
1669 const actorModel = new ActorModel(pick(rowActor, actorKeys))
1670 actorModel.Avatar = avatarModel
1671 actorModel.Server = serverModel
1676 for (const row of rows) {
1677 if (!videosMemo[row.id]) {
1679 const channel = row.VideoChannel
1680 const channelModel = new VideoChannelModel(pick(channel, [ 'id', 'name', 'description', 'actorId' ]))
1681 channelModel.Actor = buildActor(channel.Actor)
1683 const account = row.VideoChannel.Account
1684 const accountModel = new AccountModel(pick(account, [ 'id', 'name' ]))
1685 accountModel.Actor = buildActor(account.Actor)
1687 channelModel.Account = accountModel
1689 const videoModel = new VideoModel(pick(row, videoKeys))
1690 videoModel.VideoChannel = channelModel
1692 videoModel.UserVideoHistories = []
1693 videoModel.Thumbnails = []
1694 videoModel.VideoFiles = []
1695 videoModel.VideoStreamingPlaylists = []
1697 videosMemo[row.id] = videoModel
1698 // Don't take object value to have a sorted array
1699 videos.push(videoModel)
1702 const videoModel = videosMemo[row.id]
1704 if (row.userVideoHistory?.id && !historyDone.has(row.userVideoHistory.id)) {
1705 const historyModel = new UserVideoHistoryModel(pick(row.userVideoHistory, [ 'id', 'currentTime' ]))
1706 videoModel.UserVideoHistories.push(historyModel)
1708 historyDone.add(row.userVideoHistory.id)
1711 if (row.Thumbnails?.id && !thumbnailsDone.has(row.Thumbnails.id)) {
1712 const thumbnailModel = new ThumbnailModel(pick(row.Thumbnails, [ 'id', 'type', 'filename' ]))
1713 videoModel.Thumbnails.push(thumbnailModel)
1715 thumbnailsDone.add(row.Thumbnails.id)
1718 if (row.VideoFiles?.id && !videoFilesDone.has(row.VideoFiles.id)) {
1719 const videoFileModel = new VideoFileModel(pick(row.VideoFiles, videoFileKeys))
1720 videoModel.VideoFiles.push(videoFileModel)
1722 videoFilesDone.add(row.VideoFiles.id)
1725 if (row.VideoStreamingPlaylists?.id && !videoStreamingPlaylistMemo[row.VideoStreamingPlaylists.id]) {
1726 const streamingPlaylist = new VideoStreamingPlaylistModel(pick(row.VideoStreamingPlaylists, videoStreamingPlaylistKeys))
1727 streamingPlaylist.VideoFiles = []
1729 videoModel.VideoStreamingPlaylists.push(streamingPlaylist)
1731 videoStreamingPlaylistMemo[streamingPlaylist.id] = streamingPlaylist
1734 if (row.VideoStreamingPlaylists?.VideoFiles?.id && !videoFilesDone.has(row.VideoStreamingPlaylists.VideoFiles.id)) {
1735 const streamingPlaylist = videoStreamingPlaylistMemo[row.VideoStreamingPlaylists.id]
1737 const videoFileModel = new VideoFileModel(pick(row.VideoStreamingPlaylists.VideoFiles, videoFileKeys))
1738 streamingPlaylist.VideoFiles.push(videoFileModel)
1740 videoFilesDone.add(row.VideoStreamingPlaylists.VideoFiles.id)
1747 static getCategoryLabel (id: number) {
1748 return VIDEO_CATEGORIES[id] || 'Misc'
1751 static getLicenceLabel (id: number) {
1752 return VIDEO_LICENCES[id] || 'Unknown'
1755 static getLanguageLabel (id: string) {
1756 return VIDEO_LANGUAGES[id] || 'Unknown'
1759 static getPrivacyLabel (id: number) {
1760 return VIDEO_PRIVACIES[id] || 'Unknown'
1763 static getStateLabel (id: number) {
1764 return VIDEO_STATES[id] || 'Unknown'
1768 return !!this.VideoBlacklist
1772 return this.VideoChannel.Account.Actor.Server?.isBlocked() || this.VideoChannel.Account.isBlocked()
1775 getQualityFileBy<T extends MVideoWithFile> (this: T, fun: (files: MVideoFile[], it: (file: MVideoFile) => number) => MVideoFile) {
1776 // We first transcode to WebTorrent format, so try this array first
1777 if (Array.isArray(this.VideoFiles) && this.VideoFiles.length !== 0) {
1778 const file = fun(this.VideoFiles, file => file.resolution)
1780 return Object.assign(file, { Video: this })
1783 // No webtorrent files, try with streaming playlist files
1784 if (Array.isArray(this.VideoStreamingPlaylists) && this.VideoStreamingPlaylists.length !== 0) {
1785 const streamingPlaylistWithVideo = Object.assign(this.VideoStreamingPlaylists[0], { Video: this })
1787 const file = fun(streamingPlaylistWithVideo.VideoFiles, file => file.resolution)
1788 return Object.assign(file, { VideoStreamingPlaylist: streamingPlaylistWithVideo })
1794 getMaxQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1795 return this.getQualityFileBy(maxBy)
1798 getMinQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1799 return this.getQualityFileBy(minBy)
1802 getWebTorrentFile<T extends MVideoWithFile> (this: T, resolution: number): MVideoFileVideo {
1803 if (Array.isArray(this.VideoFiles) === false) return undefined
1805 const file = this.VideoFiles.find(f => f.resolution === resolution)
1806 if (!file) return undefined
1808 return Object.assign(file, { Video: this })
1811 hasWebTorrentFiles () {
1812 return Array.isArray(this.VideoFiles) === true && this.VideoFiles.length !== 0
1815 async addAndSaveThumbnail (thumbnail: MThumbnail, transaction: Transaction) {
1816 thumbnail.videoId = this.id
1818 const savedThumbnail = await thumbnail.save({ transaction })
1820 if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = []
1822 // Already have this thumbnail, skip
1823 if (this.Thumbnails.find(t => t.id === savedThumbnail.id)) return
1825 this.Thumbnails.push(savedThumbnail)
1828 generateThumbnailName () {
1829 return this.uuid + '.jpg'
1833 if (Array.isArray(this.Thumbnails) === false) return undefined
1835 return this.Thumbnails.find(t => t.type === ThumbnailType.MINIATURE)
1838 generatePreviewName () {
1839 return this.uuid + '.jpg'
1843 return !!this.getPreview()
1847 if (Array.isArray(this.Thumbnails) === false) return undefined
1849 return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW)
1853 return this.remote === false
1856 getWatchStaticPath () {
1857 return '/videos/watch/' + this.uuid
1860 getEmbedStaticPath () {
1861 return '/videos/embed/' + this.uuid
1864 getMiniatureStaticPath () {
1865 const thumbnail = this.getMiniature()
1866 if (!thumbnail) return null
1868 return join(STATIC_PATHS.THUMBNAILS, thumbnail.filename)
1871 getPreviewStaticPath () {
1872 const preview = this.getPreview()
1873 if (!preview) return null
1875 // We use a local cache, so specify our cache endpoint instead of potential remote URL
1876 return join(LAZY_STATIC_PATHS.PREVIEWS, preview.filename)
1879 toFormattedJSON (this: MVideoFormattable, options?: VideoFormattingJSONOptions): Video {
1880 return videoModelToFormattedJSON(this, options)
1883 toFormattedDetailsJSON (this: MVideoFormattableDetails): VideoDetails {
1884 return videoModelToFormattedDetailsJSON(this)
1887 getFormattedVideoFilesJSON (): VideoFile[] {
1888 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1889 let files: VideoFile[] = []
1891 if (Array.isArray(this.VideoFiles)) {
1892 const result = videoFilesModelToFormattedJSON(this, baseUrlHttp, baseUrlWs, this.VideoFiles)
1893 files = files.concat(result)
1896 for (const p of (this.VideoStreamingPlaylists || [])) {
1899 const result = videoFilesModelToFormattedJSON(p, baseUrlHttp, baseUrlWs, p.VideoFiles)
1900 files = files.concat(result)
1906 toActivityPubObject (this: MVideoAP): VideoObject {
1907 return videoModelToActivityPubObject(this)
1910 getTruncatedDescription () {
1911 if (!this.description) return null
1913 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1914 return peertubeTruncate(this.description, { length: maxLength })
1917 getMaxQualityResolution () {
1918 const file = this.getMaxQualityFile()
1919 const videoOrPlaylist = file.getVideoOrStreamingPlaylist()
1920 const originalFilePath = getVideoFilePath(videoOrPlaylist, file)
1922 return getVideoFileResolution(originalFilePath)
1925 getDescriptionAPIPath () {
1926 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1929 getHLSPlaylist (): MStreamingPlaylistFilesVideo {
1930 if (!this.VideoStreamingPlaylists) return undefined
1932 const playlist = this.VideoStreamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
1933 playlist.Video = this
1938 setHLSPlaylist (playlist: MStreamingPlaylist) {
1939 const toAdd = [ playlist ] as [ VideoStreamingPlaylistModel ]
1941 if (Array.isArray(this.VideoStreamingPlaylists) === false || this.VideoStreamingPlaylists.length === 0) {
1942 this.VideoStreamingPlaylists = toAdd
1946 this.VideoStreamingPlaylists = this.VideoStreamingPlaylists
1947 .filter(s => s.type !== VideoStreamingPlaylistType.HLS)
1951 removeFile (videoFile: MVideoFile, isRedundancy = false) {
1952 const filePath = getVideoFilePath(this, videoFile, isRedundancy)
1953 return remove(filePath)
1954 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1957 removeTorrent (videoFile: MVideoFile) {
1958 const torrentPath = getTorrentFilePath(this, videoFile)
1959 return remove(torrentPath)
1960 .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err }))
1963 async removeStreamingPlaylistFiles (streamingPlaylist: MStreamingPlaylist, isRedundancy = false) {
1964 const directoryPath = getHLSDirectory(this, isRedundancy)
1966 await remove(directoryPath)
1968 if (isRedundancy !== true) {
1969 const streamingPlaylistWithFiles = streamingPlaylist as MStreamingPlaylistFilesVideo
1970 streamingPlaylistWithFiles.Video = this
1972 if (!Array.isArray(streamingPlaylistWithFiles.VideoFiles)) {
1973 streamingPlaylistWithFiles.VideoFiles = await streamingPlaylistWithFiles.$get('VideoFiles')
1976 // Remove physical files and torrents
1978 streamingPlaylistWithFiles.VideoFiles.map(file => streamingPlaylistWithFiles.removeTorrent(file))
1984 if (this.isOwned()) return false
1986 return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)
1989 hasPrivacyForFederation () {
1990 return isPrivacyForFederation(this.privacy)
1993 hasStateForFederation () {
1994 return isStateForFederation(this.state)
1997 isNewVideo (newPrivacy: VideoPrivacy) {
1998 return this.hasPrivacyForFederation() === false && isPrivacyForFederation(newPrivacy) === true
2002 this.changed('updatedAt', true)
2008 return this.privacy === VideoPrivacy.PRIVATE || this.privacy === VideoPrivacy.INTERNAL || !!this.VideoBlacklist
2011 setPrivacy (newPrivacy: VideoPrivacy) {
2012 if (this.privacy === VideoPrivacy.PRIVATE && newPrivacy !== VideoPrivacy.PRIVATE) {
2013 this.publishedAt = new Date()
2016 this.privacy = newPrivacy
2020 return this.privacy === VideoPrivacy.PRIVATE ||
2021 this.privacy === VideoPrivacy.UNLISTED ||
2022 this.privacy === VideoPrivacy.INTERNAL
2025 async publishIfNeededAndSave (t: Transaction) {
2026 if (this.state !== VideoState.PUBLISHED) {
2027 this.state = VideoState.PUBLISHED
2028 this.publishedAt = new Date()
2029 await this.save({ transaction: t })
2038 if (this.isOwned()) {
2040 baseUrlHttp: WEBSERVER.URL,
2041 baseUrlWs: WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT
2046 baseUrlHttp: REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host,
2047 baseUrlWs: REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
2051 getTrackerUrls (baseUrlHttp: string, baseUrlWs: string) {
2052 return [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
2055 getTorrentUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2056 return baseUrlHttp + STATIC_PATHS.TORRENTS + getTorrentFileName(this, videoFile)
2059 getTorrentDownloadUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2060 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + getTorrentFileName(this, videoFile)
2063 getVideoFileUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2064 return baseUrlHttp + STATIC_PATHS.WEBSEED + getVideoFilename(this, videoFile)
2067 getVideoFileMetadataUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2068 const path = '/api/v1/videos/'
2070 return this.isOwned()
2071 ? baseUrlHttp + path + this.uuid + '/metadata/' + videoFile.id
2072 : videoFile.metadataUrl
2075 getVideoRedundancyUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2076 return baseUrlHttp + STATIC_PATHS.REDUNDANCY + getVideoFilename(this, videoFile)
2079 getVideoFileDownloadUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2080 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + getVideoFilename(this, videoFile)
2083 getBandwidthBits (videoFile: MVideoFile) {
2084 return Math.ceil((videoFile.size * 8) / this.duration)