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 (options: {
1014 const { accountId, start, count, sort, search } = options
1016 function buildBaseQuery (): FindOptions {
1020 order: getVideoSort(sort),
1023 model: VideoChannelModel,
1027 model: AccountModel,
1039 baseQuery = Object.assign(baseQuery, {
1042 [Op.iLike]: '%' + search + '%'
1051 const countQuery = buildBaseQuery()
1052 const findQuery = buildBaseQuery()
1054 const findScopes: (string | ScopeOptions)[] = [
1055 ScopeNames.WITH_SCHEDULED_UPDATE,
1056 ScopeNames.WITH_BLACKLISTED,
1057 ScopeNames.WITH_THUMBNAILS
1060 return Promise.all([
1061 VideoModel.count(countQuery),
1062 VideoModel.scope(findScopes).findAll<MVideoForUser>(findQuery)
1063 ]).then(([ count, rows ]) => {
1071 static async listForApi (options: {
1076 includeLocalVideos: boolean
1078 categoryOneOf?: number[]
1079 licenceOneOf?: number[]
1080 languageOneOf?: string[]
1081 tagsOneOf?: string[]
1082 tagsAllOf?: string[]
1083 filter?: VideoFilter
1085 videoChannelId?: number
1086 followerActorId?: number
1087 videoPlaylistId?: number
1088 trendingDays?: number
1089 user?: MUserAccountId
1090 historyOfUser?: MUserId
1091 countVideos?: boolean
1094 if ((options.filter === 'all-local' || options.filter === 'all') && !options.user.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1095 throw new Error('Try to filter all-local but no user has not the see all videos right')
1098 const trendingDays = options.sort.endsWith('trending')
1099 ? CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1102 const serverActor = await getServerActor()
1104 // followerActorId === null has a meaning, so just check undefined
1105 const followerActorId = options.followerActorId !== undefined
1106 ? options.followerActorId
1109 const queryOptions = {
1110 start: options.start,
1111 count: options.count,
1114 serverAccountId: serverActor.Account.id,
1116 categoryOneOf: options.categoryOneOf,
1117 licenceOneOf: options.licenceOneOf,
1118 languageOneOf: options.languageOneOf,
1119 tagsOneOf: options.tagsOneOf,
1120 tagsAllOf: options.tagsAllOf,
1121 filter: options.filter,
1122 withFiles: options.withFiles,
1123 accountId: options.accountId,
1124 videoChannelId: options.videoChannelId,
1125 videoPlaylistId: options.videoPlaylistId,
1126 includeLocalVideos: options.includeLocalVideos,
1128 historyOfUser: options.historyOfUser,
1130 search: options.search
1133 return VideoModel.getAvailableForApi(queryOptions, options.countVideos)
1136 static async searchAndPopulateAccountAndServer (options: {
1137 includeLocalVideos: boolean
1142 startDate?: string // ISO 8601
1143 endDate?: string // ISO 8601
1144 originallyPublishedStartDate?: string
1145 originallyPublishedEndDate?: string
1147 categoryOneOf?: number[]
1148 licenceOneOf?: number[]
1149 languageOneOf?: string[]
1150 tagsOneOf?: string[]
1151 tagsAllOf?: string[]
1152 durationMin?: number // seconds
1153 durationMax?: number // seconds
1154 user?: MUserAccountId
1155 filter?: VideoFilter
1157 const serverActor = await getServerActor()
1158 const queryOptions = {
1159 followerActorId: serverActor.id,
1160 serverAccountId: serverActor.Account.id,
1161 includeLocalVideos: options.includeLocalVideos,
1163 categoryOneOf: options.categoryOneOf,
1164 licenceOneOf: options.licenceOneOf,
1165 languageOneOf: options.languageOneOf,
1166 tagsOneOf: options.tagsOneOf,
1167 tagsAllOf: options.tagsAllOf,
1169 filter: options.filter,
1170 start: options.start,
1171 count: options.count,
1173 startDate: options.startDate,
1174 endDate: options.endDate,
1175 originallyPublishedStartDate: options.originallyPublishedStartDate,
1176 originallyPublishedEndDate: options.originallyPublishedEndDate,
1178 durationMin: options.durationMin,
1179 durationMax: options.durationMax,
1181 search: options.search
1184 return VideoModel.getAvailableForApi(queryOptions)
1187 static countLocalLives () {
1193 [Op.ne]: VideoState.LIVE_ENDED
1198 return VideoModel.count(options)
1201 static countLivesOfAccount (accountId: number) {
1207 [Op.ne]: VideoState.LIVE_ENDED
1213 model: VideoChannelModel.unscoped(),
1221 return VideoModel.count(options)
1224 static load (id: number | string, t?: Transaction): Promise<MVideoThumbnail> {
1225 const where = buildWhereIdOrUUID(id)
1231 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1234 static loadWithBlacklist (id: number | string, t?: Transaction): Promise<MVideoThumbnailBlacklist> {
1235 const where = buildWhereIdOrUUID(id)
1241 return VideoModel.scope([
1242 ScopeNames.WITH_THUMBNAILS,
1243 ScopeNames.WITH_BLACKLISTED
1247 static loadImmutableAttributes (id: number | string, t?: Transaction): Promise<MVideoImmutable> {
1250 where: buildWhereIdOrUUID(id),
1254 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1257 return ModelCache.Instance.doCache({
1258 cacheType: 'load-video-immutable-id',
1265 static loadWithRights (id: number | string, t?: Transaction): Promise<MVideoWithRights> {
1266 const where = buildWhereIdOrUUID(id)
1272 return VideoModel.scope([
1273 ScopeNames.WITH_BLACKLISTED,
1274 ScopeNames.WITH_USER_ID,
1275 ScopeNames.WITH_THUMBNAILS
1279 static loadOnlyId (id: number | string, t?: Transaction): Promise<MVideoIdThumbnail> {
1280 const where = buildWhereIdOrUUID(id)
1283 attributes: [ 'id' ],
1288 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1291 static loadWithFiles (id: number | string, t?: Transaction, logging?: boolean): Promise<MVideoWithAllFiles> {
1292 const where = buildWhereIdOrUUID(id)
1300 return VideoModel.scope([
1301 ScopeNames.WITH_WEBTORRENT_FILES,
1302 ScopeNames.WITH_STREAMING_PLAYLISTS,
1303 ScopeNames.WITH_THUMBNAILS
1307 static loadByUUID (uuid: string): Promise<MVideoThumbnail> {
1314 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1317 static loadByUrl (url: string, transaction?: Transaction): Promise<MVideoThumbnail> {
1318 const query: FindOptions = {
1325 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(query)
1328 static loadByUrlImmutableAttributes (url: string, transaction?: Transaction): Promise<MVideoImmutable> {
1330 const query: FindOptions = {
1337 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1340 return ModelCache.Instance.doCache({
1341 cacheType: 'load-video-immutable-url',
1348 static loadByUrlAndPopulateAccount (url: string, transaction?: Transaction): Promise<MVideoAccountLightBlacklistAllFiles> {
1349 const query: FindOptions = {
1356 return VideoModel.scope([
1357 ScopeNames.WITH_ACCOUNT_DETAILS,
1358 ScopeNames.WITH_WEBTORRENT_FILES,
1359 ScopeNames.WITH_STREAMING_PLAYLISTS,
1360 ScopeNames.WITH_THUMBNAILS,
1361 ScopeNames.WITH_BLACKLISTED
1365 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Transaction, userId?: number): Promise<MVideoFullLight> {
1366 const where = buildWhereIdOrUUID(id)
1369 order: [ [ 'Tags', 'name', 'ASC' ] ] as any,
1374 const scopes: (string | ScopeOptions)[] = [
1375 ScopeNames.WITH_TAGS,
1376 ScopeNames.WITH_BLACKLISTED,
1377 ScopeNames.WITH_ACCOUNT_DETAILS,
1378 ScopeNames.WITH_SCHEDULED_UPDATE,
1379 ScopeNames.WITH_WEBTORRENT_FILES,
1380 ScopeNames.WITH_STREAMING_PLAYLISTS,
1381 ScopeNames.WITH_THUMBNAILS,
1382 ScopeNames.WITH_LIVE
1386 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1394 static loadForGetAPI (parameters: {
1398 }): Promise<MVideoDetails> {
1399 const { id, t, userId } = parameters
1400 const where = buildWhereIdOrUUID(id)
1403 order: [ [ 'Tags', 'name', 'ASC' ] ] as any, // FIXME: sequelize typings
1408 const scopes: (string | ScopeOptions)[] = [
1409 ScopeNames.WITH_TAGS,
1410 ScopeNames.WITH_BLACKLISTED,
1411 ScopeNames.WITH_ACCOUNT_DETAILS,
1412 ScopeNames.WITH_SCHEDULED_UPDATE,
1413 ScopeNames.WITH_THUMBNAILS,
1414 ScopeNames.WITH_LIVE,
1415 { method: [ ScopeNames.WITH_WEBTORRENT_FILES, true ] },
1416 { method: [ ScopeNames.WITH_STREAMING_PLAYLISTS, true ] }
1420 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1428 static async getStats () {
1429 const totalLocalVideos = await VideoModel.count({
1435 let totalLocalVideoViews = await VideoModel.sum('views', {
1441 // Sequelize could return null...
1442 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1444 const { total: totalVideos } = await VideoModel.listForApi({
1447 sort: '-publishedAt',
1448 nsfw: buildNSFWFilter(),
1449 includeLocalVideos: true,
1455 totalLocalVideoViews,
1460 static incrementViews (id: number, views: number) {
1461 return VideoModel.increment('views', {
1469 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1470 // Instances only share videos
1471 const query = 'SELECT 1 FROM "videoShare" ' +
1472 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1473 'WHERE "actorFollow"."actorId" = $followerActorId AND "actorFollow"."state" = \'accepted\' AND "videoShare"."videoId" = $videoId ' +
1477 type: QueryTypes.SELECT as QueryTypes.SELECT,
1478 bind: { followerActorId, videoId },
1482 return VideoModel.sequelize.query(query, options)
1483 .then(results => results.length === 1)
1486 static bulkUpdateSupportField (videoChannel: MChannel, t: Transaction) {
1489 channelId: videoChannel.id
1494 return VideoModel.update({ support: videoChannel.support }, options)
1497 static getAllIdsFromChannel (videoChannel: MChannelId): Promise<number[]> {
1499 attributes: [ 'id' ],
1501 channelId: videoChannel.id
1505 return VideoModel.findAll(query)
1506 .then(videos => videos.map(v => v.id))
1509 // threshold corresponds to how many video the field should have to be returned
1510 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1511 const serverActor = await getServerActor()
1512 const followerActorId = serverActor.id
1514 const queryOptions: BuildVideosQueryOptions = {
1515 attributes: [ `"${field}"` ],
1516 group: `GROUP BY "${field}"`,
1517 having: `HAVING COUNT("${field}") >= ${threshold}`,
1521 serverAccountId: serverActor.Account.id,
1523 includeLocalVideos: true
1526 const { query, replacements } = buildListQuery(VideoModel, queryOptions)
1528 return this.sequelize.query<any>(query, { replacements, type: QueryTypes.SELECT })
1529 .then(rows => rows.map(r => r[field]))
1532 static buildTrendingQuery (trendingDays: number) {
1536 model: VideoViewModel,
1540 [Op.gte]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1546 private static async getAvailableForApi (
1547 options: BuildVideosQueryOptions,
1549 ): Promise<ResultList<VideoModel>> {
1550 function getCount () {
1551 if (countVideos !== true) return Promise.resolve(undefined)
1553 const countOptions = Object.assign({}, options, { isCount: true })
1554 const { query: queryCount, replacements: replacementsCount } = buildListQuery(VideoModel, countOptions)
1556 return VideoModel.sequelize.query<any>(queryCount, { replacements: replacementsCount, type: QueryTypes.SELECT })
1557 .then(rows => rows.length !== 0 ? rows[0].total : 0)
1560 function getModels () {
1561 if (options.count === 0) return Promise.resolve([])
1563 const { query, replacements, order } = buildListQuery(VideoModel, options)
1564 const queryModels = wrapForAPIResults(query, replacements, options, order)
1566 return VideoModel.sequelize.query<any>(queryModels, { replacements, type: QueryTypes.SELECT, nest: true })
1567 .then(rows => VideoModel.buildAPIResult(rows))
1570 const [ count, rows ] = await Promise.all([ getCount(), getModels() ])
1578 private static buildAPIResult (rows: any[]) {
1579 const videosMemo: { [ id: number ]: VideoModel } = {}
1580 const videoStreamingPlaylistMemo: { [ id: number ]: VideoStreamingPlaylistModel } = {}
1582 const thumbnailsDone = new Set<number>()
1583 const historyDone = new Set<number>()
1584 const videoFilesDone = new Set<number>()
1586 const videos: VideoModel[] = []
1588 const avatarKeys = [ 'id', 'filename', 'fileUrl', 'onDisk', 'createdAt', 'updatedAt' ]
1589 const actorKeys = [ 'id', 'preferredUsername', 'url', 'serverId', 'avatarId' ]
1590 const serverKeys = [ 'id', 'host' ]
1591 const videoFileKeys = [ 'id', 'createdAt', 'updatedAt', 'resolution', 'size', 'extname', 'infoHash', 'fps', 'videoId' ]
1592 const videoStreamingPlaylistKeys = [ 'id' ]
1616 'originallyPublishedAt',
1622 function buildActor (rowActor: any) {
1623 const avatarModel = rowActor.Avatar.id !== null
1624 ? new AvatarModel(pick(rowActor.Avatar, avatarKeys))
1627 const serverModel = rowActor.Server.id !== null
1628 ? new ServerModel(pick(rowActor.Server, serverKeys))
1631 const actorModel = new ActorModel(pick(rowActor, actorKeys))
1632 actorModel.Avatar = avatarModel
1633 actorModel.Server = serverModel
1638 for (const row of rows) {
1639 if (!videosMemo[row.id]) {
1641 const channel = row.VideoChannel
1642 const channelModel = new VideoChannelModel(pick(channel, [ 'id', 'name', 'description', 'actorId' ]))
1643 channelModel.Actor = buildActor(channel.Actor)
1645 const account = row.VideoChannel.Account
1646 const accountModel = new AccountModel(pick(account, [ 'id', 'name' ]))
1647 accountModel.Actor = buildActor(account.Actor)
1649 channelModel.Account = accountModel
1651 const videoModel = new VideoModel(pick(row, videoKeys))
1652 videoModel.VideoChannel = channelModel
1654 videoModel.UserVideoHistories = []
1655 videoModel.Thumbnails = []
1656 videoModel.VideoFiles = []
1657 videoModel.VideoStreamingPlaylists = []
1659 videosMemo[row.id] = videoModel
1660 // Don't take object value to have a sorted array
1661 videos.push(videoModel)
1664 const videoModel = videosMemo[row.id]
1666 if (row.userVideoHistory?.id && !historyDone.has(row.userVideoHistory.id)) {
1667 const historyModel = new UserVideoHistoryModel(pick(row.userVideoHistory, [ 'id', 'currentTime' ]))
1668 videoModel.UserVideoHistories.push(historyModel)
1670 historyDone.add(row.userVideoHistory.id)
1673 if (row.Thumbnails?.id && !thumbnailsDone.has(row.Thumbnails.id)) {
1674 const thumbnailModel = new ThumbnailModel(pick(row.Thumbnails, [ 'id', 'type', 'filename' ]))
1675 videoModel.Thumbnails.push(thumbnailModel)
1677 thumbnailsDone.add(row.Thumbnails.id)
1680 if (row.VideoFiles?.id && !videoFilesDone.has(row.VideoFiles.id)) {
1681 const videoFileModel = new VideoFileModel(pick(row.VideoFiles, videoFileKeys))
1682 videoModel.VideoFiles.push(videoFileModel)
1684 videoFilesDone.add(row.VideoFiles.id)
1687 if (row.VideoStreamingPlaylists?.id && !videoStreamingPlaylistMemo[row.VideoStreamingPlaylists.id]) {
1688 const streamingPlaylist = new VideoStreamingPlaylistModel(pick(row.VideoStreamingPlaylists, videoStreamingPlaylistKeys))
1689 streamingPlaylist.VideoFiles = []
1691 videoModel.VideoStreamingPlaylists.push(streamingPlaylist)
1693 videoStreamingPlaylistMemo[streamingPlaylist.id] = streamingPlaylist
1696 if (row.VideoStreamingPlaylists?.VideoFiles?.id && !videoFilesDone.has(row.VideoStreamingPlaylists.VideoFiles.id)) {
1697 const streamingPlaylist = videoStreamingPlaylistMemo[row.VideoStreamingPlaylists.id]
1699 const videoFileModel = new VideoFileModel(pick(row.VideoStreamingPlaylists.VideoFiles, videoFileKeys))
1700 streamingPlaylist.VideoFiles.push(videoFileModel)
1702 videoFilesDone.add(row.VideoStreamingPlaylists.VideoFiles.id)
1709 static getCategoryLabel (id: number) {
1710 return VIDEO_CATEGORIES[id] || 'Misc'
1713 static getLicenceLabel (id: number) {
1714 return VIDEO_LICENCES[id] || 'Unknown'
1717 static getLanguageLabel (id: string) {
1718 return VIDEO_LANGUAGES[id] || 'Unknown'
1721 static getPrivacyLabel (id: number) {
1722 return VIDEO_PRIVACIES[id] || 'Unknown'
1725 static getStateLabel (id: number) {
1726 return VIDEO_STATES[id] || 'Unknown'
1730 return !!this.VideoBlacklist
1734 return this.VideoChannel.Account.Actor.Server?.isBlocked() || this.VideoChannel.Account.isBlocked()
1737 getQualityFileBy<T extends MVideoWithFile> (this: T, fun: (files: MVideoFile[], it: (file: MVideoFile) => number) => MVideoFile) {
1738 if (Array.isArray(this.VideoFiles) && this.VideoFiles.length !== 0) {
1739 const file = fun(this.VideoFiles, file => file.resolution)
1741 return Object.assign(file, { Video: this })
1744 // No webtorrent files, try with streaming playlist files
1745 if (Array.isArray(this.VideoStreamingPlaylists) && this.VideoStreamingPlaylists.length !== 0) {
1746 const streamingPlaylistWithVideo = Object.assign(this.VideoStreamingPlaylists[0], { Video: this })
1748 const file = fun(streamingPlaylistWithVideo.VideoFiles, file => file.resolution)
1749 return Object.assign(file, { VideoStreamingPlaylist: streamingPlaylistWithVideo })
1755 getMaxQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1756 return this.getQualityFileBy(maxBy)
1759 getMinQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1760 return this.getQualityFileBy(minBy)
1763 getWebTorrentFile<T extends MVideoWithFile> (this: T, resolution: number): MVideoFileVideo {
1764 if (Array.isArray(this.VideoFiles) === false) return undefined
1766 const file = this.VideoFiles.find(f => f.resolution === resolution)
1767 if (!file) return undefined
1769 return Object.assign(file, { Video: this })
1772 async addAndSaveThumbnail (thumbnail: MThumbnail, transaction: Transaction) {
1773 thumbnail.videoId = this.id
1775 const savedThumbnail = await thumbnail.save({ transaction })
1777 if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = []
1779 // Already have this thumbnail, skip
1780 if (this.Thumbnails.find(t => t.id === savedThumbnail.id)) return
1782 this.Thumbnails.push(savedThumbnail)
1785 generateThumbnailName () {
1786 return this.uuid + '.jpg'
1790 if (Array.isArray(this.Thumbnails) === false) return undefined
1792 return this.Thumbnails.find(t => t.type === ThumbnailType.MINIATURE)
1795 generatePreviewName () {
1796 return this.uuid + '.jpg'
1800 return !!this.getPreview()
1804 if (Array.isArray(this.Thumbnails) === false) return undefined
1806 return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW)
1810 return this.remote === false
1813 getWatchStaticPath () {
1814 return '/videos/watch/' + this.uuid
1817 getEmbedStaticPath () {
1818 return '/videos/embed/' + this.uuid
1821 getMiniatureStaticPath () {
1822 const thumbnail = this.getMiniature()
1823 if (!thumbnail) return null
1825 return join(STATIC_PATHS.THUMBNAILS, thumbnail.filename)
1828 getPreviewStaticPath () {
1829 const preview = this.getPreview()
1830 if (!preview) return null
1832 // We use a local cache, so specify our cache endpoint instead of potential remote URL
1833 return join(LAZY_STATIC_PATHS.PREVIEWS, preview.filename)
1836 toFormattedJSON (this: MVideoFormattable, options?: VideoFormattingJSONOptions): Video {
1837 return videoModelToFormattedJSON(this, options)
1840 toFormattedDetailsJSON (this: MVideoFormattableDetails): VideoDetails {
1841 return videoModelToFormattedDetailsJSON(this)
1844 getFormattedVideoFilesJSON (): VideoFile[] {
1845 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1846 let files: MVideoFileRedundanciesOpt[] = []
1848 if (Array.isArray(this.VideoFiles)) {
1849 files = files.concat(this.VideoFiles)
1852 for (const p of (this.VideoStreamingPlaylists || [])) {
1853 files = files.concat(p.VideoFiles || [])
1856 return videoFilesModelToFormattedJSON(this, baseUrlHttp, baseUrlWs, files)
1859 toActivityPubObject (this: MVideoAP): VideoObject {
1860 return videoModelToActivityPubObject(this)
1863 getTruncatedDescription () {
1864 if (!this.description) return null
1866 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1867 return peertubeTruncate(this.description, { length: maxLength })
1870 getMaxQualityResolution () {
1871 const file = this.getMaxQualityFile()
1872 const videoOrPlaylist = file.getVideoOrStreamingPlaylist()
1873 const originalFilePath = getVideoFilePath(videoOrPlaylist, file)
1875 return getVideoFileResolution(originalFilePath)
1878 getDescriptionAPIPath () {
1879 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1882 getHLSPlaylist (): MStreamingPlaylistFilesVideo {
1883 if (!this.VideoStreamingPlaylists) return undefined
1885 const playlist = this.VideoStreamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
1886 playlist.Video = this
1891 setHLSPlaylist (playlist: MStreamingPlaylist) {
1892 const toAdd = [ playlist ] as [ VideoStreamingPlaylistModel ]
1894 if (Array.isArray(this.VideoStreamingPlaylists) === false || this.VideoStreamingPlaylists.length === 0) {
1895 this.VideoStreamingPlaylists = toAdd
1899 this.VideoStreamingPlaylists = this.VideoStreamingPlaylists
1900 .filter(s => s.type !== VideoStreamingPlaylistType.HLS)
1904 removeFile (videoFile: MVideoFile, isRedundancy = false) {
1905 const filePath = getVideoFilePath(this, videoFile, isRedundancy)
1906 return remove(filePath)
1907 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1910 removeTorrent (videoFile: MVideoFile) {
1911 const torrentPath = getTorrentFilePath(this, videoFile)
1912 return remove(torrentPath)
1913 .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err }))
1916 async removeStreamingPlaylistFiles (streamingPlaylist: MStreamingPlaylist, isRedundancy = false) {
1917 const directoryPath = getHLSDirectory(this, isRedundancy)
1919 await remove(directoryPath)
1921 if (isRedundancy !== true) {
1922 const streamingPlaylistWithFiles = streamingPlaylist as MStreamingPlaylistFilesVideo
1923 streamingPlaylistWithFiles.Video = this
1925 if (!Array.isArray(streamingPlaylistWithFiles.VideoFiles)) {
1926 streamingPlaylistWithFiles.VideoFiles = await streamingPlaylistWithFiles.$get('VideoFiles')
1929 // Remove physical files and torrents
1931 streamingPlaylistWithFiles.VideoFiles.map(file => streamingPlaylistWithFiles.removeTorrent(file))
1937 if (this.isOwned()) return false
1939 return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)
1942 hasPrivacyForFederation () {
1943 return isPrivacyForFederation(this.privacy)
1946 hasStateForFederation () {
1947 return isStateForFederation(this.state)
1950 isNewVideo (newPrivacy: VideoPrivacy) {
1951 return this.hasPrivacyForFederation() === false && isPrivacyForFederation(newPrivacy) === true
1955 this.changed('updatedAt', true)
1961 return this.privacy === VideoPrivacy.PRIVATE || this.privacy === VideoPrivacy.INTERNAL || !!this.VideoBlacklist
1964 setPrivacy (newPrivacy: VideoPrivacy) {
1965 if (this.privacy === VideoPrivacy.PRIVATE && newPrivacy !== VideoPrivacy.PRIVATE) {
1966 this.publishedAt = new Date()
1969 this.privacy = newPrivacy
1973 return this.privacy === VideoPrivacy.PRIVATE ||
1974 this.privacy === VideoPrivacy.UNLISTED ||
1975 this.privacy === VideoPrivacy.INTERNAL
1978 async publishIfNeededAndSave (t: Transaction) {
1979 if (this.state !== VideoState.PUBLISHED) {
1980 this.state = VideoState.PUBLISHED
1981 this.publishedAt = new Date()
1982 await this.save({ transaction: t })
1991 if (this.isOwned()) {
1993 baseUrlHttp: WEBSERVER.URL,
1994 baseUrlWs: WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT
1999 baseUrlHttp: REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host,
2000 baseUrlWs: REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
2004 getTrackerUrls (baseUrlHttp: string, baseUrlWs: string) {
2005 return [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
2008 getTorrentUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2009 return baseUrlHttp + STATIC_PATHS.TORRENTS + getTorrentFileName(this, videoFile)
2012 getTorrentDownloadUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2013 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + getTorrentFileName(this, videoFile)
2016 getVideoFileUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2017 return baseUrlHttp + STATIC_PATHS.WEBSEED + getVideoFilename(this, videoFile)
2020 getVideoFileMetadataUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2021 const path = '/api/v1/videos/'
2023 return this.isOwned()
2024 ? baseUrlHttp + path + this.uuid + '/metadata/' + videoFile.id
2025 : videoFile.metadataUrl
2028 getVideoRedundancyUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2029 return baseUrlHttp + STATIC_PATHS.REDUNDANCY + getVideoFilename(this, videoFile)
2032 getVideoFileDownloadUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2033 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + getVideoFilename(this, videoFile)
2036 getBandwidthBits (videoFile: MVideoFile) {
2037 return Math.ceil((videoFile.size * 8) / this.duration)