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, 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 } from '@server/helpers/video'
29 import { getHLSDirectory, getTorrentFileName, getTorrentFilePath, getVideoFilename, getVideoFilePath } from '@server/lib/video-paths'
30 import { getServerActor } from '@server/models/application/application'
31 import { ModelCache } from '@server/models/model-cache'
32 import { VideoFile } from '@shared/models/videos/video-file.model'
33 import { ResultList, UserRight, VideoPrivacy, VideoState } from '../../../shared'
34 import { VideoObject } from '../../../shared/models/activitypub/objects'
35 import { Video, VideoDetails } from '../../../shared/models/videos'
36 import { ThumbnailType } from '../../../shared/models/videos/thumbnail.type'
37 import { VideoFilter } from '../../../shared/models/videos/video-query.type'
38 import { VideoStreamingPlaylistType } from '../../../shared/models/videos/video-streaming-playlist.type'
39 import { peertubeTruncate } from '../../helpers/core-utils'
40 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
41 import { isBooleanValid } from '../../helpers/custom-validators/misc'
44 isVideoDescriptionValid,
52 } from '../../helpers/custom-validators/videos'
53 import { getVideoFileResolution } from '../../helpers/ffmpeg-utils'
54 import { logger } from '../../helpers/logger'
55 import { CONFIG } from '../../initializers/config'
62 STATIC_DOWNLOAD_PATHS,
70 } from '../../initializers/constants'
71 import { sendDeleteVideo } from '../../lib/activitypub/send'
74 MChannelAccountDefault,
77 MStreamingPlaylistFilesVideo,
81 MVideoAccountLightBlacklistAllFiles,
86 MVideoFormattableDetails,
92 MVideoThumbnailBlacklist,
96 } from '../../types/models'
97 import { MThumbnail } from '../../types/models/video/thumbnail'
98 import { MVideoFile, MVideoFileRedundanciesOpt, MVideoFileStreamingPlaylistVideo } from '../../types/models/video/video-file'
99 import { VideoAbuseModel } from '../abuse/video-abuse'
100 import { AccountModel } from '../account/account'
101 import { AccountVideoRateModel } from '../account/account-video-rate'
102 import { UserVideoHistoryModel } from '../account/user-video-history'
103 import { ActorModel } from '../activitypub/actor'
104 import { AvatarModel } from '../avatar/avatar'
105 import { VideoRedundancyModel } from '../redundancy/video-redundancy'
106 import { ServerModel } from '../server/server'
107 import { buildTrigramSearchIndex, buildWhereIdOrUUID, getVideoSort, isOutdated, throwIfNotValid } from '../utils'
108 import { ScheduleVideoUpdateModel } from './schedule-video-update'
109 import { TagModel } from './tag'
110 import { ThumbnailModel } from './thumbnail'
111 import { VideoBlacklistModel } from './video-blacklist'
112 import { VideoCaptionModel } from './video-caption'
113 import { ScopeNames as VideoChannelScopeNames, SummaryOptions, VideoChannelModel } from './video-channel'
114 import { VideoCommentModel } from './video-comment'
115 import { VideoFileModel } from './video-file'
117 videoFilesModelToFormattedJSON,
118 VideoFormattingJSONOptions,
119 videoModelToActivityPubObject,
120 videoModelToFormattedDetailsJSON,
121 videoModelToFormattedJSON
122 } from './video-format-utils'
123 import { VideoImportModel } from './video-import'
124 import { VideoPlaylistElementModel } from './video-playlist-element'
125 import { buildListQuery, BuildVideosQueryOptions, wrapForAPIResults } from './video-query-builder'
126 import { VideoShareModel } from './video-share'
127 import { VideoStreamingPlaylistModel } from './video-streaming-playlist'
128 import { VideoTagModel } from './video-tag'
129 import { VideoViewModel } from './video-view'
131 export enum ScopeNames {
132 AVAILABLE_FOR_LIST_IDS = 'AVAILABLE_FOR_LIST_IDS',
134 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
135 WITH_TAGS = 'WITH_TAGS',
136 WITH_WEBTORRENT_FILES = 'WITH_WEBTORRENT_FILES',
137 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
138 WITH_BLACKLISTED = 'WITH_BLACKLISTED',
139 WITH_USER_HISTORY = 'WITH_USER_HISTORY',
140 WITH_STREAMING_PLAYLISTS = 'WITH_STREAMING_PLAYLISTS',
141 WITH_USER_ID = 'WITH_USER_ID',
142 WITH_IMMUTABLE_ATTRIBUTES = 'WITH_IMMUTABLE_ATTRIBUTES',
143 WITH_THUMBNAILS = 'WITH_THUMBNAILS'
146 export type ForAPIOptions = {
149 videoPlaylistId?: number
153 withAccountBlockerIds?: number[]
156 export type AvailableForListIDsOptions = {
157 serverAccountId: number
158 followerActorId: number
159 includeLocalVideos: boolean
161 attributesType?: 'none' | 'id' | 'all'
164 categoryOneOf?: number[]
166 licenceOneOf?: number[]
167 languageOneOf?: string[]
174 videoChannelId?: number
176 videoPlaylistId?: number
178 trendingDays?: number
179 user?: MUserAccountId
180 historyOfUser?: MUserId
182 baseWhere?: WhereOptions[]
186 [ScopeNames.WITH_IMMUTABLE_ATTRIBUTES]: {
187 attributes: [ 'id', 'url', 'uuid', 'remote' ]
189 [ScopeNames.FOR_API]: (options: ForAPIOptions) => {
190 const query: FindOptions = {
193 model: VideoChannelModel.scope({
195 VideoChannelScopeNames.SUMMARY, {
197 withAccountBlockerIds: options.withAccountBlockerIds
204 attributes: [ 'type', 'filename' ],
205 model: ThumbnailModel,
219 if (options.withFiles === true) {
221 model: VideoFileModel,
226 if (options.videoPlaylistId) {
228 model: VideoPlaylistElementModel.unscoped(),
231 videoPlaylistId: options.videoPlaylistId
238 [ScopeNames.WITH_THUMBNAILS]: {
241 model: ThumbnailModel,
246 [ScopeNames.WITH_USER_ID]: {
249 attributes: [ 'accountId' ],
250 model: VideoChannelModel.unscoped(),
254 attributes: [ 'userId' ],
255 model: AccountModel.unscoped(),
262 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
265 model: VideoChannelModel.unscoped(),
270 exclude: [ 'privateKey', 'publicKey' ]
272 model: ActorModel.unscoped(),
276 attributes: [ 'host' ],
277 model: ServerModel.unscoped(),
281 model: AvatarModel.unscoped(),
287 model: AccountModel.unscoped(),
291 model: ActorModel.unscoped(),
293 exclude: [ 'privateKey', 'publicKey' ]
298 attributes: [ 'host' ],
299 model: ServerModel.unscoped(),
303 model: AvatarModel.unscoped(),
314 [ScopeNames.WITH_TAGS]: {
315 include: [ TagModel ]
317 [ScopeNames.WITH_BLACKLISTED]: {
320 attributes: [ 'id', 'reason', 'unfederated' ],
321 model: VideoBlacklistModel,
326 [ScopeNames.WITH_WEBTORRENT_FILES]: (withRedundancies = false) => {
327 let subInclude: any[] = []
329 if (withRedundancies === true) {
332 attributes: [ 'fileUrl' ],
333 model: VideoRedundancyModel.unscoped(),
342 model: VideoFileModel,
343 separate: true, // We may have multiple files, having multiple redundancies so let's separate this join
350 [ScopeNames.WITH_STREAMING_PLAYLISTS]: (withRedundancies = false) => {
351 const subInclude: IncludeOptions[] = [
353 model: VideoFileModel,
358 if (withRedundancies === true) {
360 attributes: [ 'fileUrl' ],
361 model: VideoRedundancyModel.unscoped(),
369 model: VideoStreamingPlaylistModel.unscoped(),
370 separate: true, // We may have multiple streaming playlists, having multiple redundancies so let's separate this join
377 [ScopeNames.WITH_SCHEDULED_UPDATE]: {
380 model: ScheduleVideoUpdateModel.unscoped(),
385 [ScopeNames.WITH_USER_HISTORY]: (userId: number) => {
389 attributes: [ 'currentTime' ],
390 model: UserVideoHistoryModel.unscoped(),
403 buildTrigramSearchIndex('video_name_trigram', 'name'),
405 { fields: [ 'createdAt' ] },
408 { name: 'publishedAt', order: 'DESC' },
409 { name: 'id', order: 'ASC' }
412 { fields: [ 'duration' ] },
413 { fields: [ 'views' ] },
414 { fields: [ 'channelId' ] },
416 fields: [ 'originallyPublishedAt' ],
418 originallyPublishedAt: {
424 fields: [ 'category' ], // We don't care videos with an unknown category
432 fields: [ 'licence' ], // We don't care videos with an unknown licence
440 fields: [ 'language' ], // We don't care videos with an unknown language
448 fields: [ 'nsfw' ], // Most of the videos are not NSFW
454 fields: [ 'remote' ], // Only index local videos
469 export class VideoModel extends Model<VideoModel> {
472 @Default(DataType.UUIDV4)
474 @Column(DataType.UUID)
478 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
484 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category', true))
490 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence', true))
496 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language', true))
497 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
501 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
503 privacy: VideoPrivacy
506 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
512 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description', true))
513 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
518 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support', true))
519 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
523 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
558 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
559 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
564 commentsEnabled: boolean
568 downloadEnabled: boolean
572 waitTranscoding: boolean
576 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
587 @Default(DataType.NOW)
594 originallyPublishedAt: Date
596 @ForeignKey(() => VideoChannelModel)
600 @BelongsTo(() => VideoChannelModel, {
606 VideoChannel: VideoChannelModel
608 @BelongsToMany(() => TagModel, {
609 foreignKey: 'videoId',
610 through: () => VideoTagModel,
615 @HasMany(() => ThumbnailModel, {
623 Thumbnails: ThumbnailModel[]
625 @HasMany(() => VideoPlaylistElementModel, {
632 VideoPlaylistElements: VideoPlaylistElementModel[]
634 @HasMany(() => VideoAbuseModel, {
641 VideoAbuses: VideoAbuseModel[]
643 @HasMany(() => VideoFileModel, {
651 VideoFiles: VideoFileModel[]
653 @HasMany(() => VideoStreamingPlaylistModel, {
661 VideoStreamingPlaylists: VideoStreamingPlaylistModel[]
663 @HasMany(() => VideoShareModel, {
670 VideoShares: VideoShareModel[]
672 @HasMany(() => AccountVideoRateModel, {
679 AccountVideoRates: AccountVideoRateModel[]
681 @HasMany(() => VideoCommentModel, {
689 VideoComments: VideoCommentModel[]
691 @HasMany(() => VideoViewModel, {
698 VideoViews: VideoViewModel[]
700 @HasMany(() => UserVideoHistoryModel, {
707 UserVideoHistories: UserVideoHistoryModel[]
709 @HasOne(() => ScheduleVideoUpdateModel, {
716 ScheduleVideoUpdate: ScheduleVideoUpdateModel
718 @HasOne(() => VideoBlacklistModel, {
725 VideoBlacklist: VideoBlacklistModel
727 @HasOne(() => VideoImportModel, {
734 VideoImport: VideoImportModel
736 @HasMany(() => VideoCaptionModel, {
743 ['separate' as any]: true
745 VideoCaptions: VideoCaptionModel[]
748 static async sendDelete (instance: MVideoAccountLight, options) {
749 if (instance.isOwned()) {
750 if (!instance.VideoChannel) {
751 instance.VideoChannel = await instance.$get('VideoChannel', {
756 transaction: options.transaction
757 }) as MChannelAccountDefault
760 return sendDeleteVideo(instance, options.transaction)
767 static async removeFiles (instance: VideoModel) {
768 const tasks: Promise<any>[] = []
770 logger.info('Removing files of video %s.', instance.url)
772 if (instance.isOwned()) {
773 if (!Array.isArray(instance.VideoFiles)) {
774 instance.VideoFiles = await instance.$get('VideoFiles')
777 // Remove physical files and torrents
778 instance.VideoFiles.forEach(file => {
779 tasks.push(instance.removeFile(file))
780 tasks.push(instance.removeTorrent(file))
783 // Remove playlists file
784 if (!Array.isArray(instance.VideoStreamingPlaylists)) {
785 instance.VideoStreamingPlaylists = await instance.$get('VideoStreamingPlaylists')
788 for (const p of instance.VideoStreamingPlaylists) {
789 tasks.push(instance.removeStreamingPlaylistFiles(p))
793 // Do not wait video deletion because we could be in a transaction
796 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
803 static invalidateCache (instance: VideoModel) {
804 ModelCache.Instance.invalidateCache('video', instance.id)
808 static async saveEssentialDataToAbuses (instance: VideoModel, options) {
809 const tasks: Promise<any>[] = []
811 if (!Array.isArray(instance.VideoAbuses)) {
812 instance.VideoAbuses = await instance.$get('VideoAbuses')
814 if (instance.VideoAbuses.length === 0) return undefined
817 logger.info('Saving video abuses details of video %s.', instance.url)
819 const details = instance.toFormattedDetailsJSON()
821 for (const abuse of instance.VideoAbuses) {
822 abuse.deletedVideo = details
823 tasks.push(abuse.save({ transaction: options.transaction }))
828 logger.error('Some errors when saving details of video %s in its abuses before destroy hook.', instance.uuid, { err })
834 static listLocal (): Bluebird<MVideoWithAllFiles[]> {
841 return VideoModel.scope([
842 ScopeNames.WITH_WEBTORRENT_FILES,
843 ScopeNames.WITH_STREAMING_PLAYLISTS,
844 ScopeNames.WITH_THUMBNAILS
848 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
849 function getRawQuery (select: string) {
850 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
851 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
852 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
853 'WHERE "Account"."actorId" = ' + actorId
854 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
855 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
856 'WHERE "VideoShare"."actorId" = ' + actorId
858 return `(${queryVideo}) UNION (${queryVideoShare})`
861 const rawQuery = getRawQuery('"Video"."id"')
862 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
868 order: getVideoSort('-createdAt', [ 'Tags', 'name', 'ASC' ] as any), // FIXME: sequelize typings
871 [Op.in]: Sequelize.literal('(' + rawQuery + ')')
873 [Op.or]: getPrivaciesForFederation()
877 attributes: [ 'language', 'fileUrl' ],
878 model: VideoCaptionModel.unscoped(),
882 attributes: [ 'id', 'url' ],
883 model: VideoShareModel.unscoped(),
885 // We only want videos shared by this actor
900 attributes: [ 'id', 'url' ],
901 model: ActorModel.unscoped()
906 model: VideoChannelModel.unscoped(),
910 attributes: [ 'name' ],
911 model: AccountModel.unscoped(),
915 attributes: [ 'id', 'url', 'followersUrl' ],
916 model: ActorModel.unscoped(),
922 attributes: [ 'id', 'url', 'followersUrl' ],
923 model: ActorModel.unscoped(),
933 return Bluebird.all([
934 VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findAll(query),
935 VideoModel.sequelize.query<{ total: string }>(rawCountQuery, { type: QueryTypes.SELECT })
936 ]).then(([ rows, totals ]) => {
937 // totals: totalVideos + totalVideoShares
939 let totalVideoShares = 0
940 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
941 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
943 const total = totalVideos + totalVideoShares
951 static listUserVideosForApi (
958 function buildBaseQuery (): FindOptions {
962 order: getVideoSort(sort),
965 model: VideoChannelModel,
981 baseQuery = Object.assign(baseQuery, {
984 [Op.iLike]: '%' + search + '%'
993 const countQuery = buildBaseQuery()
994 const findQuery = buildBaseQuery()
996 const findScopes: (string | ScopeOptions)[] = [
997 ScopeNames.WITH_SCHEDULED_UPDATE,
998 ScopeNames.WITH_BLACKLISTED,
999 ScopeNames.WITH_THUMBNAILS
1002 return Promise.all([
1003 VideoModel.count(countQuery),
1004 VideoModel.scope(findScopes).findAll<MVideoForUser>(findQuery)
1005 ]).then(([ count, rows ]) => {
1013 static async listForApi (options: {
1018 includeLocalVideos: boolean
1020 categoryOneOf?: number[]
1021 licenceOneOf?: number[]
1022 languageOneOf?: string[]
1023 tagsOneOf?: string[]
1024 tagsAllOf?: string[]
1025 filter?: VideoFilter
1027 videoChannelId?: number
1028 followerActorId?: number
1029 videoPlaylistId?: number
1030 trendingDays?: number
1031 user?: MUserAccountId
1032 historyOfUser?: MUserId
1033 countVideos?: boolean
1035 if (options.filter && options.filter === 'all-local' && !options.user.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1036 throw new Error('Try to filter all-local but no user has not the see all videos right')
1039 const trendingDays = options.sort.endsWith('trending')
1040 ? CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1043 const serverActor = await getServerActor()
1045 // followerActorId === null has a meaning, so just check undefined
1046 const followerActorId = options.followerActorId !== undefined
1047 ? options.followerActorId
1050 const queryOptions = {
1051 start: options.start,
1052 count: options.count,
1055 serverAccountId: serverActor.Account.id,
1057 categoryOneOf: options.categoryOneOf,
1058 licenceOneOf: options.licenceOneOf,
1059 languageOneOf: options.languageOneOf,
1060 tagsOneOf: options.tagsOneOf,
1061 tagsAllOf: options.tagsAllOf,
1062 filter: options.filter,
1063 withFiles: options.withFiles,
1064 accountId: options.accountId,
1065 videoChannelId: options.videoChannelId,
1066 videoPlaylistId: options.videoPlaylistId,
1067 includeLocalVideos: options.includeLocalVideos,
1069 historyOfUser: options.historyOfUser,
1073 return VideoModel.getAvailableForApi(queryOptions, options.countVideos)
1076 static async searchAndPopulateAccountAndServer (options: {
1077 includeLocalVideos: boolean
1082 startDate?: string // ISO 8601
1083 endDate?: string // ISO 8601
1084 originallyPublishedStartDate?: string
1085 originallyPublishedEndDate?: string
1087 categoryOneOf?: number[]
1088 licenceOneOf?: number[]
1089 languageOneOf?: string[]
1090 tagsOneOf?: string[]
1091 tagsAllOf?: string[]
1092 durationMin?: number // seconds
1093 durationMax?: number // seconds
1094 user?: MUserAccountId
1095 filter?: VideoFilter
1097 const serverActor = await getServerActor()
1098 const queryOptions = {
1099 followerActorId: serverActor.id,
1100 serverAccountId: serverActor.Account.id,
1101 includeLocalVideos: options.includeLocalVideos,
1103 categoryOneOf: options.categoryOneOf,
1104 licenceOneOf: options.licenceOneOf,
1105 languageOneOf: options.languageOneOf,
1106 tagsOneOf: options.tagsOneOf,
1107 tagsAllOf: options.tagsAllOf,
1109 filter: options.filter,
1110 start: options.start,
1111 count: options.count,
1113 startDate: options.startDate,
1114 endDate: options.endDate,
1115 originallyPublishedStartDate: options.originallyPublishedStartDate,
1116 originallyPublishedEndDate: options.originallyPublishedEndDate,
1118 durationMin: options.durationMin,
1119 durationMax: options.durationMax,
1121 search: options.search
1124 return VideoModel.getAvailableForApi(queryOptions)
1127 static load (id: number | string, t?: Transaction): Bluebird<MVideoThumbnail> {
1128 const where = buildWhereIdOrUUID(id)
1134 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1137 static loadWithBlacklist (id: number | string, t?: Transaction): Bluebird<MVideoThumbnailBlacklist> {
1138 const where = buildWhereIdOrUUID(id)
1144 return VideoModel.scope([
1145 ScopeNames.WITH_THUMBNAILS,
1146 ScopeNames.WITH_BLACKLISTED
1150 static loadImmutableAttributes (id: number | string, t?: Transaction): Bluebird<MVideoImmutable> {
1153 where: buildWhereIdOrUUID(id),
1157 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1160 return ModelCache.Instance.doCache({
1161 cacheType: 'load-video-immutable-id',
1168 static loadWithRights (id: number | string, t?: Transaction): Bluebird<MVideoWithRights> {
1169 const where = buildWhereIdOrUUID(id)
1175 return VideoModel.scope([
1176 ScopeNames.WITH_BLACKLISTED,
1177 ScopeNames.WITH_USER_ID,
1178 ScopeNames.WITH_THUMBNAILS
1182 static loadOnlyId (id: number | string, t?: Transaction): Bluebird<MVideoIdThumbnail> {
1183 const where = buildWhereIdOrUUID(id)
1186 attributes: [ 'id' ],
1191 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1194 static loadWithFiles (id: number | string, t?: Transaction, logging?: boolean): Bluebird<MVideoWithAllFiles> {
1195 const where = buildWhereIdOrUUID(id)
1203 return VideoModel.scope([
1204 ScopeNames.WITH_WEBTORRENT_FILES,
1205 ScopeNames.WITH_STREAMING_PLAYLISTS,
1206 ScopeNames.WITH_THUMBNAILS
1210 static loadByUUID (uuid: string): Bluebird<MVideoThumbnail> {
1217 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1220 static loadByUrl (url: string, transaction?: Transaction): Bluebird<MVideoThumbnail> {
1221 const query: FindOptions = {
1228 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(query)
1231 static loadByUrlImmutableAttributes (url: string, transaction?: Transaction): Bluebird<MVideoImmutable> {
1233 const query: FindOptions = {
1240 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1243 return ModelCache.Instance.doCache({
1244 cacheType: 'load-video-immutable-url',
1251 static loadByUrlAndPopulateAccount (url: string, transaction?: Transaction): Bluebird<MVideoAccountLightBlacklistAllFiles> {
1252 const query: FindOptions = {
1259 return VideoModel.scope([
1260 ScopeNames.WITH_ACCOUNT_DETAILS,
1261 ScopeNames.WITH_WEBTORRENT_FILES,
1262 ScopeNames.WITH_STREAMING_PLAYLISTS,
1263 ScopeNames.WITH_THUMBNAILS,
1264 ScopeNames.WITH_BLACKLISTED
1268 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Transaction, userId?: number): Bluebird<MVideoFullLight> {
1269 const where = buildWhereIdOrUUID(id)
1272 order: [ [ 'Tags', 'name', 'ASC' ] ] as any,
1277 const scopes: (string | ScopeOptions)[] = [
1278 ScopeNames.WITH_TAGS,
1279 ScopeNames.WITH_BLACKLISTED,
1280 ScopeNames.WITH_ACCOUNT_DETAILS,
1281 ScopeNames.WITH_SCHEDULED_UPDATE,
1282 ScopeNames.WITH_WEBTORRENT_FILES,
1283 ScopeNames.WITH_STREAMING_PLAYLISTS,
1284 ScopeNames.WITH_THUMBNAILS
1288 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1296 static loadForGetAPI (parameters: {
1300 }): Bluebird<MVideoDetails> {
1301 const { id, t, userId } = parameters
1302 const where = buildWhereIdOrUUID(id)
1305 order: [ [ 'Tags', 'name', 'ASC' ] ] as any, // FIXME: sequelize typings
1310 const scopes: (string | ScopeOptions)[] = [
1311 ScopeNames.WITH_TAGS,
1312 ScopeNames.WITH_BLACKLISTED,
1313 ScopeNames.WITH_ACCOUNT_DETAILS,
1314 ScopeNames.WITH_SCHEDULED_UPDATE,
1315 ScopeNames.WITH_THUMBNAILS,
1316 { method: [ ScopeNames.WITH_WEBTORRENT_FILES, true ] },
1317 { method: [ ScopeNames.WITH_STREAMING_PLAYLISTS, true ] }
1321 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1329 static async getStats () {
1330 const totalLocalVideos = await VideoModel.count({
1336 let totalLocalVideoViews = await VideoModel.sum('views', {
1342 // Sequelize could return null...
1343 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1345 const { total: totalVideos } = await VideoModel.listForApi({
1348 sort: '-publishedAt',
1349 nsfw: buildNSFWFilter(),
1350 includeLocalVideos: true,
1356 totalLocalVideoViews,
1361 static incrementViews (id: number, views: number) {
1362 return VideoModel.increment('views', {
1370 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1371 // Instances only share videos
1372 const query = 'SELECT 1 FROM "videoShare" ' +
1373 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1374 'WHERE "actorFollow"."actorId" = $followerActorId AND "actorFollow"."state" = \'accepted\' AND "videoShare"."videoId" = $videoId ' +
1378 type: QueryTypes.SELECT as QueryTypes.SELECT,
1379 bind: { followerActorId, videoId },
1383 return VideoModel.sequelize.query(query, options)
1384 .then(results => results.length === 1)
1387 static bulkUpdateSupportField (videoChannel: MChannel, t: Transaction) {
1390 channelId: videoChannel.id
1395 return VideoModel.update({ support: videoChannel.support }, options)
1398 static getAllIdsFromChannel (videoChannel: MChannelId): Bluebird<number[]> {
1400 attributes: [ 'id' ],
1402 channelId: videoChannel.id
1406 return VideoModel.findAll(query)
1407 .then(videos => videos.map(v => v.id))
1410 // threshold corresponds to how many video the field should have to be returned
1411 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1412 const serverActor = await getServerActor()
1413 const followerActorId = serverActor.id
1415 const queryOptions: BuildVideosQueryOptions = {
1416 attributes: [ `"${field}"` ],
1417 group: `GROUP BY "${field}"`,
1418 having: `HAVING COUNT("${field}") >= ${threshold}`,
1422 serverAccountId: serverActor.Account.id,
1424 includeLocalVideos: true
1427 const { query, replacements } = buildListQuery(VideoModel, queryOptions)
1429 return this.sequelize.query<any>(query, { replacements, type: QueryTypes.SELECT })
1430 .then(rows => rows.map(r => r[field]))
1433 static buildTrendingQuery (trendingDays: number) {
1437 model: VideoViewModel,
1441 [Op.gte]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1447 private static async getAvailableForApi (
1448 options: BuildVideosQueryOptions,
1450 ): Promise<ResultList<VideoModel>> {
1451 function getCount () {
1452 if (countVideos !== true) return Promise.resolve(undefined)
1454 const countOptions = Object.assign({}, options, { isCount: true })
1455 const { query: queryCount, replacements: replacementsCount } = buildListQuery(VideoModel, countOptions)
1457 return VideoModel.sequelize.query<any>(queryCount, { replacements: replacementsCount, type: QueryTypes.SELECT })
1458 .then(rows => rows.length !== 0 ? rows[0].total : 0)
1461 function getModels () {
1462 if (options.count === 0) return Promise.resolve([])
1464 const { query, replacements, order } = buildListQuery(VideoModel, options)
1465 const queryModels = wrapForAPIResults(query, replacements, options, order)
1467 return VideoModel.sequelize.query<any>(queryModels, { replacements, type: QueryTypes.SELECT, nest: true })
1468 .then(rows => VideoModel.buildAPIResult(rows))
1471 const [ count, rows ] = await Promise.all([ getCount(), getModels() ])
1479 private static buildAPIResult (rows: any[]) {
1480 const videosMemo: { [ id: number ]: VideoModel } = {}
1481 const videoStreamingPlaylistMemo: { [ id: number ]: VideoStreamingPlaylistModel } = {}
1483 const thumbnailsDone = new Set<number>()
1484 const historyDone = new Set<number>()
1485 const videoFilesDone = new Set<number>()
1487 const videos: VideoModel[] = []
1489 const avatarKeys = [ 'id', 'filename', 'fileUrl', 'onDisk', 'createdAt', 'updatedAt' ]
1490 const actorKeys = [ 'id', 'preferredUsername', 'url', 'serverId', 'avatarId' ]
1491 const serverKeys = [ 'id', 'host' ]
1492 const videoFileKeys = [ 'id', 'createdAt', 'updatedAt', 'resolution', 'size', 'extname', 'infoHash', 'fps', 'videoId' ]
1493 const videoStreamingPlaylistKeys = [ 'id' ]
1516 'originallyPublishedAt',
1522 function buildActor (rowActor: any) {
1523 const avatarModel = rowActor.Avatar.id !== null
1524 ? new AvatarModel(pick(rowActor.Avatar, avatarKeys))
1527 const serverModel = rowActor.Server.id !== null
1528 ? new ServerModel(pick(rowActor.Server, serverKeys))
1531 const actorModel = new ActorModel(pick(rowActor, actorKeys))
1532 actorModel.Avatar = avatarModel
1533 actorModel.Server = serverModel
1538 for (const row of rows) {
1539 if (!videosMemo[row.id]) {
1541 const channel = row.VideoChannel
1542 const channelModel = new VideoChannelModel(pick(channel, [ 'id', 'name', 'description', 'actorId' ]))
1543 channelModel.Actor = buildActor(channel.Actor)
1545 const account = row.VideoChannel.Account
1546 const accountModel = new AccountModel(pick(account, [ 'id', 'name' ]))
1547 accountModel.Actor = buildActor(account.Actor)
1549 channelModel.Account = accountModel
1551 const videoModel = new VideoModel(pick(row, videoKeys))
1552 videoModel.VideoChannel = channelModel
1554 videoModel.UserVideoHistories = []
1555 videoModel.Thumbnails = []
1556 videoModel.VideoFiles = []
1557 videoModel.VideoStreamingPlaylists = []
1559 videosMemo[row.id] = videoModel
1560 // Don't take object value to have a sorted array
1561 videos.push(videoModel)
1564 const videoModel = videosMemo[row.id]
1566 if (row.userVideoHistory?.id && !historyDone.has(row.userVideoHistory.id)) {
1567 const historyModel = new UserVideoHistoryModel(pick(row.userVideoHistory, [ 'id', 'currentTime' ]))
1568 videoModel.UserVideoHistories.push(historyModel)
1570 historyDone.add(row.userVideoHistory.id)
1573 if (row.Thumbnails?.id && !thumbnailsDone.has(row.Thumbnails.id)) {
1574 const thumbnailModel = new ThumbnailModel(pick(row.Thumbnails, [ 'id', 'type', 'filename' ]))
1575 videoModel.Thumbnails.push(thumbnailModel)
1577 thumbnailsDone.add(row.Thumbnails.id)
1580 if (row.VideoFiles?.id && !videoFilesDone.has(row.VideoFiles.id)) {
1581 const videoFileModel = new VideoFileModel(pick(row.VideoFiles, videoFileKeys))
1582 videoModel.VideoFiles.push(videoFileModel)
1584 videoFilesDone.add(row.VideoFiles.id)
1587 if (row.VideoFiles?.id && !videoFilesDone.has(row.VideoFiles.id)) {
1588 const videoFileModel = new VideoFileModel(pick(row.VideoFiles, videoFileKeys))
1589 videoModel.VideoFiles.push(videoFileModel)
1591 videoFilesDone.add(row.VideoFiles.id)
1594 if (row.VideoStreamingPlaylists?.id && !videoStreamingPlaylistMemo[row.VideoStreamingPlaylists.id]) {
1595 const streamingPlaylist = new VideoStreamingPlaylistModel(pick(row.VideoStreamingPlaylists, videoStreamingPlaylistKeys))
1596 streamingPlaylist.VideoFiles = []
1598 videoModel.VideoStreamingPlaylists.push(streamingPlaylist)
1600 videoStreamingPlaylistMemo[streamingPlaylist.id] = streamingPlaylist
1603 if (row.VideoStreamingPlaylists?.VideoFiles?.id && !videoFilesDone.has(row.VideoStreamingPlaylists.VideoFiles.id)) {
1604 const streamingPlaylist = videoStreamingPlaylistMemo[row.VideoStreamingPlaylists.id]
1606 const videoFileModel = new VideoFileModel(pick(row.VideoStreamingPlaylists.VideoFiles, videoFileKeys))
1607 streamingPlaylist.VideoFiles.push(videoFileModel)
1609 videoFilesDone.add(row.VideoStreamingPlaylists.VideoFiles.id)
1616 static getCategoryLabel (id: number) {
1617 return VIDEO_CATEGORIES[id] || 'Misc'
1620 static getLicenceLabel (id: number) {
1621 return VIDEO_LICENCES[id] || 'Unknown'
1624 static getLanguageLabel (id: string) {
1625 return VIDEO_LANGUAGES[id] || 'Unknown'
1628 static getPrivacyLabel (id: number) {
1629 return VIDEO_PRIVACIES[id] || 'Unknown'
1632 static getStateLabel (id: number) {
1633 return VIDEO_STATES[id] || 'Unknown'
1637 return !!this.VideoBlacklist
1641 return this.VideoChannel.Account.Actor.Server?.isBlocked() || this.VideoChannel.Account.isBlocked()
1644 getQualityFileBy<T extends MVideoWithFile> (this: T, fun: (files: MVideoFile[], it: (file: MVideoFile) => number) => MVideoFile) {
1645 if (Array.isArray(this.VideoFiles) && this.VideoFiles.length !== 0) {
1646 const file = fun(this.VideoFiles, file => file.resolution)
1648 return Object.assign(file, { Video: this })
1651 // No webtorrent files, try with streaming playlist files
1652 if (Array.isArray(this.VideoStreamingPlaylists) && this.VideoStreamingPlaylists.length !== 0) {
1653 const streamingPlaylistWithVideo = Object.assign(this.VideoStreamingPlaylists[0], { Video: this })
1655 const file = fun(streamingPlaylistWithVideo.VideoFiles, file => file.resolution)
1656 return Object.assign(file, { VideoStreamingPlaylist: streamingPlaylistWithVideo })
1662 getMaxQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1663 return this.getQualityFileBy(maxBy)
1666 getMinQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1667 return this.getQualityFileBy(minBy)
1670 getWebTorrentFile<T extends MVideoWithFile> (this: T, resolution: number): MVideoFileVideo {
1671 if (Array.isArray(this.VideoFiles) === false) return undefined
1673 const file = this.VideoFiles.find(f => f.resolution === resolution)
1674 if (!file) return undefined
1676 return Object.assign(file, { Video: this })
1679 async addAndSaveThumbnail (thumbnail: MThumbnail, transaction: Transaction) {
1680 thumbnail.videoId = this.id
1682 const savedThumbnail = await thumbnail.save({ transaction })
1684 if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = []
1686 // Already have this thumbnail, skip
1687 if (this.Thumbnails.find(t => t.id === savedThumbnail.id)) return
1689 this.Thumbnails.push(savedThumbnail)
1692 generateThumbnailName () {
1693 return this.uuid + '.jpg'
1697 if (Array.isArray(this.Thumbnails) === false) return undefined
1699 return this.Thumbnails.find(t => t.type === ThumbnailType.MINIATURE)
1702 generatePreviewName () {
1703 return this.uuid + '.jpg'
1707 return !!this.getPreview()
1711 if (Array.isArray(this.Thumbnails) === false) return undefined
1713 return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW)
1717 return this.remote === false
1720 getWatchStaticPath () {
1721 return '/videos/watch/' + this.uuid
1724 getEmbedStaticPath () {
1725 return '/videos/embed/' + this.uuid
1728 getMiniatureStaticPath () {
1729 const thumbnail = this.getMiniature()
1730 if (!thumbnail) return null
1732 return join(STATIC_PATHS.THUMBNAILS, thumbnail.filename)
1735 getPreviewStaticPath () {
1736 const preview = this.getPreview()
1737 if (!preview) return null
1739 // We use a local cache, so specify our cache endpoint instead of potential remote URL
1740 return join(LAZY_STATIC_PATHS.PREVIEWS, preview.filename)
1743 toFormattedJSON (this: MVideoFormattable, options?: VideoFormattingJSONOptions): Video {
1744 return videoModelToFormattedJSON(this, options)
1747 toFormattedDetailsJSON (this: MVideoFormattableDetails): VideoDetails {
1748 return videoModelToFormattedDetailsJSON(this)
1751 getFormattedVideoFilesJSON (): VideoFile[] {
1752 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1753 let files: MVideoFileRedundanciesOpt[] = []
1755 if (Array.isArray(this.VideoFiles)) {
1756 files = files.concat(this.VideoFiles)
1759 for (const p of (this.VideoStreamingPlaylists || [])) {
1760 files = files.concat(p.VideoFiles || [])
1763 return videoFilesModelToFormattedJSON(this, baseUrlHttp, baseUrlWs, files)
1766 toActivityPubObject (this: MVideoAP): VideoObject {
1767 return videoModelToActivityPubObject(this)
1770 getTruncatedDescription () {
1771 if (!this.description) return null
1773 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1774 return peertubeTruncate(this.description, { length: maxLength })
1777 getMaxQualityResolution () {
1778 const file = this.getMaxQualityFile()
1779 const videoOrPlaylist = file.getVideoOrStreamingPlaylist()
1780 const originalFilePath = getVideoFilePath(videoOrPlaylist, file)
1782 return getVideoFileResolution(originalFilePath)
1785 getDescriptionAPIPath () {
1786 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1789 getHLSPlaylist (): MStreamingPlaylistFilesVideo {
1790 if (!this.VideoStreamingPlaylists) return undefined
1792 const playlist = this.VideoStreamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
1793 playlist.Video = this
1798 setHLSPlaylist (playlist: MStreamingPlaylist) {
1799 const toAdd = [ playlist ] as [ VideoStreamingPlaylistModel ]
1801 if (Array.isArray(this.VideoStreamingPlaylists) === false || this.VideoStreamingPlaylists.length === 0) {
1802 this.VideoStreamingPlaylists = toAdd
1806 this.VideoStreamingPlaylists = this.VideoStreamingPlaylists
1807 .filter(s => s.type !== VideoStreamingPlaylistType.HLS)
1811 removeFile (videoFile: MVideoFile, isRedundancy = false) {
1812 const filePath = getVideoFilePath(this, videoFile, isRedundancy)
1813 return remove(filePath)
1814 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1817 removeTorrent (videoFile: MVideoFile) {
1818 const torrentPath = getTorrentFilePath(this, videoFile)
1819 return remove(torrentPath)
1820 .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err }))
1823 async removeStreamingPlaylistFiles (streamingPlaylist: MStreamingPlaylist, isRedundancy = false) {
1824 const directoryPath = getHLSDirectory(this, isRedundancy)
1826 await remove(directoryPath)
1828 if (isRedundancy !== true) {
1829 const streamingPlaylistWithFiles = streamingPlaylist as MStreamingPlaylistFilesVideo
1830 streamingPlaylistWithFiles.Video = this
1832 if (!Array.isArray(streamingPlaylistWithFiles.VideoFiles)) {
1833 streamingPlaylistWithFiles.VideoFiles = await streamingPlaylistWithFiles.$get('VideoFiles')
1836 // Remove physical files and torrents
1838 streamingPlaylistWithFiles.VideoFiles.map(file => streamingPlaylistWithFiles.removeTorrent(file))
1844 if (this.isOwned()) return false
1846 return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)
1849 hasPrivacyForFederation () {
1850 return isPrivacyForFederation(this.privacy)
1853 isNewVideo (newPrivacy: VideoPrivacy) {
1854 return this.hasPrivacyForFederation() === false && isPrivacyForFederation(newPrivacy) === true
1858 this.changed('updatedAt', true)
1864 return this.privacy === VideoPrivacy.PRIVATE || this.privacy === VideoPrivacy.INTERNAL || !!this.VideoBlacklist
1867 setPrivacy (newPrivacy: VideoPrivacy) {
1868 if (this.privacy === VideoPrivacy.PRIVATE && newPrivacy !== VideoPrivacy.PRIVATE) {
1869 this.publishedAt = new Date()
1872 this.privacy = newPrivacy
1876 return this.privacy === VideoPrivacy.PRIVATE ||
1877 this.privacy === VideoPrivacy.UNLISTED ||
1878 this.privacy === VideoPrivacy.INTERNAL
1881 async publishIfNeededAndSave (t: Transaction) {
1882 if (this.state !== VideoState.PUBLISHED) {
1883 this.state = VideoState.PUBLISHED
1884 this.publishedAt = new Date()
1885 await this.save({ transaction: t })
1894 if (this.isOwned()) {
1896 baseUrlHttp: WEBSERVER.URL,
1897 baseUrlWs: WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT
1902 baseUrlHttp: REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host,
1903 baseUrlWs: REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1907 getTrackerUrls (baseUrlHttp: string, baseUrlWs: string) {
1908 return [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1911 getTorrentUrl (videoFile: MVideoFile, baseUrlHttp: string) {
1912 return baseUrlHttp + STATIC_PATHS.TORRENTS + getTorrentFileName(this, videoFile)
1915 getTorrentDownloadUrl (videoFile: MVideoFile, baseUrlHttp: string) {
1916 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + getTorrentFileName(this, videoFile)
1919 getVideoFileUrl (videoFile: MVideoFile, baseUrlHttp: string) {
1920 return baseUrlHttp + STATIC_PATHS.WEBSEED + getVideoFilename(this, videoFile)
1923 getVideoFileMetadataUrl (videoFile: MVideoFile, baseUrlHttp: string) {
1924 const path = '/api/v1/videos/'
1926 return this.isOwned()
1927 ? baseUrlHttp + path + this.uuid + '/metadata/' + videoFile.id
1928 : videoFile.metadataUrl
1931 getVideoRedundancyUrl (videoFile: MVideoFile, baseUrlHttp: string) {
1932 return baseUrlHttp + STATIC_PATHS.REDUNDANCY + getVideoFilename(this, videoFile)
1935 getVideoFileDownloadUrl (videoFile: MVideoFile, baseUrlHttp: string) {
1936 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + getVideoFilename(this, videoFile)
1939 getBandwidthBits (videoFile: MVideoFile) {
1940 return Math.ceil((videoFile.size * 8) / this.duration)