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 { VideoTorrentObject } 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, MVideoFileStreamingPlaylistVideo, MVideoFileRedundanciesOpt } 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'
130 import { stream } from 'winston'
132 export enum ScopeNames {
133 AVAILABLE_FOR_LIST_IDS = 'AVAILABLE_FOR_LIST_IDS',
135 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
136 WITH_TAGS = 'WITH_TAGS',
137 WITH_WEBTORRENT_FILES = 'WITH_WEBTORRENT_FILES',
138 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
139 WITH_BLACKLISTED = 'WITH_BLACKLISTED',
140 WITH_USER_HISTORY = 'WITH_USER_HISTORY',
141 WITH_STREAMING_PLAYLISTS = 'WITH_STREAMING_PLAYLISTS',
142 WITH_USER_ID = 'WITH_USER_ID',
143 WITH_IMMUTABLE_ATTRIBUTES = 'WITH_IMMUTABLE_ATTRIBUTES',
144 WITH_THUMBNAILS = 'WITH_THUMBNAILS'
147 export type ForAPIOptions = {
150 videoPlaylistId?: number
154 withAccountBlockerIds?: number[]
157 export type AvailableForListIDsOptions = {
158 serverAccountId: number
159 followerActorId: number
160 includeLocalVideos: boolean
162 attributesType?: 'none' | 'id' | 'all'
165 categoryOneOf?: number[]
167 licenceOneOf?: number[]
168 languageOneOf?: string[]
175 videoChannelId?: number
177 videoPlaylistId?: number
179 trendingDays?: number
180 user?: MUserAccountId
181 historyOfUser?: MUserId
183 baseWhere?: WhereOptions[]
187 [ScopeNames.WITH_IMMUTABLE_ATTRIBUTES]: {
188 attributes: [ 'id', 'url', 'uuid', 'remote' ]
190 [ScopeNames.FOR_API]: (options: ForAPIOptions) => {
191 const query: FindOptions = {
194 model: VideoChannelModel.scope({
196 VideoChannelScopeNames.SUMMARY, {
198 withAccountBlockerIds: options.withAccountBlockerIds
205 attributes: [ 'type', 'filename' ],
206 model: ThumbnailModel,
220 if (options.withFiles === true) {
222 model: VideoFileModel,
227 if (options.videoPlaylistId) {
229 model: VideoPlaylistElementModel.unscoped(),
232 videoPlaylistId: options.videoPlaylistId
239 [ScopeNames.WITH_THUMBNAILS]: {
242 model: ThumbnailModel,
247 [ScopeNames.WITH_USER_ID]: {
250 attributes: [ 'accountId' ],
251 model: VideoChannelModel.unscoped(),
255 attributes: [ 'userId' ],
256 model: AccountModel.unscoped(),
263 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
266 model: VideoChannelModel.unscoped(),
271 exclude: [ 'privateKey', 'publicKey' ]
273 model: ActorModel.unscoped(),
277 attributes: [ 'host' ],
278 model: ServerModel.unscoped(),
282 model: AvatarModel.unscoped(),
288 model: AccountModel.unscoped(),
292 model: ActorModel.unscoped(),
294 exclude: [ 'privateKey', 'publicKey' ]
299 attributes: [ 'host' ],
300 model: ServerModel.unscoped(),
304 model: AvatarModel.unscoped(),
315 [ScopeNames.WITH_TAGS]: {
316 include: [ TagModel ]
318 [ScopeNames.WITH_BLACKLISTED]: {
321 attributes: [ 'id', 'reason', 'unfederated' ],
322 model: VideoBlacklistModel,
327 [ScopeNames.WITH_WEBTORRENT_FILES]: (withRedundancies = false) => {
328 let subInclude: any[] = []
330 if (withRedundancies === true) {
333 attributes: [ 'fileUrl' ],
334 model: VideoRedundancyModel.unscoped(),
343 model: VideoFileModel,
344 separate: true, // We may have multiple files, having multiple redundancies so let's separate this join
351 [ScopeNames.WITH_STREAMING_PLAYLISTS]: (withRedundancies = false) => {
352 const subInclude: IncludeOptions[] = [
354 model: VideoFileModel,
359 if (withRedundancies === true) {
361 attributes: [ 'fileUrl' ],
362 model: VideoRedundancyModel.unscoped(),
370 model: VideoStreamingPlaylistModel.unscoped(),
371 separate: true, // We may have multiple streaming playlists, having multiple redundancies so let's separate this join
378 [ScopeNames.WITH_SCHEDULED_UPDATE]: {
381 model: ScheduleVideoUpdateModel.unscoped(),
386 [ScopeNames.WITH_USER_HISTORY]: (userId: number) => {
390 attributes: [ 'currentTime' ],
391 model: UserVideoHistoryModel.unscoped(),
404 buildTrigramSearchIndex('video_name_trigram', 'name'),
406 { fields: [ 'createdAt' ] },
409 { name: 'publishedAt', order: 'DESC' },
410 { name: 'id', order: 'ASC' }
413 { fields: [ 'duration' ] },
414 { fields: [ 'views' ] },
415 { fields: [ 'channelId' ] },
417 fields: [ 'originallyPublishedAt' ],
419 originallyPublishedAt: {
425 fields: [ 'category' ], // We don't care videos with an unknown category
433 fields: [ 'licence' ], // We don't care videos with an unknown licence
441 fields: [ 'language' ], // We don't care videos with an unknown language
449 fields: [ 'nsfw' ], // Most of the videos are not NSFW
455 fields: [ 'remote' ], // Only index local videos
470 export class VideoModel extends Model<VideoModel> {
473 @Default(DataType.UUIDV4)
475 @Column(DataType.UUID)
479 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
485 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category', true))
491 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence', true))
497 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language', true))
498 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
502 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
504 privacy: VideoPrivacy
507 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
513 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description', true))
514 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
519 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support', true))
520 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
524 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
554 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
555 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
560 commentsEnabled: boolean
564 downloadEnabled: boolean
568 waitTranscoding: boolean
572 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
583 @Default(DataType.NOW)
590 originallyPublishedAt: Date
592 @ForeignKey(() => VideoChannelModel)
596 @BelongsTo(() => VideoChannelModel, {
602 VideoChannel: VideoChannelModel
604 @BelongsToMany(() => TagModel, {
605 foreignKey: 'videoId',
606 through: () => VideoTagModel,
611 @HasMany(() => ThumbnailModel, {
619 Thumbnails: ThumbnailModel[]
621 @HasMany(() => VideoPlaylistElementModel, {
628 VideoPlaylistElements: VideoPlaylistElementModel[]
630 @HasMany(() => VideoAbuseModel, {
637 VideoAbuses: VideoAbuseModel[]
639 @HasMany(() => VideoFileModel, {
647 VideoFiles: VideoFileModel[]
649 @HasMany(() => VideoStreamingPlaylistModel, {
657 VideoStreamingPlaylists: VideoStreamingPlaylistModel[]
659 @HasMany(() => VideoShareModel, {
666 VideoShares: VideoShareModel[]
668 @HasMany(() => AccountVideoRateModel, {
675 AccountVideoRates: AccountVideoRateModel[]
677 @HasMany(() => VideoCommentModel, {
685 VideoComments: VideoCommentModel[]
687 @HasMany(() => VideoViewModel, {
694 VideoViews: VideoViewModel[]
696 @HasMany(() => UserVideoHistoryModel, {
703 UserVideoHistories: UserVideoHistoryModel[]
705 @HasOne(() => ScheduleVideoUpdateModel, {
712 ScheduleVideoUpdate: ScheduleVideoUpdateModel
714 @HasOne(() => VideoBlacklistModel, {
721 VideoBlacklist: VideoBlacklistModel
723 @HasOne(() => VideoImportModel, {
730 VideoImport: VideoImportModel
732 @HasMany(() => VideoCaptionModel, {
739 ['separate' as any]: true
741 VideoCaptions: VideoCaptionModel[]
744 static async sendDelete (instance: MVideoAccountLight, options) {
745 if (instance.isOwned()) {
746 if (!instance.VideoChannel) {
747 instance.VideoChannel = await instance.$get('VideoChannel', {
752 transaction: options.transaction
753 }) as MChannelAccountDefault
756 return sendDeleteVideo(instance, options.transaction)
763 static async removeFiles (instance: VideoModel) {
764 const tasks: Promise<any>[] = []
766 logger.info('Removing files of video %s.', instance.url)
768 if (instance.isOwned()) {
769 if (!Array.isArray(instance.VideoFiles)) {
770 instance.VideoFiles = await instance.$get('VideoFiles')
773 // Remove physical files and torrents
774 instance.VideoFiles.forEach(file => {
775 tasks.push(instance.removeFile(file))
776 tasks.push(instance.removeTorrent(file))
779 // Remove playlists file
780 if (!Array.isArray(instance.VideoStreamingPlaylists)) {
781 instance.VideoStreamingPlaylists = await instance.$get('VideoStreamingPlaylists')
784 for (const p of instance.VideoStreamingPlaylists) {
785 tasks.push(instance.removeStreamingPlaylistFiles(p))
789 // Do not wait video deletion because we could be in a transaction
792 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
799 static invalidateCache (instance: VideoModel) {
800 ModelCache.Instance.invalidateCache('video', instance.id)
804 static async saveEssentialDataToAbuses (instance: VideoModel, options) {
805 const tasks: Promise<any>[] = []
807 if (!Array.isArray(instance.VideoAbuses)) {
808 instance.VideoAbuses = await instance.$get('VideoAbuses')
810 if (instance.VideoAbuses.length === 0) return undefined
813 logger.info('Saving video abuses details of video %s.', instance.url)
815 const details = instance.toFormattedDetailsJSON()
817 for (const abuse of instance.VideoAbuses) {
818 abuse.deletedVideo = details
819 tasks.push(abuse.save({ transaction: options.transaction }))
824 logger.error('Some errors when saving details of video %s in its abuses before destroy hook.', instance.uuid, { err })
830 static listLocal (): Bluebird<MVideoWithAllFiles[]> {
837 return VideoModel.scope([
838 ScopeNames.WITH_WEBTORRENT_FILES,
839 ScopeNames.WITH_STREAMING_PLAYLISTS,
840 ScopeNames.WITH_THUMBNAILS
844 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
845 function getRawQuery (select: string) {
846 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
847 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
848 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
849 'WHERE "Account"."actorId" = ' + actorId
850 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
851 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
852 'WHERE "VideoShare"."actorId" = ' + actorId
854 return `(${queryVideo}) UNION (${queryVideoShare})`
857 const rawQuery = getRawQuery('"Video"."id"')
858 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
864 order: getVideoSort('-createdAt', [ 'Tags', 'name', 'ASC' ] as any), // FIXME: sequelize typings
867 [Op.in]: Sequelize.literal('(' + rawQuery + ')')
869 [Op.or]: getPrivaciesForFederation()
873 attributes: [ 'language', 'fileUrl' ],
874 model: VideoCaptionModel.unscoped(),
878 attributes: [ 'id', 'url' ],
879 model: VideoShareModel.unscoped(),
881 // We only want videos shared by this actor
896 attributes: [ 'id', 'url' ],
897 model: ActorModel.unscoped()
902 model: VideoChannelModel.unscoped(),
906 attributes: [ 'name' ],
907 model: AccountModel.unscoped(),
911 attributes: [ 'id', 'url', 'followersUrl' ],
912 model: ActorModel.unscoped(),
918 attributes: [ 'id', 'url', 'followersUrl' ],
919 model: ActorModel.unscoped(),
929 return Bluebird.all([
930 VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findAll(query),
931 VideoModel.sequelize.query<{ total: string }>(rawCountQuery, { type: QueryTypes.SELECT })
932 ]).then(([ rows, totals ]) => {
933 // totals: totalVideos + totalVideoShares
935 let totalVideoShares = 0
936 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
937 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
939 const total = totalVideos + totalVideoShares
947 static listUserVideosForApi (
954 function buildBaseQuery (): FindOptions {
958 order: getVideoSort(sort),
961 model: VideoChannelModel,
977 baseQuery = Object.assign(baseQuery, {
980 [Op.iLike]: '%' + search + '%'
989 const countQuery = buildBaseQuery()
990 const findQuery = buildBaseQuery()
992 const findScopes: (string | ScopeOptions)[] = [
993 ScopeNames.WITH_SCHEDULED_UPDATE,
994 ScopeNames.WITH_BLACKLISTED,
995 ScopeNames.WITH_THUMBNAILS
999 VideoModel.count(countQuery),
1000 VideoModel.scope(findScopes).findAll<MVideoForUser>(findQuery)
1001 ]).then(([ count, rows ]) => {
1009 static async listForApi (options: {
1014 includeLocalVideos: boolean
1016 categoryOneOf?: number[]
1017 licenceOneOf?: number[]
1018 languageOneOf?: string[]
1019 tagsOneOf?: string[]
1020 tagsAllOf?: string[]
1021 filter?: VideoFilter
1023 videoChannelId?: number
1024 followerActorId?: number
1025 videoPlaylistId?: number
1026 trendingDays?: number
1027 user?: MUserAccountId
1028 historyOfUser?: MUserId
1029 countVideos?: boolean
1031 if (options.filter && options.filter === 'all-local' && !options.user.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1032 throw new Error('Try to filter all-local but no user has not the see all videos right')
1035 const trendingDays = options.sort.endsWith('trending')
1036 ? CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1039 const serverActor = await getServerActor()
1041 // followerActorId === null has a meaning, so just check undefined
1042 const followerActorId = options.followerActorId !== undefined
1043 ? options.followerActorId
1046 const queryOptions = {
1047 start: options.start,
1048 count: options.count,
1051 serverAccountId: serverActor.Account.id,
1053 categoryOneOf: options.categoryOneOf,
1054 licenceOneOf: options.licenceOneOf,
1055 languageOneOf: options.languageOneOf,
1056 tagsOneOf: options.tagsOneOf,
1057 tagsAllOf: options.tagsAllOf,
1058 filter: options.filter,
1059 withFiles: options.withFiles,
1060 accountId: options.accountId,
1061 videoChannelId: options.videoChannelId,
1062 videoPlaylistId: options.videoPlaylistId,
1063 includeLocalVideos: options.includeLocalVideos,
1065 historyOfUser: options.historyOfUser,
1069 return VideoModel.getAvailableForApi(queryOptions, options.countVideos)
1072 static async searchAndPopulateAccountAndServer (options: {
1073 includeLocalVideos: boolean
1078 startDate?: string // ISO 8601
1079 endDate?: string // ISO 8601
1080 originallyPublishedStartDate?: string
1081 originallyPublishedEndDate?: string
1083 categoryOneOf?: number[]
1084 licenceOneOf?: number[]
1085 languageOneOf?: string[]
1086 tagsOneOf?: string[]
1087 tagsAllOf?: string[]
1088 durationMin?: number // seconds
1089 durationMax?: number // seconds
1090 user?: MUserAccountId
1091 filter?: VideoFilter
1093 const serverActor = await getServerActor()
1094 const queryOptions = {
1095 followerActorId: serverActor.id,
1096 serverAccountId: serverActor.Account.id,
1097 includeLocalVideos: options.includeLocalVideos,
1099 categoryOneOf: options.categoryOneOf,
1100 licenceOneOf: options.licenceOneOf,
1101 languageOneOf: options.languageOneOf,
1102 tagsOneOf: options.tagsOneOf,
1103 tagsAllOf: options.tagsAllOf,
1105 filter: options.filter,
1106 start: options.start,
1107 count: options.count,
1109 startDate: options.startDate,
1110 endDate: options.endDate,
1111 originallyPublishedStartDate: options.originallyPublishedStartDate,
1112 originallyPublishedEndDate: options.originallyPublishedEndDate,
1114 durationMin: options.durationMin,
1115 durationMax: options.durationMax,
1117 search: options.search
1120 return VideoModel.getAvailableForApi(queryOptions)
1123 static load (id: number | string, t?: Transaction): Bluebird<MVideoThumbnail> {
1124 const where = buildWhereIdOrUUID(id)
1130 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1133 static loadWithBlacklist (id: number | string, t?: Transaction): Bluebird<MVideoThumbnailBlacklist> {
1134 const where = buildWhereIdOrUUID(id)
1140 return VideoModel.scope([
1141 ScopeNames.WITH_THUMBNAILS,
1142 ScopeNames.WITH_BLACKLISTED
1146 static loadImmutableAttributes (id: number | string, t?: Transaction): Bluebird<MVideoImmutable> {
1149 where: buildWhereIdOrUUID(id),
1153 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1156 return ModelCache.Instance.doCache({
1157 cacheType: 'load-video-immutable-id',
1164 static loadWithRights (id: number | string, t?: Transaction): Bluebird<MVideoWithRights> {
1165 const where = buildWhereIdOrUUID(id)
1171 return VideoModel.scope([
1172 ScopeNames.WITH_BLACKLISTED,
1173 ScopeNames.WITH_USER_ID,
1174 ScopeNames.WITH_THUMBNAILS
1178 static loadOnlyId (id: number | string, t?: Transaction): Bluebird<MVideoIdThumbnail> {
1179 const where = buildWhereIdOrUUID(id)
1182 attributes: [ 'id' ],
1187 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1190 static loadWithFiles (id: number | string, t?: Transaction, logging?: boolean): Bluebird<MVideoWithAllFiles> {
1191 const where = buildWhereIdOrUUID(id)
1199 return VideoModel.scope([
1200 ScopeNames.WITH_WEBTORRENT_FILES,
1201 ScopeNames.WITH_STREAMING_PLAYLISTS,
1202 ScopeNames.WITH_THUMBNAILS
1206 static loadByUUID (uuid: string): Bluebird<MVideoThumbnail> {
1213 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1216 static loadByUrl (url: string, transaction?: Transaction): Bluebird<MVideoThumbnail> {
1217 const query: FindOptions = {
1224 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(query)
1227 static loadByUrlImmutableAttributes (url: string, transaction?: Transaction): Bluebird<MVideoImmutable> {
1229 const query: FindOptions = {
1236 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1239 return ModelCache.Instance.doCache({
1240 cacheType: 'load-video-immutable-url',
1247 static loadByUrlAndPopulateAccount (url: string, transaction?: Transaction): Bluebird<MVideoAccountLightBlacklistAllFiles> {
1248 const query: FindOptions = {
1255 return VideoModel.scope([
1256 ScopeNames.WITH_ACCOUNT_DETAILS,
1257 ScopeNames.WITH_WEBTORRENT_FILES,
1258 ScopeNames.WITH_STREAMING_PLAYLISTS,
1259 ScopeNames.WITH_THUMBNAILS,
1260 ScopeNames.WITH_BLACKLISTED
1264 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Transaction, userId?: number): Bluebird<MVideoFullLight> {
1265 const where = buildWhereIdOrUUID(id)
1268 order: [ [ 'Tags', 'name', 'ASC' ] ] as any,
1273 const scopes: (string | ScopeOptions)[] = [
1274 ScopeNames.WITH_TAGS,
1275 ScopeNames.WITH_BLACKLISTED,
1276 ScopeNames.WITH_ACCOUNT_DETAILS,
1277 ScopeNames.WITH_SCHEDULED_UPDATE,
1278 ScopeNames.WITH_WEBTORRENT_FILES,
1279 ScopeNames.WITH_STREAMING_PLAYLISTS,
1280 ScopeNames.WITH_THUMBNAILS
1284 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1292 static loadForGetAPI (parameters: {
1296 }): Bluebird<MVideoDetails> {
1297 const { id, t, userId } = parameters
1298 const where = buildWhereIdOrUUID(id)
1301 order: [ [ 'Tags', 'name', 'ASC' ] ] as any, // FIXME: sequelize typings
1306 const scopes: (string | ScopeOptions)[] = [
1307 ScopeNames.WITH_TAGS,
1308 ScopeNames.WITH_BLACKLISTED,
1309 ScopeNames.WITH_ACCOUNT_DETAILS,
1310 ScopeNames.WITH_SCHEDULED_UPDATE,
1311 ScopeNames.WITH_THUMBNAILS,
1312 { method: [ ScopeNames.WITH_WEBTORRENT_FILES, true ] },
1313 { method: [ ScopeNames.WITH_STREAMING_PLAYLISTS, true ] }
1317 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1325 static async getStats () {
1326 const totalLocalVideos = await VideoModel.count({
1332 let totalLocalVideoViews = await VideoModel.sum('views', {
1338 // Sequelize could return null...
1339 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1341 const { total: totalVideos } = await VideoModel.listForApi({
1344 sort: '-publishedAt',
1345 nsfw: buildNSFWFilter(),
1346 includeLocalVideos: true,
1352 totalLocalVideoViews,
1357 static incrementViews (id: number, views: number) {
1358 return VideoModel.increment('views', {
1366 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1367 // Instances only share videos
1368 const query = 'SELECT 1 FROM "videoShare" ' +
1369 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1370 'WHERE "actorFollow"."actorId" = $followerActorId AND "actorFollow"."state" = \'accepted\' AND "videoShare"."videoId" = $videoId ' +
1374 type: QueryTypes.SELECT as QueryTypes.SELECT,
1375 bind: { followerActorId, videoId },
1379 return VideoModel.sequelize.query(query, options)
1380 .then(results => results.length === 1)
1383 static bulkUpdateSupportField (videoChannel: MChannel, t: Transaction) {
1386 channelId: videoChannel.id
1391 return VideoModel.update({ support: videoChannel.support }, options)
1394 static getAllIdsFromChannel (videoChannel: MChannelId): Bluebird<number[]> {
1396 attributes: [ 'id' ],
1398 channelId: videoChannel.id
1402 return VideoModel.findAll(query)
1403 .then(videos => videos.map(v => v.id))
1406 // threshold corresponds to how many video the field should have to be returned
1407 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1408 const serverActor = await getServerActor()
1409 const followerActorId = serverActor.id
1411 const queryOptions: BuildVideosQueryOptions = {
1412 attributes: [ `"${field}"` ],
1413 group: `GROUP BY "${field}"`,
1414 having: `HAVING COUNT("${field}") >= ${threshold}`,
1418 serverAccountId: serverActor.Account.id,
1420 includeLocalVideos: true
1423 const { query, replacements } = buildListQuery(VideoModel, queryOptions)
1425 return this.sequelize.query<any>(query, { replacements, type: QueryTypes.SELECT })
1426 .then(rows => rows.map(r => r[field]))
1429 static buildTrendingQuery (trendingDays: number) {
1433 model: VideoViewModel,
1437 [Op.gte]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1443 private static async getAvailableForApi (
1444 options: BuildVideosQueryOptions,
1446 ): Promise<ResultList<VideoModel>> {
1447 function getCount () {
1448 if (countVideos !== true) return Promise.resolve(undefined)
1450 const countOptions = Object.assign({}, options, { isCount: true })
1451 const { query: queryCount, replacements: replacementsCount } = buildListQuery(VideoModel, countOptions)
1453 return VideoModel.sequelize.query<any>(queryCount, { replacements: replacementsCount, type: QueryTypes.SELECT })
1454 .then(rows => rows.length !== 0 ? rows[0].total : 0)
1457 function getModels () {
1458 if (options.count === 0) return Promise.resolve([])
1460 const { query, replacements, order } = buildListQuery(VideoModel, options)
1461 const queryModels = wrapForAPIResults(query, replacements, options, order)
1463 return VideoModel.sequelize.query<any>(queryModels, { replacements, type: QueryTypes.SELECT, nest: true })
1464 .then(rows => VideoModel.buildAPIResult(rows))
1467 const [ count, rows ] = await Promise.all([ getCount(), getModels() ])
1475 private static buildAPIResult (rows: any[]) {
1476 const videosMemo: { [ id: number ]: VideoModel } = {}
1477 const videoStreamingPlaylistMemo: { [ id: number ]: VideoStreamingPlaylistModel } = {}
1479 const thumbnailsDone = new Set<number>()
1480 const historyDone = new Set<number>()
1481 const videoFilesDone = new Set<number>()
1482 const videoStreamingPlaylistsDone = new Set<number>()
1484 const videos: VideoModel[] = []
1486 const avatarKeys = [ 'id', 'filename', 'fileUrl', 'onDisk', 'createdAt', 'updatedAt' ]
1487 const actorKeys = [ 'id', 'preferredUsername', 'url', 'serverId', 'avatarId' ]
1488 const serverKeys = [ 'id', 'host' ]
1489 const videoFileKeys = [ 'id', 'createdAt', 'updatedAt', 'resolution', 'size', 'extname', 'infoHash', 'fps', 'videoId' ]
1490 const videoStreamingPlaylistKeys = [ 'id' ]
1513 'originallyPublishedAt',
1519 function buildActor (rowActor: any) {
1520 const avatarModel = rowActor.Avatar.id !== null
1521 ? new AvatarModel(pick(rowActor.Avatar, avatarKeys))
1524 const serverModel = rowActor.Server.id !== null
1525 ? new ServerModel(pick(rowActor.Server, serverKeys))
1528 const actorModel = new ActorModel(pick(rowActor, actorKeys))
1529 actorModel.Avatar = avatarModel
1530 actorModel.Server = serverModel
1535 for (const row of rows) {
1536 if (!videosMemo[row.id]) {
1538 const channel = row.VideoChannel
1539 const channelModel = new VideoChannelModel(pick(channel, [ 'id', 'name', 'description', 'actorId' ]))
1540 channelModel.Actor = buildActor(channel.Actor)
1542 const account = row.VideoChannel.Account
1543 const accountModel = new AccountModel(pick(account, [ 'id', 'name' ]))
1544 accountModel.Actor = buildActor(account.Actor)
1546 channelModel.Account = accountModel
1548 const videoModel = new VideoModel(pick(row, videoKeys))
1549 videoModel.VideoChannel = channelModel
1551 videoModel.UserVideoHistories = []
1552 videoModel.Thumbnails = []
1553 videoModel.VideoFiles = []
1554 videoModel.VideoStreamingPlaylists = []
1556 videosMemo[row.id] = videoModel
1557 // Don't take object value to have a sorted array
1558 videos.push(videoModel)
1561 const videoModel = videosMemo[row.id]
1563 if (row.userVideoHistory?.id && !historyDone.has(row.userVideoHistory.id)) {
1564 const historyModel = new UserVideoHistoryModel(pick(row.userVideoHistory, [ 'id', 'currentTime' ]))
1565 videoModel.UserVideoHistories.push(historyModel)
1567 historyDone.add(row.userVideoHistory.id)
1570 if (row.Thumbnails?.id && !thumbnailsDone.has(row.Thumbnails.id)) {
1571 const thumbnailModel = new ThumbnailModel(pick(row.Thumbnails, [ 'id', 'type', 'filename' ]))
1572 videoModel.Thumbnails.push(thumbnailModel)
1574 thumbnailsDone.add(row.Thumbnails.id)
1577 if (row.VideoFiles?.id && !videoFilesDone.has(row.VideoFiles.id)) {
1578 const videoFileModel = new VideoFileModel(pick(row.VideoFiles, videoFileKeys))
1579 videoModel.VideoFiles.push(videoFileModel)
1581 videoFilesDone.add(row.VideoFiles.id)
1584 if (row.VideoFiles?.id && !videoFilesDone.has(row.VideoFiles.id)) {
1585 const videoFileModel = new VideoFileModel(pick(row.VideoFiles, videoFileKeys))
1586 videoModel.VideoFiles.push(videoFileModel)
1588 videoFilesDone.add(row.VideoFiles.id)
1591 if (row.VideoStreamingPlaylists?.id && !videoStreamingPlaylistMemo[row.VideoStreamingPlaylists.id]) {
1592 const streamingPlaylist = new VideoStreamingPlaylistModel(pick(row.VideoStreamingPlaylists, videoStreamingPlaylistKeys))
1593 streamingPlaylist.VideoFiles = []
1595 videoModel.VideoStreamingPlaylists.push(streamingPlaylist)
1597 videoStreamingPlaylistMemo[streamingPlaylist.id] = streamingPlaylist
1600 if (row.VideoStreamingPlaylists?.VideoFiles?.id && !videoFilesDone.has(row.VideoStreamingPlaylists.VideoFiles.id)) {
1601 const streamingPlaylist = videoStreamingPlaylistMemo[row.VideoStreamingPlaylists.id]
1603 const videoFileModel = new VideoFileModel(pick(row.VideoStreamingPlaylists.VideoFiles, videoFileKeys))
1604 streamingPlaylist.VideoFiles.push(videoFileModel)
1606 videoFilesDone.add(row.VideoStreamingPlaylists.VideoFiles.id)
1613 static getCategoryLabel (id: number) {
1614 return VIDEO_CATEGORIES[id] || 'Misc'
1617 static getLicenceLabel (id: number) {
1618 return VIDEO_LICENCES[id] || 'Unknown'
1621 static getLanguageLabel (id: string) {
1622 return VIDEO_LANGUAGES[id] || 'Unknown'
1625 static getPrivacyLabel (id: number) {
1626 return VIDEO_PRIVACIES[id] || 'Unknown'
1629 static getStateLabel (id: number) {
1630 return VIDEO_STATES[id] || 'Unknown'
1634 return !!this.VideoBlacklist
1638 return this.VideoChannel.Account.Actor.Server?.isBlocked() || this.VideoChannel.Account.isBlocked()
1641 getQualityFileBy<T extends MVideoWithFile> (this: T, fun: (files: MVideoFile[], it: (file: MVideoFile) => number) => MVideoFile) {
1642 if (Array.isArray(this.VideoFiles) && this.VideoFiles.length !== 0) {
1643 const file = fun(this.VideoFiles, file => file.resolution)
1645 return Object.assign(file, { Video: this })
1648 // No webtorrent files, try with streaming playlist files
1649 if (Array.isArray(this.VideoStreamingPlaylists) && this.VideoStreamingPlaylists.length !== 0) {
1650 const streamingPlaylistWithVideo = Object.assign(this.VideoStreamingPlaylists[0], { Video: this })
1652 const file = fun(streamingPlaylistWithVideo.VideoFiles, file => file.resolution)
1653 return Object.assign(file, { VideoStreamingPlaylist: streamingPlaylistWithVideo })
1659 getMaxQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1660 return this.getQualityFileBy(maxBy)
1663 getMinQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1664 return this.getQualityFileBy(minBy)
1667 getWebTorrentFile<T extends MVideoWithFile> (this: T, resolution: number): MVideoFileVideo {
1668 if (Array.isArray(this.VideoFiles) === false) return undefined
1670 const file = this.VideoFiles.find(f => f.resolution === resolution)
1671 if (!file) return undefined
1673 return Object.assign(file, { Video: this })
1676 async addAndSaveThumbnail (thumbnail: MThumbnail, transaction: Transaction) {
1677 thumbnail.videoId = this.id
1679 const savedThumbnail = await thumbnail.save({ transaction })
1681 if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = []
1683 // Already have this thumbnail, skip
1684 if (this.Thumbnails.find(t => t.id === savedThumbnail.id)) return
1686 this.Thumbnails.push(savedThumbnail)
1689 generateThumbnailName () {
1690 return this.uuid + '.jpg'
1694 if (Array.isArray(this.Thumbnails) === false) return undefined
1696 return this.Thumbnails.find(t => t.type === ThumbnailType.MINIATURE)
1699 generatePreviewName () {
1700 return this.uuid + '.jpg'
1704 return !!this.getPreview()
1708 if (Array.isArray(this.Thumbnails) === false) return undefined
1710 return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW)
1714 return this.remote === false
1717 getWatchStaticPath () {
1718 return '/videos/watch/' + this.uuid
1721 getEmbedStaticPath () {
1722 return '/videos/embed/' + this.uuid
1725 getMiniatureStaticPath () {
1726 const thumbnail = this.getMiniature()
1727 if (!thumbnail) return null
1729 return join(STATIC_PATHS.THUMBNAILS, thumbnail.filename)
1732 getPreviewStaticPath () {
1733 const preview = this.getPreview()
1734 if (!preview) return null
1736 // We use a local cache, so specify our cache endpoint instead of potential remote URL
1737 return join(LAZY_STATIC_PATHS.PREVIEWS, preview.filename)
1740 toFormattedJSON (this: MVideoFormattable, options?: VideoFormattingJSONOptions): Video {
1741 return videoModelToFormattedJSON(this, options)
1744 toFormattedDetailsJSON (this: MVideoFormattableDetails): VideoDetails {
1745 return videoModelToFormattedDetailsJSON(this)
1748 getFormattedVideoFilesJSON (): VideoFile[] {
1749 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1750 let files: MVideoFileRedundanciesOpt[] = []
1752 if (Array.isArray(this.VideoFiles)) {
1753 files = files.concat(this.VideoFiles)
1756 for (const p of (this.VideoStreamingPlaylists || [])) {
1757 files = files.concat(p.VideoFiles || [])
1760 return videoFilesModelToFormattedJSON(this, baseUrlHttp, baseUrlWs, files)
1763 toActivityPubObject (this: MVideoAP): VideoTorrentObject {
1764 return videoModelToActivityPubObject(this)
1767 getTruncatedDescription () {
1768 if (!this.description) return null
1770 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1771 return peertubeTruncate(this.description, { length: maxLength })
1774 getMaxQualityResolution () {
1775 const file = this.getMaxQualityFile()
1776 const videoOrPlaylist = file.getVideoOrStreamingPlaylist()
1777 const originalFilePath = getVideoFilePath(videoOrPlaylist, file)
1779 return getVideoFileResolution(originalFilePath)
1782 getDescriptionAPIPath () {
1783 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1786 getHLSPlaylist (): MStreamingPlaylistFilesVideo {
1787 if (!this.VideoStreamingPlaylists) return undefined
1789 const playlist = this.VideoStreamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
1790 playlist.Video = this
1795 setHLSPlaylist (playlist: MStreamingPlaylist) {
1796 const toAdd = [ playlist ] as [ VideoStreamingPlaylistModel ]
1798 if (Array.isArray(this.VideoStreamingPlaylists) === false || this.VideoStreamingPlaylists.length === 0) {
1799 this.VideoStreamingPlaylists = toAdd
1803 this.VideoStreamingPlaylists = this.VideoStreamingPlaylists
1804 .filter(s => s.type !== VideoStreamingPlaylistType.HLS)
1808 removeFile (videoFile: MVideoFile, isRedundancy = false) {
1809 const filePath = getVideoFilePath(this, videoFile, isRedundancy)
1810 return remove(filePath)
1811 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1814 removeTorrent (videoFile: MVideoFile) {
1815 const torrentPath = getTorrentFilePath(this, videoFile)
1816 return remove(torrentPath)
1817 .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err }))
1820 async removeStreamingPlaylistFiles (streamingPlaylist: MStreamingPlaylist, isRedundancy = false) {
1821 const directoryPath = getHLSDirectory(this, isRedundancy)
1823 await remove(directoryPath)
1825 if (isRedundancy !== true) {
1826 const streamingPlaylistWithFiles = streamingPlaylist as MStreamingPlaylistFilesVideo
1827 streamingPlaylistWithFiles.Video = this
1829 if (!Array.isArray(streamingPlaylistWithFiles.VideoFiles)) {
1830 streamingPlaylistWithFiles.VideoFiles = await streamingPlaylistWithFiles.$get('VideoFiles')
1833 // Remove physical files and torrents
1835 streamingPlaylistWithFiles.VideoFiles.map(file => streamingPlaylistWithFiles.removeTorrent(file))
1841 if (this.isOwned()) return false
1843 return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)
1846 hasPrivacyForFederation () {
1847 return isPrivacyForFederation(this.privacy)
1850 isNewVideo (newPrivacy: VideoPrivacy) {
1851 return this.hasPrivacyForFederation() === false && isPrivacyForFederation(newPrivacy) === true
1855 this.changed('updatedAt', true)
1861 return this.privacy === VideoPrivacy.PRIVATE || this.privacy === VideoPrivacy.INTERNAL || !!this.VideoBlacklist
1864 setPrivacy (newPrivacy: VideoPrivacy) {
1865 if (this.privacy === VideoPrivacy.PRIVATE && newPrivacy !== VideoPrivacy.PRIVATE) {
1866 this.publishedAt = new Date()
1869 this.privacy = newPrivacy
1873 return this.privacy === VideoPrivacy.PRIVATE ||
1874 this.privacy === VideoPrivacy.UNLISTED ||
1875 this.privacy === VideoPrivacy.INTERNAL
1878 async publishIfNeededAndSave (t: Transaction) {
1879 if (this.state !== VideoState.PUBLISHED) {
1880 this.state = VideoState.PUBLISHED
1881 this.publishedAt = new Date()
1882 await this.save({ transaction: t })
1891 if (this.isOwned()) {
1893 baseUrlHttp: WEBSERVER.URL,
1894 baseUrlWs: WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT
1899 baseUrlHttp: REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host,
1900 baseUrlWs: REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1904 getTrackerUrls (baseUrlHttp: string, baseUrlWs: string) {
1905 return [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1908 getTorrentUrl (videoFile: MVideoFile, baseUrlHttp: string) {
1909 return baseUrlHttp + STATIC_PATHS.TORRENTS + getTorrentFileName(this, videoFile)
1912 getTorrentDownloadUrl (videoFile: MVideoFile, baseUrlHttp: string) {
1913 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + getTorrentFileName(this, videoFile)
1916 getVideoFileUrl (videoFile: MVideoFile, baseUrlHttp: string) {
1917 return baseUrlHttp + STATIC_PATHS.WEBSEED + getVideoFilename(this, videoFile)
1920 getVideoFileMetadataUrl (videoFile: MVideoFile, baseUrlHttp: string) {
1921 const path = '/api/v1/videos/'
1923 return this.isOwned()
1924 ? baseUrlHttp + path + this.uuid + '/metadata/' + videoFile.id
1925 : videoFile.metadataUrl
1928 getVideoRedundancyUrl (videoFile: MVideoFile, baseUrlHttp: string) {
1929 return baseUrlHttp + STATIC_PATHS.REDUNDANCY + getVideoFilename(this, videoFile)
1932 getVideoFileDownloadUrl (videoFile: MVideoFile, baseUrlHttp: string) {
1933 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + getVideoFilename(this, videoFile)
1936 getBandwidthBits (videoFile: MVideoFile) {
1937 return Math.ceil((videoFile.size * 8) / this.duration)