1 import * as Bluebird from 'bluebird'
2 import { maxBy, minBy, pick } from 'lodash'
3 import { join } from 'path'
4 import { FindOptions, IncludeOptions, Op, QueryTypes, ScopeOptions, Sequelize, Transaction, WhereOptions } from 'sequelize'
25 } from 'sequelize-typescript'
26 import { UserRight, VideoPrivacy, VideoState } from '../../../shared'
27 import { VideoTorrentObject } from '../../../shared/models/activitypub/objects'
28 import { Video, VideoDetails } from '../../../shared/models/videos'
29 import { VideoFilter } from '../../../shared/models/videos/video-query.type'
30 import { peertubeTruncate } from '../../helpers/core-utils'
31 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
32 import { isBooleanValid } from '../../helpers/custom-validators/misc'
35 isVideoDescriptionValid,
43 } from '../../helpers/custom-validators/videos'
44 import { getVideoFileResolution } from '../../helpers/ffmpeg-utils'
45 import { logger } from '../../helpers/logger'
46 import { getServerActor } from '../../helpers/utils'
53 STATIC_DOWNLOAD_PATHS,
61 } from '../../initializers/constants'
62 import { sendDeleteVideo } from '../../lib/activitypub/send'
63 import { AccountModel } from '../account/account'
64 import { AccountVideoRateModel } from '../account/account-video-rate'
65 import { ActorModel } from '../activitypub/actor'
66 import { AvatarModel } from '../avatar/avatar'
67 import { ServerModel } from '../server/server'
68 import { buildTrigramSearchIndex, buildWhereIdOrUUID, getVideoSort, isOutdated, throwIfNotValid } from '../utils'
69 import { TagModel } from './tag'
70 import { VideoAbuseModel } from './video-abuse'
71 import { ScopeNames as VideoChannelScopeNames, SummaryOptions, VideoChannelModel } from './video-channel'
72 import { VideoCommentModel } from './video-comment'
73 import { VideoFileModel } from './video-file'
74 import { VideoShareModel } from './video-share'
75 import { VideoTagModel } from './video-tag'
76 import { ScheduleVideoUpdateModel } from './schedule-video-update'
77 import { VideoCaptionModel } from './video-caption'
78 import { VideoBlacklistModel } from './video-blacklist'
79 import { remove } from 'fs-extra'
80 import { VideoViewModel } from './video-views'
81 import { VideoRedundancyModel } from '../redundancy/video-redundancy'
83 videoFilesModelToFormattedJSON,
84 VideoFormattingJSONOptions,
85 videoModelToActivityPubObject,
86 videoModelToFormattedDetailsJSON,
87 videoModelToFormattedJSON
88 } from './video-format-utils'
89 import { UserVideoHistoryModel } from '../account/user-video-history'
90 import { VideoImportModel } from './video-import'
91 import { VideoStreamingPlaylistModel } from './video-streaming-playlist'
92 import { VideoPlaylistElementModel } from './video-playlist-element'
93 import { CONFIG } from '../../initializers/config'
94 import { ThumbnailModel } from './thumbnail'
95 import { ThumbnailType } from '../../../shared/models/videos/thumbnail.type'
96 import { VideoStreamingPlaylistType } from '../../../shared/models/videos/video-streaming-playlist.type'
99 MChannelAccountDefault,
102 MStreamingPlaylistFilesVideo,
106 MVideoAccountLightBlacklistAllFiles,
111 MVideoFormattableDetails,
117 MVideoThumbnailBlacklist,
121 } from '../../typings/models'
122 import { MVideoFile, MVideoFileStreamingPlaylistVideo } from '../../typings/models/video/video-file'
123 import { MThumbnail } from '../../typings/models/video/thumbnail'
124 import { VideoFile } from '@shared/models/videos/video-file.model'
125 import { getHLSDirectory, getTorrentFileName, getTorrentFilePath, getVideoFilename, getVideoFilePath } from '@server/lib/video-paths'
126 import { ModelCache } from '@server/models/model-cache'
127 import { buildListQuery, BuildVideosQueryOptions, wrapForAPIResults } from './video-query-builder'
129 export enum ScopeNames {
130 AVAILABLE_FOR_LIST_IDS = 'AVAILABLE_FOR_LIST_IDS',
132 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
133 WITH_TAGS = 'WITH_TAGS',
134 WITH_WEBTORRENT_FILES = 'WITH_WEBTORRENT_FILES',
135 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
136 WITH_BLACKLISTED = 'WITH_BLACKLISTED',
137 WITH_USER_HISTORY = 'WITH_USER_HISTORY',
138 WITH_STREAMING_PLAYLISTS = 'WITH_STREAMING_PLAYLISTS',
139 WITH_USER_ID = 'WITH_USER_ID',
140 WITH_IMMUTABLE_ATTRIBUTES = 'WITH_IMMUTABLE_ATTRIBUTES',
141 WITH_THUMBNAILS = 'WITH_THUMBNAILS'
144 export type ForAPIOptions = {
147 videoPlaylistId?: number
151 withAccountBlockerIds?: number[]
154 export type AvailableForListIDsOptions = {
155 serverAccountId: number
156 followerActorId: number
157 includeLocalVideos: boolean
159 attributesType?: 'none' | 'id' | 'all'
162 categoryOneOf?: number[]
164 licenceOneOf?: number[]
165 languageOneOf?: string[]
172 videoChannelId?: number
174 videoPlaylistId?: number
176 trendingDays?: number
177 user?: MUserAccountId
178 historyOfUser?: MUserId
180 baseWhere?: WhereOptions[]
184 [ScopeNames.WITH_IMMUTABLE_ATTRIBUTES]: {
185 attributes: [ 'id', 'url', 'uuid', 'remote' ]
187 [ScopeNames.FOR_API]: (options: ForAPIOptions) => {
188 const query: FindOptions = {
191 model: VideoChannelModel.scope({
193 VideoChannelScopeNames.SUMMARY, {
195 withAccountBlockerIds: options.withAccountBlockerIds
202 attributes: [ 'type', 'filename' ],
203 model: ThumbnailModel,
217 if (options.withFiles === true) {
219 model: VideoFileModel.unscoped(),
224 if (options.videoPlaylistId) {
226 model: VideoPlaylistElementModel.unscoped(),
229 videoPlaylistId: options.videoPlaylistId
236 [ScopeNames.WITH_THUMBNAILS]: {
239 model: ThumbnailModel,
244 [ScopeNames.WITH_USER_ID]: {
247 attributes: [ 'accountId' ],
248 model: VideoChannelModel.unscoped(),
252 attributes: [ 'userId' ],
253 model: AccountModel.unscoped(),
260 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
263 model: VideoChannelModel.unscoped(),
268 exclude: [ 'privateKey', 'publicKey' ]
270 model: ActorModel.unscoped(),
274 attributes: [ 'host' ],
275 model: ServerModel.unscoped(),
279 model: AvatarModel.unscoped(),
285 model: AccountModel.unscoped(),
289 model: ActorModel.unscoped(),
291 exclude: [ 'privateKey', 'publicKey' ]
296 attributes: [ 'host' ],
297 model: ServerModel.unscoped(),
301 model: AvatarModel.unscoped(),
312 [ScopeNames.WITH_TAGS]: {
313 include: [ TagModel ]
315 [ScopeNames.WITH_BLACKLISTED]: {
318 attributes: [ 'id', 'reason', 'unfederated' ],
319 model: VideoBlacklistModel,
324 [ScopeNames.WITH_WEBTORRENT_FILES]: (withRedundancies = false) => {
325 let subInclude: any[] = []
327 if (withRedundancies === true) {
330 attributes: [ 'fileUrl' ],
331 model: VideoRedundancyModel.unscoped(),
340 model: VideoFileModel.unscoped(),
341 separate: true, // We may have multiple files, having multiple redundancies so let's separate this join
348 [ScopeNames.WITH_STREAMING_PLAYLISTS]: (withRedundancies = false) => {
349 const subInclude: IncludeOptions[] = [
351 model: VideoFileModel.unscoped(),
356 if (withRedundancies === true) {
358 attributes: [ 'fileUrl' ],
359 model: VideoRedundancyModel.unscoped(),
367 model: VideoStreamingPlaylistModel.unscoped(),
368 separate: true, // We may have multiple streaming playlists, having multiple redundancies so let's separate this join
375 [ScopeNames.WITH_SCHEDULED_UPDATE]: {
378 model: ScheduleVideoUpdateModel.unscoped(),
383 [ScopeNames.WITH_USER_HISTORY]: (userId: number) => {
387 attributes: [ 'currentTime' ],
388 model: UserVideoHistoryModel.unscoped(),
401 buildTrigramSearchIndex('video_name_trigram', 'name'),
403 { fields: [ 'createdAt' ] },
406 { name: 'publishedAt', order: 'DESC' },
407 { name: 'id', order: 'ASC' }
410 { fields: [ 'duration' ] },
411 { fields: [ 'views' ] },
412 { fields: [ 'channelId' ] },
414 fields: [ 'originallyPublishedAt' ],
416 originallyPublishedAt: {
422 fields: [ 'category' ], // We don't care videos with an unknown category
430 fields: [ 'licence' ], // We don't care videos with an unknown licence
438 fields: [ 'language' ], // We don't care videos with an unknown language
446 fields: [ 'nsfw' ], // Most of the videos are not NSFW
452 fields: [ 'remote' ], // Only index local videos
467 export class VideoModel extends Model<VideoModel> {
470 @Default(DataType.UUIDV4)
472 @Column(DataType.UUID)
476 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
482 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category', true))
488 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence', true))
494 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language', true))
495 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
499 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
504 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
510 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description', true))
511 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
516 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support', true))
517 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
521 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
551 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
552 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
557 commentsEnabled: boolean
561 downloadEnabled: boolean
565 waitTranscoding: boolean
569 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
580 @Default(DataType.NOW)
587 originallyPublishedAt: Date
589 @ForeignKey(() => VideoChannelModel)
593 @BelongsTo(() => VideoChannelModel, {
599 VideoChannel: VideoChannelModel
601 @BelongsToMany(() => TagModel, {
602 foreignKey: 'videoId',
603 through: () => VideoTagModel,
608 @HasMany(() => ThumbnailModel, {
616 Thumbnails: ThumbnailModel[]
618 @HasMany(() => VideoPlaylistElementModel, {
625 VideoPlaylistElements: VideoPlaylistElementModel[]
627 @HasMany(() => VideoAbuseModel, {
634 VideoAbuses: VideoAbuseModel[]
636 @HasMany(() => VideoFileModel, {
644 VideoFiles: VideoFileModel[]
646 @HasMany(() => VideoStreamingPlaylistModel, {
654 VideoStreamingPlaylists: VideoStreamingPlaylistModel[]
656 @HasMany(() => VideoShareModel, {
663 VideoShares: VideoShareModel[]
665 @HasMany(() => AccountVideoRateModel, {
672 AccountVideoRates: AccountVideoRateModel[]
674 @HasMany(() => VideoCommentModel, {
682 VideoComments: VideoCommentModel[]
684 @HasMany(() => VideoViewModel, {
691 VideoViews: VideoViewModel[]
693 @HasMany(() => UserVideoHistoryModel, {
700 UserVideoHistories: UserVideoHistoryModel[]
702 @HasOne(() => ScheduleVideoUpdateModel, {
709 ScheduleVideoUpdate: ScheduleVideoUpdateModel
711 @HasOne(() => VideoBlacklistModel, {
718 VideoBlacklist: VideoBlacklistModel
720 @HasOne(() => VideoImportModel, {
727 VideoImport: VideoImportModel
729 @HasMany(() => VideoCaptionModel, {
736 ['separate' as any]: true
738 VideoCaptions: VideoCaptionModel[]
741 static async sendDelete (instance: MVideoAccountLight, options) {
742 if (instance.isOwned()) {
743 if (!instance.VideoChannel) {
744 instance.VideoChannel = await instance.$get('VideoChannel', {
749 transaction: options.transaction
750 }) as MChannelAccountDefault
753 return sendDeleteVideo(instance, options.transaction)
760 static async removeFiles (instance: VideoModel) {
761 const tasks: Promise<any>[] = []
763 logger.info('Removing files of video %s.', instance.url)
765 if (instance.isOwned()) {
766 if (!Array.isArray(instance.VideoFiles)) {
767 instance.VideoFiles = await instance.$get('VideoFiles')
770 // Remove physical files and torrents
771 instance.VideoFiles.forEach(file => {
772 tasks.push(instance.removeFile(file))
773 tasks.push(instance.removeTorrent(file))
776 // Remove playlists file
777 if (!Array.isArray(instance.VideoStreamingPlaylists)) {
778 instance.VideoStreamingPlaylists = await instance.$get('VideoStreamingPlaylists')
781 for (const p of instance.VideoStreamingPlaylists) {
782 tasks.push(instance.removeStreamingPlaylistFiles(p))
786 // Do not wait video deletion because we could be in a transaction
789 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
796 static invalidateCache (instance: VideoModel) {
797 ModelCache.Instance.invalidateCache('video', instance.id)
800 static listLocal (): Bluebird<MVideoWithAllFiles[]> {
807 return VideoModel.scope([
808 ScopeNames.WITH_WEBTORRENT_FILES,
809 ScopeNames.WITH_STREAMING_PLAYLISTS,
810 ScopeNames.WITH_THUMBNAILS
814 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
815 function getRawQuery (select: string) {
816 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
817 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
818 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
819 'WHERE "Account"."actorId" = ' + actorId
820 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
821 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
822 'WHERE "VideoShare"."actorId" = ' + actorId
824 return `(${queryVideo}) UNION (${queryVideoShare})`
827 const rawQuery = getRawQuery('"Video"."id"')
828 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
834 order: getVideoSort('createdAt', [ 'Tags', 'name', 'ASC' ] as any), // FIXME: sequelize typings
837 [Op.in]: Sequelize.literal('(' + rawQuery + ')')
840 { privacy: VideoPrivacy.PUBLIC },
841 { privacy: VideoPrivacy.UNLISTED }
846 attributes: [ 'language', 'fileUrl' ],
847 model: VideoCaptionModel.unscoped(),
851 attributes: [ 'id', 'url' ],
852 model: VideoShareModel.unscoped(),
854 // We only want videos shared by this actor
869 attributes: [ 'id', 'url' ],
870 model: ActorModel.unscoped()
875 model: VideoChannelModel.unscoped(),
879 attributes: [ 'name' ],
880 model: AccountModel.unscoped(),
884 attributes: [ 'id', 'url', 'followersUrl' ],
885 model: ActorModel.unscoped(),
891 attributes: [ 'id', 'url', 'followersUrl' ],
892 model: ActorModel.unscoped(),
902 return Bluebird.all([
903 VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findAll(query),
904 VideoModel.sequelize.query<{ total: string }>(rawCountQuery, { type: QueryTypes.SELECT })
905 ]).then(([ rows, totals ]) => {
906 // totals: totalVideos + totalVideoShares
908 let totalVideoShares = 0
909 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
910 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
912 const total = totalVideos + totalVideoShares
920 static listUserVideosForApi (
927 function buildBaseQuery (): FindOptions {
931 order: getVideoSort(sort),
934 model: VideoChannelModel,
950 baseQuery = Object.assign(baseQuery, {
953 [Op.iLike]: '%' + search + '%'
962 const countQuery = buildBaseQuery()
963 const findQuery = buildBaseQuery()
965 const findScopes: (string | ScopeOptions)[] = [
966 ScopeNames.WITH_SCHEDULED_UPDATE,
967 ScopeNames.WITH_BLACKLISTED,
968 ScopeNames.WITH_THUMBNAILS
972 VideoModel.count(countQuery),
973 VideoModel.scope(findScopes).findAll<MVideoForUser>(findQuery)
974 ]).then(([ count, rows ]) => {
982 static async listForApi (options: {
987 includeLocalVideos: boolean
989 categoryOneOf?: number[]
990 licenceOneOf?: number[]
991 languageOneOf?: string[]
996 videoChannelId?: number
997 followerActorId?: number
998 videoPlaylistId?: number
999 trendingDays?: number
1000 user?: MUserAccountId
1001 historyOfUser?: MUserId
1002 countVideos?: boolean
1004 if (options.filter && options.filter === 'all-local' && !options.user.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1005 throw new Error('Try to filter all-local but no user has not the see all videos right')
1008 const trendingDays = options.sort.endsWith('trending')
1009 ? CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1012 const serverActor = await getServerActor()
1014 // followerActorId === null has a meaning, so just check undefined
1015 const followerActorId = options.followerActorId !== undefined
1016 ? options.followerActorId
1019 const queryOptions = {
1020 start: options.start,
1021 count: options.count,
1024 serverAccountId: serverActor.Account.id,
1026 categoryOneOf: options.categoryOneOf,
1027 licenceOneOf: options.licenceOneOf,
1028 languageOneOf: options.languageOneOf,
1029 tagsOneOf: options.tagsOneOf,
1030 tagsAllOf: options.tagsAllOf,
1031 filter: options.filter,
1032 withFiles: options.withFiles,
1033 accountId: options.accountId,
1034 videoChannelId: options.videoChannelId,
1035 videoPlaylistId: options.videoPlaylistId,
1036 includeLocalVideos: options.includeLocalVideos,
1038 historyOfUser: options.historyOfUser,
1042 return VideoModel.getAvailableForApi(queryOptions, options.countVideos)
1045 static async searchAndPopulateAccountAndServer (options: {
1046 includeLocalVideos: boolean
1051 startDate?: string // ISO 8601
1052 endDate?: string // ISO 8601
1053 originallyPublishedStartDate?: string
1054 originallyPublishedEndDate?: string
1056 categoryOneOf?: number[]
1057 licenceOneOf?: number[]
1058 languageOneOf?: string[]
1059 tagsOneOf?: string[]
1060 tagsAllOf?: string[]
1061 durationMin?: number // seconds
1062 durationMax?: number // seconds
1063 user?: MUserAccountId
1064 filter?: VideoFilter
1066 const serverActor = await getServerActor()
1067 const queryOptions = {
1068 followerActorId: serverActor.id,
1069 serverAccountId: serverActor.Account.id,
1070 includeLocalVideos: options.includeLocalVideos,
1072 categoryOneOf: options.categoryOneOf,
1073 licenceOneOf: options.licenceOneOf,
1074 languageOneOf: options.languageOneOf,
1075 tagsOneOf: options.tagsOneOf,
1076 tagsAllOf: options.tagsAllOf,
1078 filter: options.filter,
1079 start: options.start,
1080 count: options.count,
1082 startDate: options.startDate,
1083 endDate: options.endDate,
1084 originallyPublishedStartDate: options.originallyPublishedStartDate,
1085 originallyPublishedEndDate: options.originallyPublishedEndDate,
1087 durationMin: options.durationMin,
1088 durationMax: options.durationMax,
1090 search: options.search
1093 return VideoModel.getAvailableForApi(queryOptions)
1096 static load (id: number | string, t?: Transaction): Bluebird<MVideoThumbnail> {
1097 const where = buildWhereIdOrUUID(id)
1103 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1106 static loadWithBlacklist (id: number | string, t?: Transaction): Bluebird<MVideoThumbnailBlacklist> {
1107 const where = buildWhereIdOrUUID(id)
1113 return VideoModel.scope([
1114 ScopeNames.WITH_THUMBNAILS,
1115 ScopeNames.WITH_BLACKLISTED
1119 static loadImmutableAttributes (id: number | string, t?: Transaction): Bluebird<MVideoImmutable> {
1122 where: buildWhereIdOrUUID(id),
1126 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1129 return ModelCache.Instance.doCache({
1130 cacheType: 'load-video-immutable-id',
1137 static loadWithRights (id: number | string, t?: Transaction): Bluebird<MVideoWithRights> {
1138 const where = buildWhereIdOrUUID(id)
1144 return VideoModel.scope([
1145 ScopeNames.WITH_BLACKLISTED,
1146 ScopeNames.WITH_USER_ID,
1147 ScopeNames.WITH_THUMBNAILS
1151 static loadOnlyId (id: number | string, t?: Transaction): Bluebird<MVideoIdThumbnail> {
1152 const where = buildWhereIdOrUUID(id)
1155 attributes: [ 'id' ],
1160 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1163 static loadWithFiles (id: number | string, t?: Transaction, logging?: boolean): Bluebird<MVideoWithAllFiles> {
1164 const where = buildWhereIdOrUUID(id)
1172 return VideoModel.scope([
1173 ScopeNames.WITH_WEBTORRENT_FILES,
1174 ScopeNames.WITH_STREAMING_PLAYLISTS,
1175 ScopeNames.WITH_THUMBNAILS
1179 static loadByUUID (uuid: string): Bluebird<MVideoThumbnail> {
1186 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1189 static loadByUrl (url: string, transaction?: Transaction): Bluebird<MVideoThumbnail> {
1190 const query: FindOptions = {
1197 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(query)
1200 static loadByUrlImmutableAttributes (url: string, transaction?: Transaction): Bluebird<MVideoImmutable> {
1202 const query: FindOptions = {
1209 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1212 return ModelCache.Instance.doCache({
1213 cacheType: 'load-video-immutable-url',
1220 static loadByUrlAndPopulateAccount (url: string, transaction?: Transaction): Bluebird<MVideoAccountLightBlacklistAllFiles> {
1221 const query: FindOptions = {
1228 return VideoModel.scope([
1229 ScopeNames.WITH_ACCOUNT_DETAILS,
1230 ScopeNames.WITH_WEBTORRENT_FILES,
1231 ScopeNames.WITH_STREAMING_PLAYLISTS,
1232 ScopeNames.WITH_THUMBNAILS,
1233 ScopeNames.WITH_BLACKLISTED
1237 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Transaction, userId?: number): Bluebird<MVideoFullLight> {
1238 const where = buildWhereIdOrUUID(id)
1241 order: [ [ 'Tags', 'name', 'ASC' ] ] as any,
1246 const scopes: (string | ScopeOptions)[] = [
1247 ScopeNames.WITH_TAGS,
1248 ScopeNames.WITH_BLACKLISTED,
1249 ScopeNames.WITH_ACCOUNT_DETAILS,
1250 ScopeNames.WITH_SCHEDULED_UPDATE,
1251 ScopeNames.WITH_WEBTORRENT_FILES,
1252 ScopeNames.WITH_STREAMING_PLAYLISTS,
1253 ScopeNames.WITH_THUMBNAILS
1257 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1265 static loadForGetAPI (parameters: {
1269 }): Bluebird<MVideoDetails> {
1270 const { id, t, userId } = parameters
1271 const where = buildWhereIdOrUUID(id)
1274 order: [ [ 'Tags', 'name', 'ASC' ] ] as any, // FIXME: sequelize typings
1279 const scopes: (string | ScopeOptions)[] = [
1280 ScopeNames.WITH_TAGS,
1281 ScopeNames.WITH_BLACKLISTED,
1282 ScopeNames.WITH_ACCOUNT_DETAILS,
1283 ScopeNames.WITH_SCHEDULED_UPDATE,
1284 ScopeNames.WITH_THUMBNAILS,
1285 { method: [ ScopeNames.WITH_WEBTORRENT_FILES, true ] },
1286 { method: [ ScopeNames.WITH_STREAMING_PLAYLISTS, true ] }
1290 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1298 static async getStats () {
1299 const totalLocalVideos = await VideoModel.count({
1304 const totalVideos = await VideoModel.count()
1306 let totalLocalVideoViews = await VideoModel.sum('views', {
1311 // Sequelize could return null...
1312 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1316 totalLocalVideoViews,
1321 static incrementViews (id: number, views: number) {
1322 return VideoModel.increment('views', {
1330 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1331 // Instances only share videos
1332 const query = 'SELECT 1 FROM "videoShare" ' +
1333 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1334 'WHERE "actorFollow"."actorId" = $followerActorId AND "videoShare"."videoId" = $videoId ' +
1338 type: QueryTypes.SELECT as QueryTypes.SELECT,
1339 bind: { followerActorId, videoId },
1343 return VideoModel.sequelize.query(query, options)
1344 .then(results => results.length === 1)
1347 static bulkUpdateSupportField (videoChannel: MChannel, t: Transaction) {
1350 channelId: videoChannel.id
1355 return VideoModel.update({ support: videoChannel.support }, options)
1358 static getAllIdsFromChannel (videoChannel: MChannelId): Bluebird<number[]> {
1360 attributes: [ 'id' ],
1362 channelId: videoChannel.id
1366 return VideoModel.findAll(query)
1367 .then(videos => videos.map(v => v.id))
1370 // threshold corresponds to how many video the field should have to be returned
1371 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1372 const serverActor = await getServerActor()
1373 const followerActorId = serverActor.id
1375 const queryOptions: BuildVideosQueryOptions = {
1376 attributes: [ `"${field}"` ],
1377 group: `GROUP BY "${field}"`,
1378 having: `HAVING COUNT("${field}") >= ${threshold}`,
1382 serverAccountId: serverActor.Account.id,
1384 includeLocalVideos: true
1387 const { query, replacements } = buildListQuery(VideoModel, queryOptions)
1389 return this.sequelize.query<any>(query, { replacements, type: QueryTypes.SELECT })
1390 .then(rows => rows.map(r => r[field]))
1393 static buildTrendingQuery (trendingDays: number) {
1397 model: VideoViewModel,
1401 [Op.gte]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1407 private static async getAvailableForApi (
1408 options: BuildVideosQueryOptions,
1411 function getCount () {
1412 if (countVideos !== true) return Promise.resolve(undefined)
1414 const countOptions = Object.assign({}, options, { isCount: true })
1415 const { query: queryCount, replacements: replacementsCount } = buildListQuery(VideoModel, countOptions)
1417 return VideoModel.sequelize.query<any>(queryCount, { replacements: replacementsCount, type: QueryTypes.SELECT })
1418 .then(rows => rows.length !== 0 ? rows[0].total : 0)
1421 function getModels () {
1422 const { query, replacements, order } = buildListQuery(VideoModel, options)
1423 const queryModels = wrapForAPIResults(query, replacements, options, order)
1425 return VideoModel.sequelize.query<any>(queryModels, { replacements, type: QueryTypes.SELECT, nest: true })
1426 .then(rows => VideoModel.buildAPIResult(rows))
1429 const [ count, rows ] = await Promise.all([ getCount(), getModels() ])
1437 private static buildAPIResult (rows: any[]) {
1438 const memo: { [ id: number ]: VideoModel } = {}
1440 const thumbnailsDone = new Set<number>()
1441 const historyDone = new Set<number>()
1442 const videoFilesDone = new Set<number>()
1444 const videos: VideoModel[] = []
1446 const avatarKeys = [ 'id', 'filename', 'fileUrl', 'onDisk', 'createdAt', 'updatedAt' ]
1447 const actorKeys = [ 'id', 'preferredUsername', 'url', 'serverId', 'avatarId' ]
1448 const serverKeys = [ 'id', 'host' ]
1449 const videoFileKeys = [ 'id', 'createdAt', 'updatedAt', 'resolution', 'size', 'extname', 'infoHash', 'fps', 'videoId' ]
1472 'originallyPublishedAt',
1478 function buildActor (rowActor: any) {
1479 const avatarModel = rowActor.Avatar.id !== null
1480 ? new AvatarModel(pick(rowActor.Avatar, avatarKeys))
1483 const serverModel = rowActor.Server.id !== null
1484 ? new ServerModel(pick(rowActor.Server, serverKeys))
1487 const actorModel = new ActorModel(pick(rowActor, actorKeys))
1488 actorModel.Avatar = avatarModel
1489 actorModel.Server = serverModel
1494 for (const row of rows) {
1495 if (!memo[row.id]) {
1497 const channel = row.VideoChannel
1498 const channelModel = new VideoChannelModel(pick(channel, [ 'id', 'name', 'description', 'actorId' ]))
1499 channelModel.Actor = buildActor(channel.Actor)
1501 const account = row.VideoChannel.Account
1502 const accountModel = new AccountModel(pick(account, [ 'id', 'name' ]))
1503 accountModel.Actor = buildActor(account.Actor)
1505 channelModel.Account = accountModel
1507 const videoModel = new VideoModel(pick(row, videoKeys))
1508 videoModel.VideoChannel = channelModel
1510 videoModel.UserVideoHistories = []
1511 videoModel.Thumbnails = []
1512 videoModel.VideoFiles = []
1514 memo[row.id] = videoModel
1515 // Don't take object value to have a sorted array
1516 videos.push(videoModel)
1519 const videoModel = memo[row.id]
1521 if (row.userVideoHistory?.id && !historyDone.has(row.userVideoHistory.id)) {
1522 const historyModel = new UserVideoHistoryModel(pick(row.userVideoHistory, [ 'id', 'currentTime' ]))
1523 videoModel.UserVideoHistories.push(historyModel)
1525 historyDone.add(row.userVideoHistory.id)
1528 if (row.Thumbnails?.id && !thumbnailsDone.has(row.Thumbnails.id)) {
1529 const thumbnailModel = new ThumbnailModel(pick(row.Thumbnails, [ 'id', 'type', 'filename' ]))
1530 videoModel.Thumbnails.push(thumbnailModel)
1532 thumbnailsDone.add(row.Thumbnails.id)
1535 if (row.VideoFiles?.id && !videoFilesDone.has(row.VideoFiles.id)) {
1536 const videoFileModel = new VideoFileModel(pick(row.VideoFiles, videoFileKeys))
1537 videoModel.VideoFiles.push(videoFileModel)
1539 videoFilesDone.add(row.VideoFiles.id)
1546 private static isPrivacyForFederation (privacy: VideoPrivacy) {
1547 const castedPrivacy = parseInt(privacy + '', 10)
1549 return castedPrivacy === VideoPrivacy.PUBLIC || castedPrivacy === VideoPrivacy.UNLISTED
1552 static getCategoryLabel (id: number) {
1553 return VIDEO_CATEGORIES[id] || 'Misc'
1556 static getLicenceLabel (id: number) {
1557 return VIDEO_LICENCES[id] || 'Unknown'
1560 static getLanguageLabel (id: string) {
1561 return VIDEO_LANGUAGES[id] || 'Unknown'
1564 static getPrivacyLabel (id: number) {
1565 return VIDEO_PRIVACIES[id] || 'Unknown'
1568 static getStateLabel (id: number) {
1569 return VIDEO_STATES[id] || 'Unknown'
1573 return !!this.VideoBlacklist
1577 return (this.VideoChannel.Account.Actor.Server && this.VideoChannel.Account.Actor.Server.isBlocked()) ||
1578 this.VideoChannel.Account.isBlocked()
1581 getQualityFileBy<T extends MVideoWithFile> (this: T, fun: (files: MVideoFile[], it: (file: MVideoFile) => number) => MVideoFile) {
1582 if (Array.isArray(this.VideoFiles) && this.VideoFiles.length !== 0) {
1583 const file = fun(this.VideoFiles, file => file.resolution)
1585 return Object.assign(file, { Video: this })
1588 // No webtorrent files, try with streaming playlist files
1589 if (Array.isArray(this.VideoStreamingPlaylists) && this.VideoStreamingPlaylists.length !== 0) {
1590 const streamingPlaylistWithVideo = Object.assign(this.VideoStreamingPlaylists[0], { Video: this })
1592 const file = fun(streamingPlaylistWithVideo.VideoFiles, file => file.resolution)
1593 return Object.assign(file, { VideoStreamingPlaylist: streamingPlaylistWithVideo })
1599 getMaxQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1600 return this.getQualityFileBy(maxBy)
1603 getMinQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1604 return this.getQualityFileBy(minBy)
1607 getWebTorrentFile<T extends MVideoWithFile> (this: T, resolution: number): MVideoFileVideo {
1608 if (Array.isArray(this.VideoFiles) === false) return undefined
1610 const file = this.VideoFiles.find(f => f.resolution === resolution)
1611 if (!file) return undefined
1613 return Object.assign(file, { Video: this })
1616 async addAndSaveThumbnail (thumbnail: MThumbnail, transaction: Transaction) {
1617 thumbnail.videoId = this.id
1619 const savedThumbnail = await thumbnail.save({ transaction })
1621 if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = []
1623 // Already have this thumbnail, skip
1624 if (this.Thumbnails.find(t => t.id === savedThumbnail.id)) return
1626 this.Thumbnails.push(savedThumbnail)
1629 generateThumbnailName () {
1630 return this.uuid + '.jpg'
1634 if (Array.isArray(this.Thumbnails) === false) return undefined
1636 return this.Thumbnails.find(t => t.type === ThumbnailType.MINIATURE)
1639 generatePreviewName () {
1640 return this.uuid + '.jpg'
1644 return !!this.getPreview()
1648 if (Array.isArray(this.Thumbnails) === false) return undefined
1650 return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW)
1654 return this.remote === false
1657 getWatchStaticPath () {
1658 return '/videos/watch/' + this.uuid
1661 getEmbedStaticPath () {
1662 return '/videos/embed/' + this.uuid
1665 getMiniatureStaticPath () {
1666 const thumbnail = this.getMiniature()
1667 if (!thumbnail) return null
1669 return join(STATIC_PATHS.THUMBNAILS, thumbnail.filename)
1672 getPreviewStaticPath () {
1673 const preview = this.getPreview()
1674 if (!preview) return null
1676 // We use a local cache, so specify our cache endpoint instead of potential remote URL
1677 return join(LAZY_STATIC_PATHS.PREVIEWS, preview.filename)
1680 toFormattedJSON (this: MVideoFormattable, options?: VideoFormattingJSONOptions): Video {
1681 return videoModelToFormattedJSON(this, options)
1684 toFormattedDetailsJSON (this: MVideoFormattableDetails): VideoDetails {
1685 return videoModelToFormattedDetailsJSON(this)
1688 getFormattedVideoFilesJSON (): VideoFile[] {
1689 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1690 return videoFilesModelToFormattedJSON(this, baseUrlHttp, baseUrlWs, this.VideoFiles)
1693 toActivityPubObject (this: MVideoAP): VideoTorrentObject {
1694 return videoModelToActivityPubObject(this)
1697 getTruncatedDescription () {
1698 if (!this.description) return null
1700 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1701 return peertubeTruncate(this.description, { length: maxLength })
1704 getMaxQualityResolution () {
1705 const file = this.getMaxQualityFile()
1706 const videoOrPlaylist = file.getVideoOrStreamingPlaylist()
1707 const originalFilePath = getVideoFilePath(videoOrPlaylist, file)
1709 return getVideoFileResolution(originalFilePath)
1712 getDescriptionAPIPath () {
1713 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1716 getHLSPlaylist (): MStreamingPlaylistFilesVideo {
1717 if (!this.VideoStreamingPlaylists) return undefined
1719 const playlist = this.VideoStreamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
1720 playlist.Video = this
1725 setHLSPlaylist (playlist: MStreamingPlaylist) {
1726 const toAdd = [ playlist ] as [ VideoStreamingPlaylistModel ]
1728 if (Array.isArray(this.VideoStreamingPlaylists) === false || this.VideoStreamingPlaylists.length === 0) {
1729 this.VideoStreamingPlaylists = toAdd
1733 this.VideoStreamingPlaylists = this.VideoStreamingPlaylists
1734 .filter(s => s.type !== VideoStreamingPlaylistType.HLS)
1738 removeFile (videoFile: MVideoFile, isRedundancy = false) {
1739 const filePath = getVideoFilePath(this, videoFile, isRedundancy)
1740 return remove(filePath)
1741 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1744 removeTorrent (videoFile: MVideoFile) {
1745 const torrentPath = getTorrentFilePath(this, videoFile)
1746 return remove(torrentPath)
1747 .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err }))
1750 async removeStreamingPlaylistFiles (streamingPlaylist: MStreamingPlaylist, isRedundancy = false) {
1751 const directoryPath = getHLSDirectory(this, isRedundancy)
1753 await remove(directoryPath)
1755 if (isRedundancy !== true) {
1756 const streamingPlaylistWithFiles = streamingPlaylist as MStreamingPlaylistFilesVideo
1757 streamingPlaylistWithFiles.Video = this
1759 if (!Array.isArray(streamingPlaylistWithFiles.VideoFiles)) {
1760 streamingPlaylistWithFiles.VideoFiles = await streamingPlaylistWithFiles.$get('VideoFiles')
1763 // Remove physical files and torrents
1765 streamingPlaylistWithFiles.VideoFiles.map(file => streamingPlaylistWithFiles.removeTorrent(file))
1771 if (this.isOwned()) return false
1773 return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)
1776 hasPrivacyForFederation () {
1777 return VideoModel.isPrivacyForFederation(this.privacy)
1780 isNewVideo (newPrivacy: VideoPrivacy) {
1781 return this.hasPrivacyForFederation() === false && VideoModel.isPrivacyForFederation(newPrivacy) === true
1785 this.changed('updatedAt', true)
1791 return this.privacy === VideoPrivacy.PRIVATE || this.privacy === VideoPrivacy.INTERNAL || !!this.VideoBlacklist
1794 setPrivacy (newPrivacy: VideoPrivacy) {
1795 if (this.privacy === VideoPrivacy.PRIVATE && newPrivacy !== VideoPrivacy.PRIVATE) {
1796 this.publishedAt = new Date()
1799 this.privacy = newPrivacy
1803 return this.privacy === VideoPrivacy.PRIVATE ||
1804 this.privacy === VideoPrivacy.UNLISTED ||
1805 this.privacy === VideoPrivacy.INTERNAL
1808 async publishIfNeededAndSave (t: Transaction) {
1809 if (this.state !== VideoState.PUBLISHED) {
1810 this.state = VideoState.PUBLISHED
1811 this.publishedAt = new Date()
1812 await this.save({ transaction: t })
1821 if (this.isOwned()) {
1823 baseUrlHttp: WEBSERVER.URL,
1824 baseUrlWs: WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT
1829 baseUrlHttp: REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host,
1830 baseUrlWs: REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1834 getTrackerUrls (baseUrlHttp: string, baseUrlWs: string) {
1835 return [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1838 getTorrentUrl (videoFile: MVideoFile, baseUrlHttp: string) {
1839 return baseUrlHttp + STATIC_PATHS.TORRENTS + getTorrentFileName(this, videoFile)
1842 getTorrentDownloadUrl (videoFile: MVideoFile, baseUrlHttp: string) {
1843 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + getTorrentFileName(this, videoFile)
1846 getVideoFileUrl (videoFile: MVideoFile, baseUrlHttp: string) {
1847 return baseUrlHttp + STATIC_PATHS.WEBSEED + getVideoFilename(this, videoFile)
1850 getVideoRedundancyUrl (videoFile: MVideoFile, baseUrlHttp: string) {
1851 return baseUrlHttp + STATIC_PATHS.REDUNDANCY + getVideoFilename(this, videoFile)
1854 getVideoFileDownloadUrl (videoFile: MVideoFile, baseUrlHttp: string) {
1855 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + getVideoFilename(this, videoFile)
1858 getBandwidthBits (videoFile: MVideoFile) {
1859 return Math.ceil((videoFile.size * 8) / this.duration)