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, MVideoFileRedundanciesOpt, 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 { UserVideoHistoryModel } from '../account/user-video-history'
104 import { ActorModel } from '../activitypub/actor'
105 import { AvatarModel } from '../avatar/avatar'
106 import { VideoRedundancyModel } from '../redundancy/video-redundancy'
107 import { ServerModel } from '../server/server'
108 import { buildTrigramSearchIndex, buildWhereIdOrUUID, getVideoSort, isOutdated, throwIfNotValid } from '../utils'
109 import { ScheduleVideoUpdateModel } from './schedule-video-update'
110 import { TagModel } from './tag'
111 import { ThumbnailModel } from './thumbnail'
112 import { VideoBlacklistModel } from './video-blacklist'
113 import { VideoCaptionModel } from './video-caption'
114 import { ScopeNames as VideoChannelScopeNames, SummaryOptions, VideoChannelModel } from './video-channel'
115 import { VideoCommentModel } from './video-comment'
116 import { VideoFileModel } from './video-file'
118 videoFilesModelToFormattedJSON,
119 VideoFormattingJSONOptions,
120 videoModelToActivityPubObject,
121 videoModelToFormattedDetailsJSON,
122 videoModelToFormattedJSON
123 } from './video-format-utils'
124 import { VideoImportModel } from './video-import'
125 import { VideoLiveModel } from './video-live'
126 import { VideoPlaylistElementModel } from './video-playlist-element'
127 import { buildListQuery, BuildVideosQueryOptions, wrapForAPIResults } from './video-query-builder'
128 import { VideoShareModel } from './video-share'
129 import { VideoStreamingPlaylistModel } from './video-streaming-playlist'
130 import { VideoTagModel } from './video-tag'
131 import { VideoViewModel } from './video-view'
133 export enum ScopeNames {
134 AVAILABLE_FOR_LIST_IDS = 'AVAILABLE_FOR_LIST_IDS',
136 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
137 WITH_TAGS = 'WITH_TAGS',
138 WITH_WEBTORRENT_FILES = 'WITH_WEBTORRENT_FILES',
139 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
140 WITH_BLACKLISTED = 'WITH_BLACKLISTED',
141 WITH_USER_HISTORY = 'WITH_USER_HISTORY',
142 WITH_STREAMING_PLAYLISTS = 'WITH_STREAMING_PLAYLISTS',
143 WITH_USER_ID = 'WITH_USER_ID',
144 WITH_IMMUTABLE_ATTRIBUTES = 'WITH_IMMUTABLE_ATTRIBUTES',
145 WITH_THUMBNAILS = 'WITH_THUMBNAILS',
146 WITH_LIVE = 'WITH_LIVE'
149 export type ForAPIOptions = {
152 videoPlaylistId?: number
156 withAccountBlockerIds?: number[]
159 export type AvailableForListIDsOptions = {
160 serverAccountId: number
161 followerActorId: number
162 includeLocalVideos: boolean
164 attributesType?: 'none' | 'id' | 'all'
167 categoryOneOf?: number[]
169 licenceOneOf?: number[]
170 languageOneOf?: string[]
177 videoChannelId?: number
179 videoPlaylistId?: number
181 trendingDays?: number
182 user?: MUserAccountId
183 historyOfUser?: MUserId
185 baseWhere?: WhereOptions[]
189 [ScopeNames.WITH_IMMUTABLE_ATTRIBUTES]: {
190 attributes: [ 'id', 'url', 'uuid', 'remote' ]
192 [ScopeNames.FOR_API]: (options: ForAPIOptions) => {
193 const include: Includeable[] = [
195 model: VideoChannelModel.scope({
197 VideoChannelScopeNames.SUMMARY, {
199 withAccountBlockerIds: options.withAccountBlockerIds
206 attributes: [ 'type', 'filename' ],
207 model: ThumbnailModel,
212 const query: FindOptions = {}
222 if (options.withFiles === true) {
224 model: VideoFileModel,
229 if (options.videoPlaylistId) {
231 model: VideoPlaylistElementModel.unscoped(),
234 videoPlaylistId: options.videoPlaylistId
239 query.include = include
243 [ScopeNames.WITH_THUMBNAILS]: {
246 model: ThumbnailModel,
251 [ScopeNames.WITH_LIVE]: {
254 model: VideoLiveModel.unscoped(),
259 [ScopeNames.WITH_USER_ID]: {
262 attributes: [ 'accountId' ],
263 model: VideoChannelModel.unscoped(),
267 attributes: [ 'userId' ],
268 model: AccountModel.unscoped(),
275 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
278 model: VideoChannelModel.unscoped(),
283 exclude: [ 'privateKey', 'publicKey' ]
285 model: ActorModel.unscoped(),
289 attributes: [ 'host' ],
290 model: ServerModel.unscoped(),
294 model: AvatarModel.unscoped(),
300 model: AccountModel.unscoped(),
304 model: ActorModel.unscoped(),
306 exclude: [ 'privateKey', 'publicKey' ]
311 attributes: [ 'host' ],
312 model: ServerModel.unscoped(),
316 model: AvatarModel.unscoped(),
327 [ScopeNames.WITH_TAGS]: {
328 include: [ TagModel ]
330 [ScopeNames.WITH_BLACKLISTED]: {
333 attributes: [ 'id', 'reason', 'unfederated' ],
334 model: VideoBlacklistModel,
339 [ScopeNames.WITH_WEBTORRENT_FILES]: (withRedundancies = false) => {
340 let subInclude: any[] = []
342 if (withRedundancies === true) {
345 attributes: [ 'fileUrl' ],
346 model: VideoRedundancyModel.unscoped(),
355 model: VideoFileModel,
356 separate: true, // We may have multiple files, having multiple redundancies so let's separate this join
363 [ScopeNames.WITH_STREAMING_PLAYLISTS]: (withRedundancies = false) => {
364 const subInclude: IncludeOptions[] = [
366 model: VideoFileModel,
371 if (withRedundancies === true) {
373 attributes: [ 'fileUrl' ],
374 model: VideoRedundancyModel.unscoped(),
382 model: VideoStreamingPlaylistModel.unscoped(),
383 separate: true, // We may have multiple streaming playlists, having multiple redundancies so let's separate this join
390 [ScopeNames.WITH_SCHEDULED_UPDATE]: {
393 model: ScheduleVideoUpdateModel.unscoped(),
398 [ScopeNames.WITH_USER_HISTORY]: (userId: number) => {
402 attributes: [ 'currentTime' ],
403 model: UserVideoHistoryModel.unscoped(),
416 buildTrigramSearchIndex('video_name_trigram', 'name'),
418 { fields: [ 'createdAt' ] },
421 { name: 'publishedAt', order: 'DESC' },
422 { name: 'id', order: 'ASC' }
425 { fields: [ 'duration' ] },
426 { fields: [ 'views' ] },
427 { fields: [ 'channelId' ] },
429 fields: [ 'originallyPublishedAt' ],
431 originallyPublishedAt: {
437 fields: [ 'category' ], // We don't care videos with an unknown category
445 fields: [ 'licence' ], // We don't care videos with an unknown licence
453 fields: [ 'language' ], // We don't care videos with an unknown language
461 fields: [ 'nsfw' ], // Most of the videos are not NSFW
467 fields: [ 'remote' ], // Only index local videos
482 export class VideoModel extends Model {
485 @Default(DataType.UUIDV4)
487 @Column(DataType.UUID)
491 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
497 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category', true))
503 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence', true))
509 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language', true))
510 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
514 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
516 privacy: VideoPrivacy
519 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
525 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description', true))
526 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
531 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support', true))
532 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
536 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
571 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
572 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
577 commentsEnabled: boolean
581 downloadEnabled: boolean
585 waitTranscoding: boolean
589 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
600 @Default(DataType.NOW)
607 originallyPublishedAt: Date
609 @ForeignKey(() => VideoChannelModel)
613 @BelongsTo(() => VideoChannelModel, {
619 VideoChannel: VideoChannelModel
621 @BelongsToMany(() => TagModel, {
622 foreignKey: 'videoId',
623 through: () => VideoTagModel,
628 @HasMany(() => ThumbnailModel, {
636 Thumbnails: ThumbnailModel[]
638 @HasMany(() => VideoPlaylistElementModel, {
645 VideoPlaylistElements: VideoPlaylistElementModel[]
647 @HasMany(() => VideoAbuseModel, {
654 VideoAbuses: VideoAbuseModel[]
656 @HasMany(() => VideoFileModel, {
664 VideoFiles: VideoFileModel[]
666 @HasMany(() => VideoStreamingPlaylistModel, {
674 VideoStreamingPlaylists: VideoStreamingPlaylistModel[]
676 @HasMany(() => VideoShareModel, {
683 VideoShares: VideoShareModel[]
685 @HasMany(() => AccountVideoRateModel, {
692 AccountVideoRates: AccountVideoRateModel[]
694 @HasMany(() => VideoCommentModel, {
702 VideoComments: VideoCommentModel[]
704 @HasMany(() => VideoViewModel, {
711 VideoViews: VideoViewModel[]
713 @HasMany(() => UserVideoHistoryModel, {
720 UserVideoHistories: UserVideoHistoryModel[]
722 @HasOne(() => ScheduleVideoUpdateModel, {
729 ScheduleVideoUpdate: ScheduleVideoUpdateModel
731 @HasOne(() => VideoBlacklistModel, {
738 VideoBlacklist: VideoBlacklistModel
740 @HasOne(() => VideoLiveModel, {
747 VideoLive: VideoLiveModel
749 @HasOne(() => VideoImportModel, {
756 VideoImport: VideoImportModel
758 @HasMany(() => VideoCaptionModel, {
765 ['separate' as any]: true
767 VideoCaptions: VideoCaptionModel[]
770 static async sendDelete (instance: MVideoAccountLight, options) {
771 if (instance.isOwned()) {
772 if (!instance.VideoChannel) {
773 instance.VideoChannel = await instance.$get('VideoChannel', {
778 transaction: options.transaction
779 }) as MChannelAccountDefault
782 return sendDeleteVideo(instance, options.transaction)
789 static async removeFiles (instance: VideoModel) {
790 const tasks: Promise<any>[] = []
792 logger.info('Removing files of video %s.', instance.url)
794 if (instance.isOwned()) {
795 if (!Array.isArray(instance.VideoFiles)) {
796 instance.VideoFiles = await instance.$get('VideoFiles')
799 // Remove physical files and torrents
800 instance.VideoFiles.forEach(file => {
801 tasks.push(instance.removeFile(file))
802 tasks.push(instance.removeTorrent(file))
805 // Remove playlists file
806 if (!Array.isArray(instance.VideoStreamingPlaylists)) {
807 instance.VideoStreamingPlaylists = await instance.$get('VideoStreamingPlaylists')
810 for (const p of instance.VideoStreamingPlaylists) {
811 tasks.push(instance.removeStreamingPlaylistFiles(p))
815 // Do not wait video deletion because we could be in a transaction
818 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
825 static stopLiveIfNeeded (instance: VideoModel) {
826 if (!instance.isLive) return
828 logger.info('Stopping live of video %s after video deletion.', instance.uuid)
830 return LiveManager.Instance.stopSessionOf(instance.id)
834 static invalidateCache (instance: VideoModel) {
835 ModelCache.Instance.invalidateCache('video', instance.id)
839 static async saveEssentialDataToAbuses (instance: VideoModel, options) {
840 const tasks: Promise<any>[] = []
842 if (!Array.isArray(instance.VideoAbuses)) {
843 instance.VideoAbuses = await instance.$get('VideoAbuses')
845 if (instance.VideoAbuses.length === 0) return undefined
848 logger.info('Saving video abuses details of video %s.', instance.url)
850 const details = instance.toFormattedDetailsJSON()
852 for (const abuse of instance.VideoAbuses) {
853 abuse.deletedVideo = details
854 tasks.push(abuse.save({ transaction: options.transaction }))
859 logger.error('Some errors when saving details of video %s in its abuses before destroy hook.', instance.uuid, { err })
865 static listLocal (): Promise<MVideoWithAllFiles[]> {
872 return VideoModel.scope([
873 ScopeNames.WITH_WEBTORRENT_FILES,
874 ScopeNames.WITH_STREAMING_PLAYLISTS,
875 ScopeNames.WITH_THUMBNAILS
879 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
880 function getRawQuery (select: string) {
881 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
882 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
883 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
884 'WHERE "Account"."actorId" = ' + actorId
885 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
886 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
887 'WHERE "VideoShare"."actorId" = ' + actorId
889 return `(${queryVideo}) UNION (${queryVideoShare})`
892 const rawQuery = getRawQuery('"Video"."id"')
893 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
899 order: getVideoSort('-createdAt', [ 'Tags', 'name', 'ASC' ] as any), // FIXME: sequelize typings
902 [Op.in]: Sequelize.literal('(' + rawQuery + ')')
904 [Op.or]: getPrivaciesForFederation()
908 attributes: [ 'language', 'fileUrl' ],
909 model: VideoCaptionModel.unscoped(),
913 attributes: [ 'id', 'url' ],
914 model: VideoShareModel.unscoped(),
916 // We only want videos shared by this actor
931 attributes: [ 'id', 'url' ],
932 model: ActorModel.unscoped()
937 model: VideoChannelModel.unscoped(),
941 attributes: [ 'name' ],
942 model: AccountModel.unscoped(),
946 attributes: [ 'id', 'url', 'followersUrl' ],
947 model: ActorModel.unscoped(),
953 attributes: [ 'id', 'url', 'followersUrl' ],
954 model: ActorModel.unscoped(),
960 model: VideoStreamingPlaylistModel.unscoped(),
964 model: VideoFileModel,
969 VideoLiveModel.unscoped(),
975 return Bluebird.all([
976 VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findAll(query),
977 VideoModel.sequelize.query<{ total: string }>(rawCountQuery, { type: QueryTypes.SELECT })
978 ]).then(([ rows, totals ]) => {
979 // totals: totalVideos + totalVideoShares
981 let totalVideoShares = 0
982 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
983 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
985 const total = totalVideos + totalVideoShares
993 static async listPublishedLiveIds () {
995 attributes: [ 'id' ],
998 state: VideoState.PUBLISHED
1002 const result = await VideoModel.findAll(options)
1004 return result.map(v => v.id)
1007 static listUserVideosForApi (
1014 function buildBaseQuery (): FindOptions {
1018 order: getVideoSort(sort),
1021 model: VideoChannelModel,
1025 model: AccountModel,
1037 baseQuery = Object.assign(baseQuery, {
1040 [Op.iLike]: '%' + search + '%'
1049 const countQuery = buildBaseQuery()
1050 const findQuery = buildBaseQuery()
1052 const findScopes: (string | ScopeOptions)[] = [
1053 ScopeNames.WITH_SCHEDULED_UPDATE,
1054 ScopeNames.WITH_BLACKLISTED,
1055 ScopeNames.WITH_THUMBNAILS
1058 return Promise.all([
1059 VideoModel.count(countQuery),
1060 VideoModel.scope(findScopes).findAll<MVideoForUser>(findQuery)
1061 ]).then(([ count, rows ]) => {
1069 static async listForApi (options: {
1074 includeLocalVideos: boolean
1076 categoryOneOf?: number[]
1077 licenceOneOf?: number[]
1078 languageOneOf?: string[]
1079 tagsOneOf?: string[]
1080 tagsAllOf?: string[]
1081 filter?: VideoFilter
1083 videoChannelId?: number
1084 followerActorId?: number
1085 videoPlaylistId?: number
1086 trendingDays?: number
1087 user?: MUserAccountId
1088 historyOfUser?: MUserId
1089 countVideos?: boolean
1092 if ((options.filter === 'all-local' || options.filter === 'all') && !options.user.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1093 throw new Error('Try to filter all-local but no user has not the see all videos right')
1096 const trendingDays = options.sort.endsWith('trending')
1097 ? CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1100 const serverActor = await getServerActor()
1102 // followerActorId === null has a meaning, so just check undefined
1103 const followerActorId = options.followerActorId !== undefined
1104 ? options.followerActorId
1107 const queryOptions = {
1108 start: options.start,
1109 count: options.count,
1112 serverAccountId: serverActor.Account.id,
1114 categoryOneOf: options.categoryOneOf,
1115 licenceOneOf: options.licenceOneOf,
1116 languageOneOf: options.languageOneOf,
1117 tagsOneOf: options.tagsOneOf,
1118 tagsAllOf: options.tagsAllOf,
1119 filter: options.filter,
1120 withFiles: options.withFiles,
1121 accountId: options.accountId,
1122 videoChannelId: options.videoChannelId,
1123 videoPlaylistId: options.videoPlaylistId,
1124 includeLocalVideos: options.includeLocalVideos,
1126 historyOfUser: options.historyOfUser,
1128 search: options.search
1131 return VideoModel.getAvailableForApi(queryOptions, options.countVideos)
1134 static async searchAndPopulateAccountAndServer (options: {
1135 includeLocalVideos: boolean
1140 startDate?: string // ISO 8601
1141 endDate?: string // ISO 8601
1142 originallyPublishedStartDate?: string
1143 originallyPublishedEndDate?: string
1145 categoryOneOf?: number[]
1146 licenceOneOf?: number[]
1147 languageOneOf?: string[]
1148 tagsOneOf?: string[]
1149 tagsAllOf?: string[]
1150 durationMin?: number // seconds
1151 durationMax?: number // seconds
1152 user?: MUserAccountId
1153 filter?: VideoFilter
1155 const serverActor = await getServerActor()
1156 const queryOptions = {
1157 followerActorId: serverActor.id,
1158 serverAccountId: serverActor.Account.id,
1159 includeLocalVideos: options.includeLocalVideos,
1161 categoryOneOf: options.categoryOneOf,
1162 licenceOneOf: options.licenceOneOf,
1163 languageOneOf: options.languageOneOf,
1164 tagsOneOf: options.tagsOneOf,
1165 tagsAllOf: options.tagsAllOf,
1167 filter: options.filter,
1168 start: options.start,
1169 count: options.count,
1171 startDate: options.startDate,
1172 endDate: options.endDate,
1173 originallyPublishedStartDate: options.originallyPublishedStartDate,
1174 originallyPublishedEndDate: options.originallyPublishedEndDate,
1176 durationMin: options.durationMin,
1177 durationMax: options.durationMax,
1179 search: options.search
1182 return VideoModel.getAvailableForApi(queryOptions)
1185 static countLocalLives () {
1191 [Op.ne]: VideoState.LIVE_ENDED
1196 return VideoModel.count(options)
1199 static countLivesOfAccount (accountId: number) {
1205 [Op.ne]: VideoState.LIVE_ENDED
1211 model: VideoChannelModel.unscoped(),
1219 return VideoModel.count(options)
1222 static load (id: number | string, t?: Transaction): Promise<MVideoThumbnail> {
1223 const where = buildWhereIdOrUUID(id)
1229 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1232 static loadWithBlacklist (id: number | string, t?: Transaction): Promise<MVideoThumbnailBlacklist> {
1233 const where = buildWhereIdOrUUID(id)
1239 return VideoModel.scope([
1240 ScopeNames.WITH_THUMBNAILS,
1241 ScopeNames.WITH_BLACKLISTED
1245 static loadImmutableAttributes (id: number | string, t?: Transaction): Promise<MVideoImmutable> {
1248 where: buildWhereIdOrUUID(id),
1252 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1255 return ModelCache.Instance.doCache({
1256 cacheType: 'load-video-immutable-id',
1263 static loadWithRights (id: number | string, t?: Transaction): Promise<MVideoWithRights> {
1264 const where = buildWhereIdOrUUID(id)
1270 return VideoModel.scope([
1271 ScopeNames.WITH_BLACKLISTED,
1272 ScopeNames.WITH_USER_ID,
1273 ScopeNames.WITH_THUMBNAILS
1277 static loadOnlyId (id: number | string, t?: Transaction): Promise<MVideoIdThumbnail> {
1278 const where = buildWhereIdOrUUID(id)
1281 attributes: [ 'id' ],
1286 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1289 static loadWithFiles (id: number | string, t?: Transaction, logging?: boolean): Promise<MVideoWithAllFiles> {
1290 const where = buildWhereIdOrUUID(id)
1298 return VideoModel.scope([
1299 ScopeNames.WITH_WEBTORRENT_FILES,
1300 ScopeNames.WITH_STREAMING_PLAYLISTS,
1301 ScopeNames.WITH_THUMBNAILS
1305 static loadByUUID (uuid: string): Promise<MVideoThumbnail> {
1312 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1315 static loadByUrl (url: string, transaction?: Transaction): Promise<MVideoThumbnail> {
1316 const query: FindOptions = {
1323 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(query)
1326 static loadByUrlImmutableAttributes (url: string, transaction?: Transaction): Promise<MVideoImmutable> {
1328 const query: FindOptions = {
1335 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1338 return ModelCache.Instance.doCache({
1339 cacheType: 'load-video-immutable-url',
1346 static loadByUrlAndPopulateAccount (url: string, transaction?: Transaction): Promise<MVideoAccountLightBlacklistAllFiles> {
1347 const query: FindOptions = {
1354 return VideoModel.scope([
1355 ScopeNames.WITH_ACCOUNT_DETAILS,
1356 ScopeNames.WITH_WEBTORRENT_FILES,
1357 ScopeNames.WITH_STREAMING_PLAYLISTS,
1358 ScopeNames.WITH_THUMBNAILS,
1359 ScopeNames.WITH_BLACKLISTED
1363 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Transaction, userId?: number): Promise<MVideoFullLight> {
1364 const where = buildWhereIdOrUUID(id)
1367 order: [ [ 'Tags', 'name', 'ASC' ] ] as any,
1372 const scopes: (string | ScopeOptions)[] = [
1373 ScopeNames.WITH_TAGS,
1374 ScopeNames.WITH_BLACKLISTED,
1375 ScopeNames.WITH_ACCOUNT_DETAILS,
1376 ScopeNames.WITH_SCHEDULED_UPDATE,
1377 ScopeNames.WITH_WEBTORRENT_FILES,
1378 ScopeNames.WITH_STREAMING_PLAYLISTS,
1379 ScopeNames.WITH_THUMBNAILS,
1380 ScopeNames.WITH_LIVE
1384 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1392 static loadForGetAPI (parameters: {
1396 }): Promise<MVideoDetails> {
1397 const { id, t, userId } = parameters
1398 const where = buildWhereIdOrUUID(id)
1401 order: [ [ 'Tags', 'name', 'ASC' ] ] as any, // FIXME: sequelize typings
1406 const scopes: (string | ScopeOptions)[] = [
1407 ScopeNames.WITH_TAGS,
1408 ScopeNames.WITH_BLACKLISTED,
1409 ScopeNames.WITH_ACCOUNT_DETAILS,
1410 ScopeNames.WITH_SCHEDULED_UPDATE,
1411 ScopeNames.WITH_THUMBNAILS,
1412 ScopeNames.WITH_LIVE,
1413 { method: [ ScopeNames.WITH_WEBTORRENT_FILES, true ] },
1414 { method: [ ScopeNames.WITH_STREAMING_PLAYLISTS, true ] }
1418 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1426 static async getStats () {
1427 const totalLocalVideos = await VideoModel.count({
1433 let totalLocalVideoViews = await VideoModel.sum('views', {
1439 // Sequelize could return null...
1440 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1442 const { total: totalVideos } = await VideoModel.listForApi({
1445 sort: '-publishedAt',
1446 nsfw: buildNSFWFilter(),
1447 includeLocalVideos: true,
1453 totalLocalVideoViews,
1458 static incrementViews (id: number, views: number) {
1459 return VideoModel.increment('views', {
1467 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1468 // Instances only share videos
1469 const query = 'SELECT 1 FROM "videoShare" ' +
1470 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1471 'WHERE "actorFollow"."actorId" = $followerActorId AND "actorFollow"."state" = \'accepted\' AND "videoShare"."videoId" = $videoId ' +
1475 type: QueryTypes.SELECT as QueryTypes.SELECT,
1476 bind: { followerActorId, videoId },
1480 return VideoModel.sequelize.query(query, options)
1481 .then(results => results.length === 1)
1484 static bulkUpdateSupportField (videoChannel: MChannel, t: Transaction) {
1487 channelId: videoChannel.id
1492 return VideoModel.update({ support: videoChannel.support }, options)
1495 static getAllIdsFromChannel (videoChannel: MChannelId): Promise<number[]> {
1497 attributes: [ 'id' ],
1499 channelId: videoChannel.id
1503 return VideoModel.findAll(query)
1504 .then(videos => videos.map(v => v.id))
1507 // threshold corresponds to how many video the field should have to be returned
1508 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1509 const serverActor = await getServerActor()
1510 const followerActorId = serverActor.id
1512 const queryOptions: BuildVideosQueryOptions = {
1513 attributes: [ `"${field}"` ],
1514 group: `GROUP BY "${field}"`,
1515 having: `HAVING COUNT("${field}") >= ${threshold}`,
1519 serverAccountId: serverActor.Account.id,
1521 includeLocalVideos: true
1524 const { query, replacements } = buildListQuery(VideoModel, queryOptions)
1526 return this.sequelize.query<any>(query, { replacements, type: QueryTypes.SELECT })
1527 .then(rows => rows.map(r => r[field]))
1530 static buildTrendingQuery (trendingDays: number) {
1534 model: VideoViewModel,
1538 [Op.gte]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1544 private static async getAvailableForApi (
1545 options: BuildVideosQueryOptions,
1547 ): Promise<ResultList<VideoModel>> {
1548 function getCount () {
1549 if (countVideos !== true) return Promise.resolve(undefined)
1551 const countOptions = Object.assign({}, options, { isCount: true })
1552 const { query: queryCount, replacements: replacementsCount } = buildListQuery(VideoModel, countOptions)
1554 return VideoModel.sequelize.query<any>(queryCount, { replacements: replacementsCount, type: QueryTypes.SELECT })
1555 .then(rows => rows.length !== 0 ? rows[0].total : 0)
1558 function getModels () {
1559 if (options.count === 0) return Promise.resolve([])
1561 const { query, replacements, order } = buildListQuery(VideoModel, options)
1562 const queryModels = wrapForAPIResults(query, replacements, options, order)
1564 return VideoModel.sequelize.query<any>(queryModels, { replacements, type: QueryTypes.SELECT, nest: true })
1565 .then(rows => VideoModel.buildAPIResult(rows))
1568 const [ count, rows ] = await Promise.all([ getCount(), getModels() ])
1576 private static buildAPIResult (rows: any[]) {
1577 const videosMemo: { [ id: number ]: VideoModel } = {}
1578 const videoStreamingPlaylistMemo: { [ id: number ]: VideoStreamingPlaylistModel } = {}
1580 const thumbnailsDone = new Set<number>()
1581 const historyDone = new Set<number>()
1582 const videoFilesDone = new Set<number>()
1584 const videos: VideoModel[] = []
1586 const avatarKeys = [ 'id', 'filename', 'fileUrl', 'onDisk', 'createdAt', 'updatedAt' ]
1587 const actorKeys = [ 'id', 'preferredUsername', 'url', 'serverId', 'avatarId' ]
1588 const serverKeys = [ 'id', 'host' ]
1589 const videoFileKeys = [ 'id', 'createdAt', 'updatedAt', 'resolution', 'size', 'extname', 'infoHash', 'fps', 'videoId' ]
1590 const videoStreamingPlaylistKeys = [ 'id' ]
1614 'originallyPublishedAt',
1620 function buildActor (rowActor: any) {
1621 const avatarModel = rowActor.Avatar.id !== null
1622 ? new AvatarModel(pick(rowActor.Avatar, avatarKeys))
1625 const serverModel = rowActor.Server.id !== null
1626 ? new ServerModel(pick(rowActor.Server, serverKeys))
1629 const actorModel = new ActorModel(pick(rowActor, actorKeys))
1630 actorModel.Avatar = avatarModel
1631 actorModel.Server = serverModel
1636 for (const row of rows) {
1637 if (!videosMemo[row.id]) {
1639 const channel = row.VideoChannel
1640 const channelModel = new VideoChannelModel(pick(channel, [ 'id', 'name', 'description', 'actorId' ]))
1641 channelModel.Actor = buildActor(channel.Actor)
1643 const account = row.VideoChannel.Account
1644 const accountModel = new AccountModel(pick(account, [ 'id', 'name' ]))
1645 accountModel.Actor = buildActor(account.Actor)
1647 channelModel.Account = accountModel
1649 const videoModel = new VideoModel(pick(row, videoKeys))
1650 videoModel.VideoChannel = channelModel
1652 videoModel.UserVideoHistories = []
1653 videoModel.Thumbnails = []
1654 videoModel.VideoFiles = []
1655 videoModel.VideoStreamingPlaylists = []
1657 videosMemo[row.id] = videoModel
1658 // Don't take object value to have a sorted array
1659 videos.push(videoModel)
1662 const videoModel = videosMemo[row.id]
1664 if (row.userVideoHistory?.id && !historyDone.has(row.userVideoHistory.id)) {
1665 const historyModel = new UserVideoHistoryModel(pick(row.userVideoHistory, [ 'id', 'currentTime' ]))
1666 videoModel.UserVideoHistories.push(historyModel)
1668 historyDone.add(row.userVideoHistory.id)
1671 if (row.Thumbnails?.id && !thumbnailsDone.has(row.Thumbnails.id)) {
1672 const thumbnailModel = new ThumbnailModel(pick(row.Thumbnails, [ 'id', 'type', 'filename' ]))
1673 videoModel.Thumbnails.push(thumbnailModel)
1675 thumbnailsDone.add(row.Thumbnails.id)
1678 if (row.VideoFiles?.id && !videoFilesDone.has(row.VideoFiles.id)) {
1679 const videoFileModel = new VideoFileModel(pick(row.VideoFiles, videoFileKeys))
1680 videoModel.VideoFiles.push(videoFileModel)
1682 videoFilesDone.add(row.VideoFiles.id)
1685 if (row.VideoStreamingPlaylists?.id && !videoStreamingPlaylistMemo[row.VideoStreamingPlaylists.id]) {
1686 const streamingPlaylist = new VideoStreamingPlaylistModel(pick(row.VideoStreamingPlaylists, videoStreamingPlaylistKeys))
1687 streamingPlaylist.VideoFiles = []
1689 videoModel.VideoStreamingPlaylists.push(streamingPlaylist)
1691 videoStreamingPlaylistMemo[streamingPlaylist.id] = streamingPlaylist
1694 if (row.VideoStreamingPlaylists?.VideoFiles?.id && !videoFilesDone.has(row.VideoStreamingPlaylists.VideoFiles.id)) {
1695 const streamingPlaylist = videoStreamingPlaylistMemo[row.VideoStreamingPlaylists.id]
1697 const videoFileModel = new VideoFileModel(pick(row.VideoStreamingPlaylists.VideoFiles, videoFileKeys))
1698 streamingPlaylist.VideoFiles.push(videoFileModel)
1700 videoFilesDone.add(row.VideoStreamingPlaylists.VideoFiles.id)
1707 static getCategoryLabel (id: number) {
1708 return VIDEO_CATEGORIES[id] || 'Misc'
1711 static getLicenceLabel (id: number) {
1712 return VIDEO_LICENCES[id] || 'Unknown'
1715 static getLanguageLabel (id: string) {
1716 return VIDEO_LANGUAGES[id] || 'Unknown'
1719 static getPrivacyLabel (id: number) {
1720 return VIDEO_PRIVACIES[id] || 'Unknown'
1723 static getStateLabel (id: number) {
1724 return VIDEO_STATES[id] || 'Unknown'
1728 return !!this.VideoBlacklist
1732 return this.VideoChannel.Account.Actor.Server?.isBlocked() || this.VideoChannel.Account.isBlocked()
1735 getQualityFileBy<T extends MVideoWithFile> (this: T, fun: (files: MVideoFile[], it: (file: MVideoFile) => number) => MVideoFile) {
1736 if (Array.isArray(this.VideoFiles) && this.VideoFiles.length !== 0) {
1737 const file = fun(this.VideoFiles, file => file.resolution)
1739 return Object.assign(file, { Video: this })
1742 // No webtorrent files, try with streaming playlist files
1743 if (Array.isArray(this.VideoStreamingPlaylists) && this.VideoStreamingPlaylists.length !== 0) {
1744 const streamingPlaylistWithVideo = Object.assign(this.VideoStreamingPlaylists[0], { Video: this })
1746 const file = fun(streamingPlaylistWithVideo.VideoFiles, file => file.resolution)
1747 return Object.assign(file, { VideoStreamingPlaylist: streamingPlaylistWithVideo })
1753 getMaxQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1754 return this.getQualityFileBy(maxBy)
1757 getMinQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1758 return this.getQualityFileBy(minBy)
1761 getWebTorrentFile<T extends MVideoWithFile> (this: T, resolution: number): MVideoFileVideo {
1762 if (Array.isArray(this.VideoFiles) === false) return undefined
1764 const file = this.VideoFiles.find(f => f.resolution === resolution)
1765 if (!file) return undefined
1767 return Object.assign(file, { Video: this })
1770 async addAndSaveThumbnail (thumbnail: MThumbnail, transaction: Transaction) {
1771 thumbnail.videoId = this.id
1773 const savedThumbnail = await thumbnail.save({ transaction })
1775 if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = []
1777 // Already have this thumbnail, skip
1778 if (this.Thumbnails.find(t => t.id === savedThumbnail.id)) return
1780 this.Thumbnails.push(savedThumbnail)
1783 generateThumbnailName () {
1784 return this.uuid + '.jpg'
1788 if (Array.isArray(this.Thumbnails) === false) return undefined
1790 return this.Thumbnails.find(t => t.type === ThumbnailType.MINIATURE)
1793 generatePreviewName () {
1794 return this.uuid + '.jpg'
1798 return !!this.getPreview()
1802 if (Array.isArray(this.Thumbnails) === false) return undefined
1804 return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW)
1808 return this.remote === false
1811 getWatchStaticPath () {
1812 return '/videos/watch/' + this.uuid
1815 getEmbedStaticPath () {
1816 return '/videos/embed/' + this.uuid
1819 getMiniatureStaticPath () {
1820 const thumbnail = this.getMiniature()
1821 if (!thumbnail) return null
1823 return join(STATIC_PATHS.THUMBNAILS, thumbnail.filename)
1826 getPreviewStaticPath () {
1827 const preview = this.getPreview()
1828 if (!preview) return null
1830 // We use a local cache, so specify our cache endpoint instead of potential remote URL
1831 return join(LAZY_STATIC_PATHS.PREVIEWS, preview.filename)
1834 toFormattedJSON (this: MVideoFormattable, options?: VideoFormattingJSONOptions): Video {
1835 return videoModelToFormattedJSON(this, options)
1838 toFormattedDetailsJSON (this: MVideoFormattableDetails): VideoDetails {
1839 return videoModelToFormattedDetailsJSON(this)
1842 getFormattedVideoFilesJSON (): VideoFile[] {
1843 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1844 let files: MVideoFileRedundanciesOpt[] = []
1846 if (Array.isArray(this.VideoFiles)) {
1847 files = files.concat(this.VideoFiles)
1850 for (const p of (this.VideoStreamingPlaylists || [])) {
1851 files = files.concat(p.VideoFiles || [])
1854 return videoFilesModelToFormattedJSON(this, baseUrlHttp, baseUrlWs, files)
1857 toActivityPubObject (this: MVideoAP): VideoObject {
1858 return videoModelToActivityPubObject(this)
1861 getTruncatedDescription () {
1862 if (!this.description) return null
1864 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1865 return peertubeTruncate(this.description, { length: maxLength })
1868 getMaxQualityResolution () {
1869 const file = this.getMaxQualityFile()
1870 const videoOrPlaylist = file.getVideoOrStreamingPlaylist()
1871 const originalFilePath = getVideoFilePath(videoOrPlaylist, file)
1873 return getVideoFileResolution(originalFilePath)
1876 getDescriptionAPIPath () {
1877 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1880 getHLSPlaylist (): MStreamingPlaylistFilesVideo {
1881 if (!this.VideoStreamingPlaylists) return undefined
1883 const playlist = this.VideoStreamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
1884 playlist.Video = this
1889 setHLSPlaylist (playlist: MStreamingPlaylist) {
1890 const toAdd = [ playlist ] as [ VideoStreamingPlaylistModel ]
1892 if (Array.isArray(this.VideoStreamingPlaylists) === false || this.VideoStreamingPlaylists.length === 0) {
1893 this.VideoStreamingPlaylists = toAdd
1897 this.VideoStreamingPlaylists = this.VideoStreamingPlaylists
1898 .filter(s => s.type !== VideoStreamingPlaylistType.HLS)
1902 removeFile (videoFile: MVideoFile, isRedundancy = false) {
1903 const filePath = getVideoFilePath(this, videoFile, isRedundancy)
1904 return remove(filePath)
1905 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1908 removeTorrent (videoFile: MVideoFile) {
1909 const torrentPath = getTorrentFilePath(this, videoFile)
1910 return remove(torrentPath)
1911 .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err }))
1914 async removeStreamingPlaylistFiles (streamingPlaylist: MStreamingPlaylist, isRedundancy = false) {
1915 const directoryPath = getHLSDirectory(this, isRedundancy)
1917 await remove(directoryPath)
1919 if (isRedundancy !== true) {
1920 const streamingPlaylistWithFiles = streamingPlaylist as MStreamingPlaylistFilesVideo
1921 streamingPlaylistWithFiles.Video = this
1923 if (!Array.isArray(streamingPlaylistWithFiles.VideoFiles)) {
1924 streamingPlaylistWithFiles.VideoFiles = await streamingPlaylistWithFiles.$get('VideoFiles')
1927 // Remove physical files and torrents
1929 streamingPlaylistWithFiles.VideoFiles.map(file => streamingPlaylistWithFiles.removeTorrent(file))
1935 if (this.isOwned()) return false
1937 return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)
1940 hasPrivacyForFederation () {
1941 return isPrivacyForFederation(this.privacy)
1944 hasStateForFederation () {
1945 return isStateForFederation(this.state)
1948 isNewVideo (newPrivacy: VideoPrivacy) {
1949 return this.hasPrivacyForFederation() === false && isPrivacyForFederation(newPrivacy) === true
1953 this.changed('updatedAt', true)
1959 return this.privacy === VideoPrivacy.PRIVATE || this.privacy === VideoPrivacy.INTERNAL || !!this.VideoBlacklist
1962 setPrivacy (newPrivacy: VideoPrivacy) {
1963 if (this.privacy === VideoPrivacy.PRIVATE && newPrivacy !== VideoPrivacy.PRIVATE) {
1964 this.publishedAt = new Date()
1967 this.privacy = newPrivacy
1971 return this.privacy === VideoPrivacy.PRIVATE ||
1972 this.privacy === VideoPrivacy.UNLISTED ||
1973 this.privacy === VideoPrivacy.INTERNAL
1976 async publishIfNeededAndSave (t: Transaction) {
1977 if (this.state !== VideoState.PUBLISHED) {
1978 this.state = VideoState.PUBLISHED
1979 this.publishedAt = new Date()
1980 await this.save({ transaction: t })
1989 if (this.isOwned()) {
1991 baseUrlHttp: WEBSERVER.URL,
1992 baseUrlWs: WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT
1997 baseUrlHttp: REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host,
1998 baseUrlWs: REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
2002 getTrackerUrls (baseUrlHttp: string, baseUrlWs: string) {
2003 return [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
2006 getTorrentUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2007 return baseUrlHttp + STATIC_PATHS.TORRENTS + getTorrentFileName(this, videoFile)
2010 getTorrentDownloadUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2011 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + getTorrentFileName(this, videoFile)
2014 getVideoFileUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2015 return baseUrlHttp + STATIC_PATHS.WEBSEED + getVideoFilename(this, videoFile)
2018 getVideoFileMetadataUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2019 const path = '/api/v1/videos/'
2021 return this.isOwned()
2022 ? baseUrlHttp + path + this.uuid + '/metadata/' + videoFile.id
2023 : videoFile.metadataUrl
2026 getVideoRedundancyUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2027 return baseUrlHttp + STATIC_PATHS.REDUNDANCY + getVideoFilename(this, videoFile)
2030 getVideoFileDownloadUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2031 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + getVideoFilename(this, videoFile)
2034 getBandwidthBits (videoFile: MVideoFile) {
2035 return Math.ceil((videoFile.size * 8) / this.duration)