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'
128 import { buildNSFWFilter } from '@server/helpers/express-utils'
130 export enum ScopeNames {
131 AVAILABLE_FOR_LIST_IDS = 'AVAILABLE_FOR_LIST_IDS',
133 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
134 WITH_TAGS = 'WITH_TAGS',
135 WITH_WEBTORRENT_FILES = 'WITH_WEBTORRENT_FILES',
136 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
137 WITH_BLACKLISTED = 'WITH_BLACKLISTED',
138 WITH_USER_HISTORY = 'WITH_USER_HISTORY',
139 WITH_STREAMING_PLAYLISTS = 'WITH_STREAMING_PLAYLISTS',
140 WITH_USER_ID = 'WITH_USER_ID',
141 WITH_IMMUTABLE_ATTRIBUTES = 'WITH_IMMUTABLE_ATTRIBUTES',
142 WITH_THUMBNAILS = 'WITH_THUMBNAILS'
145 export type ForAPIOptions = {
148 videoPlaylistId?: number
152 withAccountBlockerIds?: number[]
155 export type AvailableForListIDsOptions = {
156 serverAccountId: number
157 followerActorId: number
158 includeLocalVideos: boolean
160 attributesType?: 'none' | 'id' | 'all'
163 categoryOneOf?: number[]
165 licenceOneOf?: number[]
166 languageOneOf?: string[]
173 videoChannelId?: number
175 videoPlaylistId?: number
177 trendingDays?: number
178 user?: MUserAccountId
179 historyOfUser?: MUserId
181 baseWhere?: WhereOptions[]
185 [ScopeNames.WITH_IMMUTABLE_ATTRIBUTES]: {
186 attributes: [ 'id', 'url', 'uuid', 'remote' ]
188 [ScopeNames.FOR_API]: (options: ForAPIOptions) => {
189 const query: FindOptions = {
192 model: VideoChannelModel.scope({
194 VideoChannelScopeNames.SUMMARY, {
196 withAccountBlockerIds: options.withAccountBlockerIds
203 attributes: [ 'type', 'filename' ],
204 model: ThumbnailModel,
218 if (options.withFiles === true) {
220 model: VideoFileModel,
225 if (options.videoPlaylistId) {
227 model: VideoPlaylistElementModel.unscoped(),
230 videoPlaylistId: options.videoPlaylistId
237 [ScopeNames.WITH_THUMBNAILS]: {
240 model: ThumbnailModel,
245 [ScopeNames.WITH_USER_ID]: {
248 attributes: [ 'accountId' ],
249 model: VideoChannelModel.unscoped(),
253 attributes: [ 'userId' ],
254 model: AccountModel.unscoped(),
261 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
264 model: VideoChannelModel.unscoped(),
269 exclude: [ 'privateKey', 'publicKey' ]
271 model: ActorModel.unscoped(),
275 attributes: [ 'host' ],
276 model: ServerModel.unscoped(),
280 model: AvatarModel.unscoped(),
286 model: AccountModel.unscoped(),
290 model: ActorModel.unscoped(),
292 exclude: [ 'privateKey', 'publicKey' ]
297 attributes: [ 'host' ],
298 model: ServerModel.unscoped(),
302 model: AvatarModel.unscoped(),
313 [ScopeNames.WITH_TAGS]: {
314 include: [ TagModel ]
316 [ScopeNames.WITH_BLACKLISTED]: {
319 attributes: [ 'id', 'reason', 'unfederated' ],
320 model: VideoBlacklistModel,
325 [ScopeNames.WITH_WEBTORRENT_FILES]: (withRedundancies = false) => {
326 let subInclude: any[] = []
328 if (withRedundancies === true) {
331 attributes: [ 'fileUrl' ],
332 model: VideoRedundancyModel.unscoped(),
341 model: VideoFileModel,
342 separate: true, // We may have multiple files, having multiple redundancies so let's separate this join
349 [ScopeNames.WITH_STREAMING_PLAYLISTS]: (withRedundancies = false) => {
350 const subInclude: IncludeOptions[] = [
352 model: VideoFileModel,
357 if (withRedundancies === true) {
359 attributes: [ 'fileUrl' ],
360 model: VideoRedundancyModel.unscoped(),
368 model: VideoStreamingPlaylistModel.unscoped(),
369 separate: true, // We may have multiple streaming playlists, having multiple redundancies so let's separate this join
376 [ScopeNames.WITH_SCHEDULED_UPDATE]: {
379 model: ScheduleVideoUpdateModel.unscoped(),
384 [ScopeNames.WITH_USER_HISTORY]: (userId: number) => {
388 attributes: [ 'currentTime' ],
389 model: UserVideoHistoryModel.unscoped(),
402 buildTrigramSearchIndex('video_name_trigram', 'name'),
404 { fields: [ 'createdAt' ] },
407 { name: 'publishedAt', order: 'DESC' },
408 { name: 'id', order: 'ASC' }
411 { fields: [ 'duration' ] },
412 { fields: [ 'views' ] },
413 { fields: [ 'channelId' ] },
415 fields: [ 'originallyPublishedAt' ],
417 originallyPublishedAt: {
423 fields: [ 'category' ], // We don't care videos with an unknown category
431 fields: [ 'licence' ], // We don't care videos with an unknown licence
439 fields: [ 'language' ], // We don't care videos with an unknown language
447 fields: [ 'nsfw' ], // Most of the videos are not NSFW
453 fields: [ 'remote' ], // Only index local videos
468 export class VideoModel extends Model<VideoModel> {
471 @Default(DataType.UUIDV4)
473 @Column(DataType.UUID)
477 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
483 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category', true))
489 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence', true))
495 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language', true))
496 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
500 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
505 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
511 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description', true))
512 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
517 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support', true))
518 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
522 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
552 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
553 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
558 commentsEnabled: boolean
562 downloadEnabled: boolean
566 waitTranscoding: boolean
570 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
581 @Default(DataType.NOW)
588 originallyPublishedAt: Date
590 @ForeignKey(() => VideoChannelModel)
594 @BelongsTo(() => VideoChannelModel, {
600 VideoChannel: VideoChannelModel
602 @BelongsToMany(() => TagModel, {
603 foreignKey: 'videoId',
604 through: () => VideoTagModel,
609 @HasMany(() => ThumbnailModel, {
617 Thumbnails: ThumbnailModel[]
619 @HasMany(() => VideoPlaylistElementModel, {
626 VideoPlaylistElements: VideoPlaylistElementModel[]
628 @HasMany(() => VideoAbuseModel, {
635 VideoAbuses: VideoAbuseModel[]
637 @HasMany(() => VideoFileModel, {
645 VideoFiles: VideoFileModel[]
647 @HasMany(() => VideoStreamingPlaylistModel, {
655 VideoStreamingPlaylists: VideoStreamingPlaylistModel[]
657 @HasMany(() => VideoShareModel, {
664 VideoShares: VideoShareModel[]
666 @HasMany(() => AccountVideoRateModel, {
673 AccountVideoRates: AccountVideoRateModel[]
675 @HasMany(() => VideoCommentModel, {
683 VideoComments: VideoCommentModel[]
685 @HasMany(() => VideoViewModel, {
692 VideoViews: VideoViewModel[]
694 @HasMany(() => UserVideoHistoryModel, {
701 UserVideoHistories: UserVideoHistoryModel[]
703 @HasOne(() => ScheduleVideoUpdateModel, {
710 ScheduleVideoUpdate: ScheduleVideoUpdateModel
712 @HasOne(() => VideoBlacklistModel, {
719 VideoBlacklist: VideoBlacklistModel
721 @HasOne(() => VideoImportModel, {
728 VideoImport: VideoImportModel
730 @HasMany(() => VideoCaptionModel, {
737 ['separate' as any]: true
739 VideoCaptions: VideoCaptionModel[]
742 static async sendDelete (instance: MVideoAccountLight, options) {
743 if (instance.isOwned()) {
744 if (!instance.VideoChannel) {
745 instance.VideoChannel = await instance.$get('VideoChannel', {
750 transaction: options.transaction
751 }) as MChannelAccountDefault
754 return sendDeleteVideo(instance, options.transaction)
761 static async removeFiles (instance: VideoModel) {
762 const tasks: Promise<any>[] = []
764 logger.info('Removing files of video %s.', instance.url)
766 if (instance.isOwned()) {
767 if (!Array.isArray(instance.VideoFiles)) {
768 instance.VideoFiles = await instance.$get('VideoFiles')
771 // Remove physical files and torrents
772 instance.VideoFiles.forEach(file => {
773 tasks.push(instance.removeFile(file))
774 tasks.push(instance.removeTorrent(file))
777 // Remove playlists file
778 if (!Array.isArray(instance.VideoStreamingPlaylists)) {
779 instance.VideoStreamingPlaylists = await instance.$get('VideoStreamingPlaylists')
782 for (const p of instance.VideoStreamingPlaylists) {
783 tasks.push(instance.removeStreamingPlaylistFiles(p))
787 // Do not wait video deletion because we could be in a transaction
790 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
797 static invalidateCache (instance: VideoModel) {
798 ModelCache.Instance.invalidateCache('video', instance.id)
801 static listLocal (): Bluebird<MVideoWithAllFiles[]> {
808 return VideoModel.scope([
809 ScopeNames.WITH_WEBTORRENT_FILES,
810 ScopeNames.WITH_STREAMING_PLAYLISTS,
811 ScopeNames.WITH_THUMBNAILS
815 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
816 function getRawQuery (select: string) {
817 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
818 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
819 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
820 'WHERE "Account"."actorId" = ' + actorId
821 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
822 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
823 'WHERE "VideoShare"."actorId" = ' + actorId
825 return `(${queryVideo}) UNION (${queryVideoShare})`
828 const rawQuery = getRawQuery('"Video"."id"')
829 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
835 order: getVideoSort('createdAt', [ 'Tags', 'name', 'ASC' ] as any), // FIXME: sequelize typings
838 [Op.in]: Sequelize.literal('(' + rawQuery + ')')
841 { privacy: VideoPrivacy.PUBLIC },
842 { privacy: VideoPrivacy.UNLISTED }
847 attributes: [ 'language', 'fileUrl' ],
848 model: VideoCaptionModel.unscoped(),
852 attributes: [ 'id', 'url' ],
853 model: VideoShareModel.unscoped(),
855 // We only want videos shared by this actor
870 attributes: [ 'id', 'url' ],
871 model: ActorModel.unscoped()
876 model: VideoChannelModel.unscoped(),
880 attributes: [ 'name' ],
881 model: AccountModel.unscoped(),
885 attributes: [ 'id', 'url', 'followersUrl' ],
886 model: ActorModel.unscoped(),
892 attributes: [ 'id', 'url', 'followersUrl' ],
893 model: ActorModel.unscoped(),
903 return Bluebird.all([
904 VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findAll(query),
905 VideoModel.sequelize.query<{ total: string }>(rawCountQuery, { type: QueryTypes.SELECT })
906 ]).then(([ rows, totals ]) => {
907 // totals: totalVideos + totalVideoShares
909 let totalVideoShares = 0
910 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
911 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
913 const total = totalVideos + totalVideoShares
921 static listUserVideosForApi (
928 function buildBaseQuery (): FindOptions {
932 order: getVideoSort(sort),
935 model: VideoChannelModel,
951 baseQuery = Object.assign(baseQuery, {
954 [Op.iLike]: '%' + search + '%'
963 const countQuery = buildBaseQuery()
964 const findQuery = buildBaseQuery()
966 const findScopes: (string | ScopeOptions)[] = [
967 ScopeNames.WITH_SCHEDULED_UPDATE,
968 ScopeNames.WITH_BLACKLISTED,
969 ScopeNames.WITH_THUMBNAILS
973 VideoModel.count(countQuery),
974 VideoModel.scope(findScopes).findAll<MVideoForUser>(findQuery)
975 ]).then(([ count, rows ]) => {
983 static async listForApi (options: {
988 includeLocalVideos: boolean
990 categoryOneOf?: number[]
991 licenceOneOf?: number[]
992 languageOneOf?: string[]
997 videoChannelId?: number
998 followerActorId?: number
999 videoPlaylistId?: number
1000 trendingDays?: number
1001 user?: MUserAccountId
1002 historyOfUser?: MUserId
1003 countVideos?: boolean
1005 if (options.filter && options.filter === 'all-local' && !options.user.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1006 throw new Error('Try to filter all-local but no user has not the see all videos right')
1009 const trendingDays = options.sort.endsWith('trending')
1010 ? CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1013 const serverActor = await getServerActor()
1015 // followerActorId === null has a meaning, so just check undefined
1016 const followerActorId = options.followerActorId !== undefined
1017 ? options.followerActorId
1020 const queryOptions = {
1021 start: options.start,
1022 count: options.count,
1025 serverAccountId: serverActor.Account.id,
1027 categoryOneOf: options.categoryOneOf,
1028 licenceOneOf: options.licenceOneOf,
1029 languageOneOf: options.languageOneOf,
1030 tagsOneOf: options.tagsOneOf,
1031 tagsAllOf: options.tagsAllOf,
1032 filter: options.filter,
1033 withFiles: options.withFiles,
1034 accountId: options.accountId,
1035 videoChannelId: options.videoChannelId,
1036 videoPlaylistId: options.videoPlaylistId,
1037 includeLocalVideos: options.includeLocalVideos,
1039 historyOfUser: options.historyOfUser,
1043 return VideoModel.getAvailableForApi(queryOptions, options.countVideos)
1046 static async searchAndPopulateAccountAndServer (options: {
1047 includeLocalVideos: boolean
1052 startDate?: string // ISO 8601
1053 endDate?: string // ISO 8601
1054 originallyPublishedStartDate?: string
1055 originallyPublishedEndDate?: string
1057 categoryOneOf?: number[]
1058 licenceOneOf?: number[]
1059 languageOneOf?: string[]
1060 tagsOneOf?: string[]
1061 tagsAllOf?: string[]
1062 durationMin?: number // seconds
1063 durationMax?: number // seconds
1064 user?: MUserAccountId
1065 filter?: VideoFilter
1067 const serverActor = await getServerActor()
1068 const queryOptions = {
1069 followerActorId: serverActor.id,
1070 serverAccountId: serverActor.Account.id,
1071 includeLocalVideos: options.includeLocalVideos,
1073 categoryOneOf: options.categoryOneOf,
1074 licenceOneOf: options.licenceOneOf,
1075 languageOneOf: options.languageOneOf,
1076 tagsOneOf: options.tagsOneOf,
1077 tagsAllOf: options.tagsAllOf,
1079 filter: options.filter,
1080 start: options.start,
1081 count: options.count,
1083 startDate: options.startDate,
1084 endDate: options.endDate,
1085 originallyPublishedStartDate: options.originallyPublishedStartDate,
1086 originallyPublishedEndDate: options.originallyPublishedEndDate,
1088 durationMin: options.durationMin,
1089 durationMax: options.durationMax,
1091 search: options.search
1094 return VideoModel.getAvailableForApi(queryOptions)
1097 static load (id: number | string, t?: Transaction): Bluebird<MVideoThumbnail> {
1098 const where = buildWhereIdOrUUID(id)
1104 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1107 static loadWithBlacklist (id: number | string, t?: Transaction): Bluebird<MVideoThumbnailBlacklist> {
1108 const where = buildWhereIdOrUUID(id)
1114 return VideoModel.scope([
1115 ScopeNames.WITH_THUMBNAILS,
1116 ScopeNames.WITH_BLACKLISTED
1120 static loadImmutableAttributes (id: number | string, t?: Transaction): Bluebird<MVideoImmutable> {
1123 where: buildWhereIdOrUUID(id),
1127 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1130 return ModelCache.Instance.doCache({
1131 cacheType: 'load-video-immutable-id',
1138 static loadWithRights (id: number | string, t?: Transaction): Bluebird<MVideoWithRights> {
1139 const where = buildWhereIdOrUUID(id)
1145 return VideoModel.scope([
1146 ScopeNames.WITH_BLACKLISTED,
1147 ScopeNames.WITH_USER_ID,
1148 ScopeNames.WITH_THUMBNAILS
1152 static loadOnlyId (id: number | string, t?: Transaction): Bluebird<MVideoIdThumbnail> {
1153 const where = buildWhereIdOrUUID(id)
1156 attributes: [ 'id' ],
1161 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1164 static loadWithFiles (id: number | string, t?: Transaction, logging?: boolean): Bluebird<MVideoWithAllFiles> {
1165 const where = buildWhereIdOrUUID(id)
1173 return VideoModel.scope([
1174 ScopeNames.WITH_WEBTORRENT_FILES,
1175 ScopeNames.WITH_STREAMING_PLAYLISTS,
1176 ScopeNames.WITH_THUMBNAILS
1180 static loadByUUID (uuid: string): Bluebird<MVideoThumbnail> {
1187 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1190 static loadByUrl (url: string, transaction?: Transaction): Bluebird<MVideoThumbnail> {
1191 const query: FindOptions = {
1198 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(query)
1201 static loadByUrlImmutableAttributes (url: string, transaction?: Transaction): Bluebird<MVideoImmutable> {
1203 const query: FindOptions = {
1210 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1213 return ModelCache.Instance.doCache({
1214 cacheType: 'load-video-immutable-url',
1221 static loadByUrlAndPopulateAccount (url: string, transaction?: Transaction): Bluebird<MVideoAccountLightBlacklistAllFiles> {
1222 const query: FindOptions = {
1229 return VideoModel.scope([
1230 ScopeNames.WITH_ACCOUNT_DETAILS,
1231 ScopeNames.WITH_WEBTORRENT_FILES,
1232 ScopeNames.WITH_STREAMING_PLAYLISTS,
1233 ScopeNames.WITH_THUMBNAILS,
1234 ScopeNames.WITH_BLACKLISTED
1238 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Transaction, userId?: number): Bluebird<MVideoFullLight> {
1239 const where = buildWhereIdOrUUID(id)
1242 order: [ [ 'Tags', 'name', 'ASC' ] ] as any,
1247 const scopes: (string | ScopeOptions)[] = [
1248 ScopeNames.WITH_TAGS,
1249 ScopeNames.WITH_BLACKLISTED,
1250 ScopeNames.WITH_ACCOUNT_DETAILS,
1251 ScopeNames.WITH_SCHEDULED_UPDATE,
1252 ScopeNames.WITH_WEBTORRENT_FILES,
1253 ScopeNames.WITH_STREAMING_PLAYLISTS,
1254 ScopeNames.WITH_THUMBNAILS
1258 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1266 static loadForGetAPI (parameters: {
1270 }): Bluebird<MVideoDetails> {
1271 const { id, t, userId } = parameters
1272 const where = buildWhereIdOrUUID(id)
1275 order: [ [ 'Tags', 'name', 'ASC' ] ] as any, // FIXME: sequelize typings
1280 const scopes: (string | ScopeOptions)[] = [
1281 ScopeNames.WITH_TAGS,
1282 ScopeNames.WITH_BLACKLISTED,
1283 ScopeNames.WITH_ACCOUNT_DETAILS,
1284 ScopeNames.WITH_SCHEDULED_UPDATE,
1285 ScopeNames.WITH_THUMBNAILS,
1286 { method: [ ScopeNames.WITH_WEBTORRENT_FILES, true ] },
1287 { method: [ ScopeNames.WITH_STREAMING_PLAYLISTS, true ] }
1291 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1299 static async getStats () {
1300 const totalLocalVideos = await VideoModel.count({
1306 let totalLocalVideoViews = await VideoModel.sum('views', {
1312 // Sequelize could return null...
1313 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1315 const { total: totalVideos } = await VideoModel.listForApi({
1318 sort: '-publishedAt',
1319 nsfw: buildNSFWFilter(),
1320 includeLocalVideos: true,
1326 totalLocalVideoViews,
1331 static incrementViews (id: number, views: number) {
1332 return VideoModel.increment('views', {
1340 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1341 // Instances only share videos
1342 const query = 'SELECT 1 FROM "videoShare" ' +
1343 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1344 'WHERE "actorFollow"."actorId" = $followerActorId AND "videoShare"."videoId" = $videoId ' +
1348 type: QueryTypes.SELECT as QueryTypes.SELECT,
1349 bind: { followerActorId, videoId },
1353 return VideoModel.sequelize.query(query, options)
1354 .then(results => results.length === 1)
1357 static bulkUpdateSupportField (videoChannel: MChannel, t: Transaction) {
1360 channelId: videoChannel.id
1365 return VideoModel.update({ support: videoChannel.support }, options)
1368 static getAllIdsFromChannel (videoChannel: MChannelId): Bluebird<number[]> {
1370 attributes: [ 'id' ],
1372 channelId: videoChannel.id
1376 return VideoModel.findAll(query)
1377 .then(videos => videos.map(v => v.id))
1380 // threshold corresponds to how many video the field should have to be returned
1381 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1382 const serverActor = await getServerActor()
1383 const followerActorId = serverActor.id
1385 const queryOptions: BuildVideosQueryOptions = {
1386 attributes: [ `"${field}"` ],
1387 group: `GROUP BY "${field}"`,
1388 having: `HAVING COUNT("${field}") >= ${threshold}`,
1392 serverAccountId: serverActor.Account.id,
1394 includeLocalVideos: true
1397 const { query, replacements } = buildListQuery(VideoModel, queryOptions)
1399 return this.sequelize.query<any>(query, { replacements, type: QueryTypes.SELECT })
1400 .then(rows => rows.map(r => r[field]))
1403 static buildTrendingQuery (trendingDays: number) {
1407 model: VideoViewModel,
1411 [Op.gte]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1417 private static async getAvailableForApi (
1418 options: BuildVideosQueryOptions,
1421 function getCount () {
1422 if (countVideos !== true) return Promise.resolve(undefined)
1424 const countOptions = Object.assign({}, options, { isCount: true })
1425 const { query: queryCount, replacements: replacementsCount } = buildListQuery(VideoModel, countOptions)
1427 return VideoModel.sequelize.query<any>(queryCount, { replacements: replacementsCount, type: QueryTypes.SELECT })
1428 .then(rows => rows.length !== 0 ? rows[0].total : 0)
1431 function getModels () {
1432 if (options.count === 0) return Promise.resolve([])
1434 const { query, replacements, order } = buildListQuery(VideoModel, options)
1435 const queryModels = wrapForAPIResults(query, replacements, options, order)
1437 return VideoModel.sequelize.query<any>(queryModels, { replacements, type: QueryTypes.SELECT, nest: true })
1438 .then(rows => VideoModel.buildAPIResult(rows))
1441 const [ count, rows ] = await Promise.all([ getCount(), getModels() ])
1449 private static buildAPIResult (rows: any[]) {
1450 const memo: { [ id: number ]: VideoModel } = {}
1452 const thumbnailsDone = new Set<number>()
1453 const historyDone = new Set<number>()
1454 const videoFilesDone = new Set<number>()
1456 const videos: VideoModel[] = []
1458 const avatarKeys = [ 'id', 'filename', 'fileUrl', 'onDisk', 'createdAt', 'updatedAt' ]
1459 const actorKeys = [ 'id', 'preferredUsername', 'url', 'serverId', 'avatarId' ]
1460 const serverKeys = [ 'id', 'host' ]
1461 const videoFileKeys = [ 'id', 'createdAt', 'updatedAt', 'resolution', 'size', 'extname', 'infoHash', 'fps', 'videoId' ]
1484 'originallyPublishedAt',
1490 function buildActor (rowActor: any) {
1491 const avatarModel = rowActor.Avatar.id !== null
1492 ? new AvatarModel(pick(rowActor.Avatar, avatarKeys))
1495 const serverModel = rowActor.Server.id !== null
1496 ? new ServerModel(pick(rowActor.Server, serverKeys))
1499 const actorModel = new ActorModel(pick(rowActor, actorKeys))
1500 actorModel.Avatar = avatarModel
1501 actorModel.Server = serverModel
1506 for (const row of rows) {
1507 if (!memo[row.id]) {
1509 const channel = row.VideoChannel
1510 const channelModel = new VideoChannelModel(pick(channel, [ 'id', 'name', 'description', 'actorId' ]))
1511 channelModel.Actor = buildActor(channel.Actor)
1513 const account = row.VideoChannel.Account
1514 const accountModel = new AccountModel(pick(account, [ 'id', 'name' ]))
1515 accountModel.Actor = buildActor(account.Actor)
1517 channelModel.Account = accountModel
1519 const videoModel = new VideoModel(pick(row, videoKeys))
1520 videoModel.VideoChannel = channelModel
1522 videoModel.UserVideoHistories = []
1523 videoModel.Thumbnails = []
1524 videoModel.VideoFiles = []
1526 memo[row.id] = videoModel
1527 // Don't take object value to have a sorted array
1528 videos.push(videoModel)
1531 const videoModel = memo[row.id]
1533 if (row.userVideoHistory?.id && !historyDone.has(row.userVideoHistory.id)) {
1534 const historyModel = new UserVideoHistoryModel(pick(row.userVideoHistory, [ 'id', 'currentTime' ]))
1535 videoModel.UserVideoHistories.push(historyModel)
1537 historyDone.add(row.userVideoHistory.id)
1540 if (row.Thumbnails?.id && !thumbnailsDone.has(row.Thumbnails.id)) {
1541 const thumbnailModel = new ThumbnailModel(pick(row.Thumbnails, [ 'id', 'type', 'filename' ]))
1542 videoModel.Thumbnails.push(thumbnailModel)
1544 thumbnailsDone.add(row.Thumbnails.id)
1547 if (row.VideoFiles?.id && !videoFilesDone.has(row.VideoFiles.id)) {
1548 const videoFileModel = new VideoFileModel(pick(row.VideoFiles, videoFileKeys))
1549 videoModel.VideoFiles.push(videoFileModel)
1551 videoFilesDone.add(row.VideoFiles.id)
1558 private static isPrivacyForFederation (privacy: VideoPrivacy) {
1559 const castedPrivacy = parseInt(privacy + '', 10)
1561 return castedPrivacy === VideoPrivacy.PUBLIC || castedPrivacy === VideoPrivacy.UNLISTED
1564 static getCategoryLabel (id: number) {
1565 return VIDEO_CATEGORIES[id] || 'Misc'
1568 static getLicenceLabel (id: number) {
1569 return VIDEO_LICENCES[id] || 'Unknown'
1572 static getLanguageLabel (id: string) {
1573 return VIDEO_LANGUAGES[id] || 'Unknown'
1576 static getPrivacyLabel (id: number) {
1577 return VIDEO_PRIVACIES[id] || 'Unknown'
1580 static getStateLabel (id: number) {
1581 return VIDEO_STATES[id] || 'Unknown'
1585 return !!this.VideoBlacklist
1589 return (this.VideoChannel.Account.Actor.Server && this.VideoChannel.Account.Actor.Server.isBlocked()) ||
1590 this.VideoChannel.Account.isBlocked()
1593 getQualityFileBy<T extends MVideoWithFile> (this: T, fun: (files: MVideoFile[], it: (file: MVideoFile) => number) => MVideoFile) {
1594 if (Array.isArray(this.VideoFiles) && this.VideoFiles.length !== 0) {
1595 const file = fun(this.VideoFiles, file => file.resolution)
1597 return Object.assign(file, { Video: this })
1600 // No webtorrent files, try with streaming playlist files
1601 if (Array.isArray(this.VideoStreamingPlaylists) && this.VideoStreamingPlaylists.length !== 0) {
1602 const streamingPlaylistWithVideo = Object.assign(this.VideoStreamingPlaylists[0], { Video: this })
1604 const file = fun(streamingPlaylistWithVideo.VideoFiles, file => file.resolution)
1605 return Object.assign(file, { VideoStreamingPlaylist: streamingPlaylistWithVideo })
1611 getMaxQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1612 return this.getQualityFileBy(maxBy)
1615 getMinQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1616 return this.getQualityFileBy(minBy)
1619 getWebTorrentFile<T extends MVideoWithFile> (this: T, resolution: number): MVideoFileVideo {
1620 if (Array.isArray(this.VideoFiles) === false) return undefined
1622 const file = this.VideoFiles.find(f => f.resolution === resolution)
1623 if (!file) return undefined
1625 return Object.assign(file, { Video: this })
1628 async addAndSaveThumbnail (thumbnail: MThumbnail, transaction: Transaction) {
1629 thumbnail.videoId = this.id
1631 const savedThumbnail = await thumbnail.save({ transaction })
1633 if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = []
1635 // Already have this thumbnail, skip
1636 if (this.Thumbnails.find(t => t.id === savedThumbnail.id)) return
1638 this.Thumbnails.push(savedThumbnail)
1641 generateThumbnailName () {
1642 return this.uuid + '.jpg'
1646 if (Array.isArray(this.Thumbnails) === false) return undefined
1648 return this.Thumbnails.find(t => t.type === ThumbnailType.MINIATURE)
1651 generatePreviewName () {
1652 return this.uuid + '.jpg'
1656 return !!this.getPreview()
1660 if (Array.isArray(this.Thumbnails) === false) return undefined
1662 return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW)
1666 return this.remote === false
1669 getWatchStaticPath () {
1670 return '/videos/watch/' + this.uuid
1673 getEmbedStaticPath () {
1674 return '/videos/embed/' + this.uuid
1677 getMiniatureStaticPath () {
1678 const thumbnail = this.getMiniature()
1679 if (!thumbnail) return null
1681 return join(STATIC_PATHS.THUMBNAILS, thumbnail.filename)
1684 getPreviewStaticPath () {
1685 const preview = this.getPreview()
1686 if (!preview) return null
1688 // We use a local cache, so specify our cache endpoint instead of potential remote URL
1689 return join(LAZY_STATIC_PATHS.PREVIEWS, preview.filename)
1692 toFormattedJSON (this: MVideoFormattable, options?: VideoFormattingJSONOptions): Video {
1693 return videoModelToFormattedJSON(this, options)
1696 toFormattedDetailsJSON (this: MVideoFormattableDetails): VideoDetails {
1697 return videoModelToFormattedDetailsJSON(this)
1700 getFormattedVideoFilesJSON (): VideoFile[] {
1701 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1702 return videoFilesModelToFormattedJSON(this, baseUrlHttp, baseUrlWs, this.VideoFiles)
1705 toActivityPubObject (this: MVideoAP): VideoTorrentObject {
1706 return videoModelToActivityPubObject(this)
1709 getTruncatedDescription () {
1710 if (!this.description) return null
1712 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1713 return peertubeTruncate(this.description, { length: maxLength })
1716 getMaxQualityResolution () {
1717 const file = this.getMaxQualityFile()
1718 const videoOrPlaylist = file.getVideoOrStreamingPlaylist()
1719 const originalFilePath = getVideoFilePath(videoOrPlaylist, file)
1721 return getVideoFileResolution(originalFilePath)
1724 getDescriptionAPIPath () {
1725 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1728 getHLSPlaylist (): MStreamingPlaylistFilesVideo {
1729 if (!this.VideoStreamingPlaylists) return undefined
1731 const playlist = this.VideoStreamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
1732 playlist.Video = this
1737 setHLSPlaylist (playlist: MStreamingPlaylist) {
1738 const toAdd = [ playlist ] as [ VideoStreamingPlaylistModel ]
1740 if (Array.isArray(this.VideoStreamingPlaylists) === false || this.VideoStreamingPlaylists.length === 0) {
1741 this.VideoStreamingPlaylists = toAdd
1745 this.VideoStreamingPlaylists = this.VideoStreamingPlaylists
1746 .filter(s => s.type !== VideoStreamingPlaylistType.HLS)
1750 removeFile (videoFile: MVideoFile, isRedundancy = false) {
1751 const filePath = getVideoFilePath(this, videoFile, isRedundancy)
1752 return remove(filePath)
1753 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1756 removeTorrent (videoFile: MVideoFile) {
1757 const torrentPath = getTorrentFilePath(this, videoFile)
1758 return remove(torrentPath)
1759 .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err }))
1762 async removeStreamingPlaylistFiles (streamingPlaylist: MStreamingPlaylist, isRedundancy = false) {
1763 const directoryPath = getHLSDirectory(this, isRedundancy)
1765 await remove(directoryPath)
1767 if (isRedundancy !== true) {
1768 const streamingPlaylistWithFiles = streamingPlaylist as MStreamingPlaylistFilesVideo
1769 streamingPlaylistWithFiles.Video = this
1771 if (!Array.isArray(streamingPlaylistWithFiles.VideoFiles)) {
1772 streamingPlaylistWithFiles.VideoFiles = await streamingPlaylistWithFiles.$get('VideoFiles')
1775 // Remove physical files and torrents
1777 streamingPlaylistWithFiles.VideoFiles.map(file => streamingPlaylistWithFiles.removeTorrent(file))
1783 if (this.isOwned()) return false
1785 return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)
1788 hasPrivacyForFederation () {
1789 return VideoModel.isPrivacyForFederation(this.privacy)
1792 isNewVideo (newPrivacy: VideoPrivacy) {
1793 return this.hasPrivacyForFederation() === false && VideoModel.isPrivacyForFederation(newPrivacy) === true
1797 this.changed('updatedAt', true)
1803 return this.privacy === VideoPrivacy.PRIVATE || this.privacy === VideoPrivacy.INTERNAL || !!this.VideoBlacklist
1806 setPrivacy (newPrivacy: VideoPrivacy) {
1807 if (this.privacy === VideoPrivacy.PRIVATE && newPrivacy !== VideoPrivacy.PRIVATE) {
1808 this.publishedAt = new Date()
1811 this.privacy = newPrivacy
1815 return this.privacy === VideoPrivacy.PRIVATE ||
1816 this.privacy === VideoPrivacy.UNLISTED ||
1817 this.privacy === VideoPrivacy.INTERNAL
1820 async publishIfNeededAndSave (t: Transaction) {
1821 if (this.state !== VideoState.PUBLISHED) {
1822 this.state = VideoState.PUBLISHED
1823 this.publishedAt = new Date()
1824 await this.save({ transaction: t })
1833 if (this.isOwned()) {
1835 baseUrlHttp: WEBSERVER.URL,
1836 baseUrlWs: WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT
1841 baseUrlHttp: REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host,
1842 baseUrlWs: REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1846 getTrackerUrls (baseUrlHttp: string, baseUrlWs: string) {
1847 return [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1850 getTorrentUrl (videoFile: MVideoFile, baseUrlHttp: string) {
1851 return baseUrlHttp + STATIC_PATHS.TORRENTS + getTorrentFileName(this, videoFile)
1854 getTorrentDownloadUrl (videoFile: MVideoFile, baseUrlHttp: string) {
1855 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + getTorrentFileName(this, videoFile)
1858 getVideoFileUrl (videoFile: MVideoFile, baseUrlHttp: string) {
1859 return baseUrlHttp + STATIC_PATHS.WEBSEED + getVideoFilename(this, videoFile)
1862 getVideoFileMetadataUrl (videoFile: MVideoFile, baseUrlHttp: string) {
1863 const path = '/api/v1/videos/'
1865 return this.isOwned()
1866 ? baseUrlHttp + path + this.uuid + '/metadata/' + videoFile.id
1867 : videoFile.metadataUrl
1870 getVideoRedundancyUrl (videoFile: MVideoFile, baseUrlHttp: string) {
1871 return baseUrlHttp + STATIC_PATHS.REDUNDANCY + getVideoFilename(this, videoFile)
1874 getVideoFileDownloadUrl (videoFile: MVideoFile, baseUrlHttp: string) {
1875 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + getVideoFilename(this, videoFile)
1878 getBandwidthBits (videoFile: MVideoFile) {
1879 return Math.ceil((videoFile.size * 8) / this.duration)