ActivityPub-federated video streaming platform using P2P directly in your web browser
Take into account channel owner video quota
Chocobozzz675310a5fac4
diff --git a/packages/server-commands/src/shared/abstract-command.ts b/packages/server-commands/src/shared/abstract-command.tsindex 0b4bafce9e..86e96577b7 100644--- a/packages/server-commands/src/shared/abstract-command.ts+++ b/packages/server-commands/src/shared/abstract-command.ts@@ -263,6 +263,12 @@ export abstract class AbstractCommand {const initStatus = initializeSessionRes.statusif (videoFilePath && initStatus === HttpStatusCode.CREATED_201) {+ if (expectedStatus !== HttpStatusCode.OK_200) {+ throw new Error(+ `Expected status code is not correct for resumable upload initialization. Expected ${expectedStatus} but got success`+ )+ }+const locationHeader = initializeSessionRes.header['location']expect(locationHeader).to.not.be.undefineddiff --git a/packages/server-commands/src/videos/channel-collaborators-command.ts b/packages/server-commands/src/videos/channel-collaborators-command.tsindex 5c82551458..7140c32345 100644--- a/packages/server-commands/src/videos/channel-collaborators-command.ts+++ b/packages/server-commands/src/videos/channel-collaborators-command.ts@@ -102,9 +102,7 @@ export class ChannelCollaboratorsCommand extends AbstractCommand {async createEditor (user: string, channel: string) {const collaboratorToken = await this.server.users.generateUserAndToken(user)- const { id } = await this.invite({ channel, target: user })-- await this.accept({ channel, id, token: collaboratorToken })+ await this.addEditor({ channel, editorToken: collaboratorToken, editor: user })return collaboratorToken}@@ -116,4 +114,16 @@ export class ChannelCollaboratorsCommand extends AbstractCommand {return collaboratorToken}++ async addEditor (options: {+ channel: string+ editorToken: string+ editor: string+ }) {+ const { editor, channel, editorToken } = options++ const { id } = await this.invite({ channel, target: editor })++ await this.accept({ channel, id, token: editorToken })+ }}diff --git a/packages/tests/src/api/check-params/upload-quota.ts b/packages/tests/src/api/check-params/upload-quota.tsindex 908ba84a65..017f575265 100644--- a/packages/tests/src/api/check-params/upload-quota.ts+++ b/packages/tests/src/api/check-params/upload-quota.ts@@ -1,7 +1,5 @@/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */-import { expect } from 'chai'-import { FIXTURE_URLS } from '@tests/shared/fixture-urls.js'import { randomInt } from '@peertube/peertube-core-utils'import { HttpStatusCode, VideoImportState, VideoPrivacy } from '@peertube/peertube-models'import {@@ -13,11 +11,15 @@ import {VideosCommand,waitJobs} from '@peertube/peertube-server-commands'+import { FIXTURE_URLS } from '@tests/shared/fixture-urls.js'+import { expect } from 'chai'describe('Test upload quota', function () {let server: PeerTubeServerlet rootId: numberlet command: VideosCommand+ let editorToken: string+ let editorId: number// ---------------------------------------------------------------@@ -34,6 +36,10 @@ describe('Test upload quota', function () {await server.users.update({ userId: rootId, videoQuota: 42 })command = server.videos++ editorToken = await server.channelCollaborators.createEditor('editor', 'root_channel')+ editorId = await server.users.getMyInfo({ token: editorToken }).then(info => info.id)+ await server.users.update({ userId: editorId, videoQuota: -1, videoQuotaDaily: -1 })})describe('When having a video quota', function () {@@ -70,20 +76,22 @@ describe('Test upload quota', function () {it('Should fail to import with HTTP/Torrent/magnet', async function () {this.timeout(120_000)- const baseAttributes = {- channelId: server.store.channel.id,- privacy: VideoPrivacy.PUBLIC+ for (const token of [ server.accessToken, editorToken ]) {+ const baseAttributes = {+ channelId: server.store.channel.id,+ privacy: VideoPrivacy.PUBLIC+ }+ await server.videoImports.importVideo({ token, attributes: { ...baseAttributes, targetUrl: FIXTURE_URLS.goodVideo } })+ await server.videoImports.importVideo({ token, attributes: { ...baseAttributes, magnetUri: FIXTURE_URLS.magnet } })+ await server.videoImports.importVideo({ token, attributes: { ...baseAttributes, torrentfile: 'video-720p.torrent' as any } })}- await server.videoImports.importVideo({ attributes: { ...baseAttributes, targetUrl: FIXTURE_URLS.goodVideo } })- await server.videoImports.importVideo({ attributes: { ...baseAttributes, magnetUri: FIXTURE_URLS.magnet } })- await server.videoImports.importVideo({ attributes: { ...baseAttributes, torrentfile: 'video-720p.torrent' as any } })await waitJobs([ server ])const { total, data: videoImports } = await server.videoImports.listMyVideoImports()- expect(total).to.equal(3)+ expect(total).to.equal(6)- expect(videoImports).to.have.lengthOf(3)+ expect(videoImports).to.have.lengthOf(6)for (const videoImport of videoImports) {expect(videoImport.state.id).to.equal(VideoImportState.FAILED)@@ -97,8 +105,12 @@ describe('Test upload quota', function () {it('Should fail with a user having too many videos daily', async function () {await server.users.update({ userId: rootId, videoQuotaDaily: 42 })- await command.upload({ expectedStatus: HttpStatusCode.PAYLOAD_TOO_LARGE_413, mode: 'legacy' })- await command.upload({ expectedStatus: HttpStatusCode.PAYLOAD_TOO_LARGE_413, mode: 'resumable' })+ for (const token of [ server.accessToken, editorToken ]) {+ const attributes = { channelId: server.store.channel.id }++ await command.upload({ token, expectedStatus: HttpStatusCode.PAYLOAD_TOO_LARGE_413, mode: 'legacy', attributes })+ await command.upload({ token, expectedStatus: HttpStatusCode.PAYLOAD_TOO_LARGE_413, mode: 'resumable', attributes })+ }})})@@ -126,6 +138,52 @@ describe('Test upload quota', function () {})})+ describe('With channel editors', function () {+ it('Should take into account the quota of the target channel', async function () {+ await server.users.update({ userId: rootId, videoQuota: 42, videoQuotaDaily: 42 })++ await command.upload({+ token: editorToken,+ attributes: { channelId: server.store.channel.id },+ expectedStatus: HttpStatusCode.PAYLOAD_TOO_LARGE_413+ })++ await command.upload({+ token: editorToken,+ attributes: { channelId: await server.channels.getIdOf({ channelName: 'editor_channel' }) }+ })+ })++ it('Should not be able to update the channel of a video if the target channel owner has no quota left', async function () {+ await server.users.update({ userId: rootId, videoQuota: -1, videoQuotaDaily: -1 })+ await server.users.update({ userId: editorId, videoQuota: 42, videoQuotaDaily: 42 })++ await server.channels.create({ attributes: { name: 'root_channel2' }, token: server.accessToken })+ await server.channelCollaborators.addEditor({ channel: 'root_channel2', editorToken, editor: 'editor' })++ const { uuid } = await command.quickUpload({ name: 'video' })++ // Another root channel, no problem+ await command.update({+ id: uuid,+ token: editorToken,+ attributes: {+ channelId: await server.channels.getIdOf({ channelName: 'root_channel2' })+ }+ })++ // Editor channel, failing+ await command.update({+ id: uuid,+ token: editorToken,+ attributes: {+ channelId: await server.channels.getIdOf({ channelName: 'editor_channel' })+ },+ expectedStatus: HttpStatusCode.PAYLOAD_TOO_LARGE_413+ })+ })+ })+after(async function () {await cleanupTests([ server ])})diff --git a/packages/tests/src/api/check-params/video-studio.ts b/packages/tests/src/api/check-params/video-studio.tsindex 6c2e3f7681..d6a050d08d 100644--- a/packages/tests/src/api/check-params/video-studio.ts+++ b/packages/tests/src/api/check-params/video-studio.ts@@ -348,10 +348,12 @@ describe('Test video studio API validator', function () {this.timeout(360000)const user = await server.users.create({ username: 'user_quota_1' })- const token = await server.login.getAccessToken('user_quota_1')- const { uuid } = await server.videos.quickUpload({ token, name: 'video_quota_1', fixture: 'video_short.mp4' })+ const userToken = await server.login.getAccessToken('user_quota_1')+ const editorToken = await server.channelCollaborators.createEditor('editor_quota_1', 'user_quota_1_channel')- const addIntroOutroByUser = (type: 'add-intro' | 'add-outro', expectedStatus: HttpStatusCodeType) => {+ const { uuid } = await server.videos.quickUpload({ token: userToken, name: 'video_quota_1', fixture: 'video_short.mp4' })++ const addIntroOutroByUser = (type: 'add-intro' | 'add-outro', token: string, expectedStatus: HttpStatusCodeType) => {return command.createEditionTasks({token,videoId: uuid,@@ -369,17 +371,19 @@ describe('Test video studio API validator', function () {await waitJobs([ server ])- const { videoQuotaUsed } = await server.users.getMyQuotaUsed({ token })+ const { videoQuotaUsed } = await server.users.getMyQuotaUsed({ token: userToken })await server.users.update({ userId: user.id, videoQuota: Math.round(videoQuotaUsed * 2.5) })// Still valid- await addIntroOutroByUser('add-intro', HttpStatusCode.NO_CONTENT_204)+ await addIntroOutroByUser('add-intro', userToken, HttpStatusCode.NO_CONTENT_204)await waitJobs([ server ])// Too much quota- await addIntroOutroByUser('add-intro', HttpStatusCode.PAYLOAD_TOO_LARGE_413)- await addIntroOutroByUser('add-outro', HttpStatusCode.PAYLOAD_TOO_LARGE_413)+ for (const token of [ userToken, editorToken ]) {+ await addIntroOutroByUser('add-intro', token, HttpStatusCode.PAYLOAD_TOO_LARGE_413)+ await addIntroOutroByUser('add-outro', token, HttpStatusCode.PAYLOAD_TOO_LARGE_413)+ }})})})diff --git a/packages/tests/src/api/live/live-constraints.ts b/packages/tests/src/api/live/live-constraints.tsindex 60906e346a..cd9cefd349 100644--- a/packages/tests/src/api/live/live-constraints.ts+++ b/packages/tests/src/api/live/live-constraints.ts@@ -4,7 +4,8 @@ import { wait } from '@peertube/peertube-core-utils'import { LiveVideoError, UserVideoQuota, VideoPrivacy, VideoResolution } from '@peertube/peertube-models'import {PeerTubeServer,- cleanupTests, createMultipleServers,+ cleanupTests,+ createMultipleServers,doubleFollow,setAccessTokensToServers,setDefaultVideoChannel,@@ -21,9 +22,10 @@ describe('Test live constraints', function () {let userId: numberlet userAccessToken: stringlet userChannelId: number+ let editorToken: string- async function createLiveWrapper (options: { replay: boolean, permanent: boolean }) {- const { replay, permanent } = options+ async function createLiveWrapper (options: { replay: boolean, permanent: boolean, token?: string }) {+ const { replay, permanent, token = userAccessToken } = optionsconst liveAttributes = {name: 'user live',@@ -34,7 +36,7 @@ describe('Test live constraints', function () {permanentLive: permanent}- const { uuid } = await servers[0].live.create({ token: userAccessToken, fields: liveAttributes })+ const { uuid } = await servers[0].live.create({ token, fields: liveAttributes })return uuid}@@ -77,6 +79,8 @@ describe('Test live constraints', function () {await updateQuota({ total: 1, daily: -1 })}+ editorToken = await servers[0].channelCollaborators.createEditor('editor', 'user1_channel')+// Server 1 and server 2 follow each otherawait doubleFollow(servers[0], servers[1])})@@ -84,8 +88,8 @@ describe('Test live constraints', function () {it('Should not have size limit if save replay is disabled', async function () {this.timeout(60000)- const userVideoLiveoId = await createLiveWrapper({ replay: false, permanent: false })- await servers[0].live.runAndTestStreamError({ token: userAccessToken, videoId: userVideoLiveoId, shouldHaveError: false })+ const userVideoLiveId = await createLiveWrapper({ replay: false, permanent: false })+ await servers[0].live.runAndTestStreamError({ token: userAccessToken, videoId: userVideoLiveId, shouldHaveError: false })})it('Should have size limit depending on user global quota if save replay is enabled on non permanent live', async function () {@@ -94,15 +98,15 @@ describe('Test live constraints', function () {// Wait for user quota memoize cache invalidationawait wait(5000)- const userVideoLiveoId = await createLiveWrapper({ replay: true, permanent: false })- await servers[0].live.runAndTestStreamError({ token: userAccessToken, videoId: userVideoLiveoId, shouldHaveError: true })+ const userVideoLiveId = await createLiveWrapper({ replay: true, permanent: false })+ await servers[0].live.runAndTestStreamError({ token: userAccessToken, videoId: userVideoLiveId, shouldHaveError: true })- await waitUntilLiveReplacedByReplayOnAllServers(servers, userVideoLiveoId)+ await waitUntilLiveReplacedByReplayOnAllServers(servers, userVideoLiveId)await waitJobs(servers)- await checkSaveReplay(userVideoLiveoId, [ VideoResolution.H_720P ])+ await checkSaveReplay(userVideoLiveId, [ VideoResolution.H_720P ])- const session = await servers[0].live.getReplaySession({ videoId: userVideoLiveoId })+ const session = await servers[0].live.getReplaySession({ videoId: userVideoLiveId })expect(session.error).to.equal(LiveVideoError.QUOTA_EXCEEDED)})@@ -112,17 +116,17 @@ describe('Test live constraints', function () {// Wait for user quota memoize cache invalidationawait wait(5000)- const userVideoLiveoId = await createLiveWrapper({ replay: true, permanent: true })- await servers[0].live.runAndTestStreamError({ token: userAccessToken, videoId: userVideoLiveoId, shouldHaveError: true })+ const userVideoLiveId = await createLiveWrapper({ replay: true, permanent: true })+ await servers[0].live.runAndTestStreamError({ token: userAccessToken, videoId: userVideoLiveId, shouldHaveError: true })await waitJobs(servers)- await waitUntilLiveWaitingOnAllServers(servers, userVideoLiveoId)+ await waitUntilLiveWaitingOnAllServers(servers, userVideoLiveId)- const session = await servers[0].live.findLatestSession({ videoId: userVideoLiveoId })+ const session = await servers[0].live.findLatestSession({ videoId: userVideoLiveId })expect(session.error).to.equal(LiveVideoError.QUOTA_EXCEEDED)})- it('Should have size limit depending on user daily quota if save replay is enabled', async function () {+ it('Should have size limit depending on user daily quota if save replay is enabled with an editor token', async function () {this.timeout(60000)// Wait for user quota memoize cache invalidation@@ -130,15 +134,15 @@ describe('Test live constraints', function () {await updateQuota({ total: -1, daily: 1 })- const userVideoLiveoId = await createLiveWrapper({ replay: true, permanent: false })- await servers[0].live.runAndTestStreamError({ token: userAccessToken, videoId: userVideoLiveoId, shouldHaveError: true })+ const userVideoLiveId = await createLiveWrapper({ replay: true, permanent: false, token: editorToken })+ await servers[0].live.runAndTestStreamError({ token: userAccessToken, videoId: userVideoLiveId, shouldHaveError: true })- await waitUntilLiveReplacedByReplayOnAllServers(servers, userVideoLiveoId)+ await waitUntilLiveReplacedByReplayOnAllServers(servers, userVideoLiveId)await waitJobs(servers)- await checkSaveReplay(userVideoLiveoId, [ VideoResolution.H_720P ])+ await checkSaveReplay(userVideoLiveId, [ VideoResolution.H_720P ])- const session = await servers[0].live.getReplaySession({ videoId: userVideoLiveoId })+ const session = await servers[0].live.getReplaySession({ videoId: userVideoLiveId })expect(session.error).to.equal(LiveVideoError.QUOTA_EXCEEDED)})@@ -150,17 +154,17 @@ describe('Test live constraints', function () {await updateQuota({ total: 10 * 1000 * 1000, daily: -1 })- const userVideoLiveoId = await createLiveWrapper({ replay: true, permanent: false })- await servers[0].live.runAndTestStreamError({ token: userAccessToken, videoId: userVideoLiveoId, shouldHaveError: false })+ const userVideoLiveId = await createLiveWrapper({ replay: true, permanent: false })+ await servers[0].live.runAndTestStreamError({ token: userAccessToken, videoId: userVideoLiveId, shouldHaveError: false })})it('Should have the same quota in admin and as a user', async function () {this.timeout(120000)- const userVideoLiveoId = await createLiveWrapper({ replay: true, permanent: false })- const ffmpegCommand = await servers[0].live.sendRTMPStreamInVideo({ token: userAccessToken, videoId: userVideoLiveoId })+ const userVideoLiveId = await createLiveWrapper({ replay: true, permanent: false })+ const ffmpegCommand = await servers[0].live.sendRTMPStreamInVideo({ token: userAccessToken, videoId: userVideoLiveId })- await servers[0].live.waitUntilPublished({ videoId: userVideoLiveoId })+ await servers[0].live.waitUntilPublished({ videoId: userVideoLiveId })// Wait previous live cleanupsawait wait(3000)@@ -217,15 +221,15 @@ describe('Test live constraints', function () {}})- const userVideoLiveoId = await createLiveWrapper({ replay: true, permanent: false })- await servers[0].live.runAndTestStreamError({ token: userAccessToken, videoId: userVideoLiveoId, shouldHaveError: true })+ const userVideoLiveId = await createLiveWrapper({ replay: true, permanent: false })+ await servers[0].live.runAndTestStreamError({ token: userAccessToken, videoId: userVideoLiveId, shouldHaveError: true })- await waitUntilLiveReplacedByReplayOnAllServers(servers, userVideoLiveoId)+ await waitUntilLiveReplacedByReplayOnAllServers(servers, userVideoLiveId)await waitJobs(servers)- await checkSaveReplay(userVideoLiveoId, [ 720, 240, 144, 0 ])+ await checkSaveReplay(userVideoLiveId, [ 720, 240, 144, 0 ])- const session = await servers[0].live.getReplaySession({ videoId: userVideoLiveoId })+ const session = await servers[0].live.getReplaySession({ videoId: userVideoLiveId })expect(session.error).to.equal(LiveVideoError.DURATION_EXCEEDED)})diff --git a/server/core/lib/job-queue/handlers/video-import.ts b/server/core/lib/job-queue/handlers/video-import.tsindex 90b3a4e786..ee77bdba38 100644--- a/server/core/lib/job-queue/handlers/video-import.ts+++ b/server/core/lib/job-queue/handlers/video-import.ts@@ -45,6 +45,7 @@ import { federateVideoIfNeeded } from '../../activitypub/videos/index.js'import { Notifier } from '../../notifier/index.js'import { createLocalVideoThumbnailsFromVideo } from '../../thumbnail.js'import { JobQueue } from '../job-queue.js'+import { UserModel } from '@server/models/user/user.js'async function processVideoImport (job: Job): Promise<VideoImportPreventExceptionResult> {const payload = job.data as VideoImportPayload@@ -152,7 +153,9 @@ async function processFile (downloader: () => Promise<string>, videoImport: MVid// Get information about this videoconst stats = await stat(tmpVideoPath)- const isAble = await isUserQuotaValid({ userId: videoImport.User.id, uploadSize: stats.size })+ const user = await UserModel.loadByVideoId(videoImport.videoId)++ const isAble = await isUserQuotaValid({ channelUserId: user.id, uploadSize: stats.size })if (isAble === false) {throw new Error('The user video quota is exceeded with this video to import.')}diff --git a/server/core/lib/job-queue/handlers/video-studio-edition.ts b/server/core/lib/job-queue/handlers/video-studio-edition.tsindex 4a03bd179b..b94db0e1ae 100644--- a/server/core/lib/job-queue/handlers/video-studio-edition.ts+++ b/server/core/lib/job-queue/handlers/video-studio-edition.ts@@ -198,7 +198,7 @@ async function checkUserQuotaOrThrow (video: MVideoFullLight, payload: VideoStudconst filePathFinder = (i: number) => (payload.tasks[i] as VideoStudioTaskIntroPayload | VideoStudioTaskOutroPayload).options.fileconst additionalBytes = await approximateIntroOutroAdditionalSize(video, payload.tasks, filePathFinder)- if (await isUserQuotaValid({ userId: user.id, uploadSize: additionalBytes }) === false) {+ if (await isUserQuotaValid({ channelUserId: user.id, uploadSize: additionalBytes }) === false) {throw new Error('Quota exceeded for this user to edit the video')}}diff --git a/server/core/lib/live/shared/muxing-session.ts b/server/core/lib/live/shared/muxing-session.tsindex 8afb420923..5dea64b83b 100644--- a/server/core/lib/live/shared/muxing-session.ts+++ b/server/core/lib/live/shared/muxing-session.ts@@ -110,8 +110,8 @@ class MuxingSession extends EventEmitter implements MuxingSession {private aborted = false- private readonly isAbleToUploadVideoWithCache = memoizee((userId: number) => {- return isUserQuotaValid({ userId, uploadSize: 1000 })+ private readonly isAbleToUploadVideoWithCache = memoizee((channelUserId: number) => {+ return isUserQuotaValid({ channelUserId, uploadSize: 1000 })}, { maxAge: MEMOIZE_TTL.LIVE_ABLE_TO_UPLOAD })private readonly hasClientSocketInBadHealthWithCache = memoizee((sessionId: string) => {diff --git a/server/core/lib/user-import-export/importers/videos-importer.ts b/server/core/lib/user-import-export/importers/videos-importer.tsindex 126a6a173c..dd8ebef0ba 100644--- a/server/core/lib/user-import-export/importers/videos-importer.ts+++ b/server/core/lib/user-import-export/importers/videos-importer.ts@@ -190,7 +190,7 @@ export class VideosImporter extends AbstractUserImporter<VideoExportJSON, Importlet ffprobe: FfprobeDataif (videoFilePath) {- if (await isUserQuotaValid({ userId: this.user.id, uploadSize: videoSize, checkDaily: false }) === false) {+ if (await isUserQuotaValid({ channelUserId: this.user.id, uploadSize: videoSize, checkDaily: false }) === false) {throw new Error(`Cannot import video ${videoImportData.name} for user ${this.user.username} because of exceeded quota`)}diff --git a/server/core/lib/user.ts b/server/core/lib/user.tsindex 03329e15f3..8bcff7e94b 100644--- a/server/core/lib/user.ts+++ b/server/core/lib/user.ts@@ -229,12 +229,12 @@ export async function getOriginalVideoFileTotalDailyFromUser (user: MUserId) {}export async function isUserQuotaValid (options: {- userId: number+ channelUserId: numberuploadSize: numbercheckDaily?: boolean // default true}) {- const { userId, uploadSize, checkDaily = true } = options- const user = await UserModel.loadById(userId)+ const { channelUserId, uploadSize, checkDaily = true } = options+ const user = await UserModel.loadById(channelUserId)if (user.videoQuota === -1 && user.videoQuotaDaily === -1) return Promise.resolve(true)@@ -248,7 +248,7 @@ export async function isUserQuotaValid (options: {logger.debug('Check user %d quota to upload content.',- userId,+ channelUserId,{ totalBytes, totalBytesDaily, videoQuota: user.videoQuota, videoQuotaDaily: user.videoQuotaDaily, uploadSize })diff --git a/server/core/middlewares/validators/shared/videos.ts b/server/core/middlewares/validators/shared/videos.tsindex 070001dcdd..f97b74301e 100644--- a/server/core/middlewares/validators/shared/videos.ts+++ b/server/core/middlewares/validators/shared/videos.ts@@ -339,19 +339,17 @@ export async function checkCanManageVideo (options: {return true}-type NewType = MUserId-// ---------------------------------------------------------------------------export async function checkUserQuota (options: {- user: NewType+ channelUser: MUserIdvideoFileSize: numberreq: Requestres: Response}) {- const { user, videoFileSize, req, res } = options+ const { channelUser, videoFileSize, req, res } = options- if (await isUserQuotaValid({ userId: user.id, uploadSize: videoFileSize }) === false) {+ if (await isUserQuotaValid({ channelUserId: channelUser.id, uploadSize: videoFileSize }) === false) {res.fail({status: HttpStatusCode.PAYLOAD_TOO_LARGE_413,message: req.t('The user video quota is exceeded with this video'),diff --git a/server/core/middlewares/validators/users/user-import.ts b/server/core/middlewares/validators/users/user-import.tsindex 53c86110de..112438adc8 100644--- a/server/core/middlewares/validators/users/user-import.ts+++ b/server/core/middlewares/validators/users/user-import.ts@@ -58,7 +58,7 @@ export const userImportRequestResumableInitValidator = [const fileMetadata = res.locals.uploadVideoFileResumableMetadataconst user = res.locals.user- if (await isUserQuotaValid({ userId: user.id, uploadSize: fileMetadata.size }) === false) {+ if (await isUserQuotaValid({ channelUserId: user.id, uploadSize: fileMetadata.size }) === false) {return res.fail({message: 'User video quota is exceeded with this import',status: HttpStatusCode.PAYLOAD_TOO_LARGE_413,diff --git a/server/core/middlewares/validators/videos/shared/video-validators.ts b/server/core/middlewares/validators/videos/shared/video-validators.tsindex 80c9fd363e..ab8c77e087 100644--- a/server/core/middlewares/validators/videos/shared/video-validators.ts+++ b/server/core/middlewares/validators/videos/shared/video-validators.ts@@ -5,18 +5,18 @@ import { logger } from '@server/helpers/logger.js'import { CONSTRAINTS_FIELDS, VIDEO_STATES } from '@server/initializers/constants.js'import { isLocalVideoFileAccepted } from '@server/lib/moderation.js'import { Hooks } from '@server/lib/plugins/hooks.js'-import { MUserAccountId, MVideo } from '@server/types/models/index.js'+import { MUserId, MVideo } from '@server/types/models/index.js'import express from 'express'import { checkUserQuota } from '../../shared/index.js'export async function commonVideoFileChecks (options: {req: express.Requestres: express.Response- user: MUserAccountId+ channelUser: MUserIdvideoFileSize: numberfiles: express.UploadFilesForCheck}): Promise<boolean> {- const { req, res, user, videoFileSize, files } = options+ const { req, res, channelUser, videoFileSize, files } = optionsif (!isVideoFileMimeTypeValid(files)) {res.fail({@@ -38,7 +38,7 @@ export async function commonVideoFileChecks (options: {return false}- if (await checkUserQuota({ user, videoFileSize, req, res }) === false) return false+ if (await checkUserQuota({ channelUser, videoFileSize, req, res }) === false) return falsereturn true}@@ -61,10 +61,12 @@ export async function isVideoFileAccepted (options: {if (acceptedResult?.accepted !== true) {logger.info('Refused local video file.', { acceptedResult, acceptParameters })+res.fail({status: HttpStatusCode.FORBIDDEN_403,message: acceptedResult.errorMessage || req.t('Refused local video file')})+return false}diff --git a/server/core/middlewares/validators/videos/video-channels.ts b/server/core/middlewares/validators/videos/video-channels.tsindex 7c7425cbe0..fd76b2869b 100644--- a/server/core/middlewares/validators/videos/video-channels.ts+++ b/server/core/middlewares/validators/videos/video-channels.ts@@ -160,8 +160,8 @@ export const videoChannelImportVideosValidator = [})}- const user = { id: res.locals.videoChannel.Account.userId }- if (!await checkUserQuota({ user, videoFileSize: 1, req, res })) return+ const channelUser = { id: res.locals.videoChannel.Account.userId }+ if (!await checkUserQuota({ channelUser, videoFileSize: 1, req, res })) returnreturn next()}diff --git a/server/core/middlewares/validators/videos/video-ownership-changes.ts b/server/core/middlewares/validators/videos/video-ownership-changes.tsindex 2392fb531f..a32d077bf5 100644--- a/server/core/middlewares/validators/videos/video-ownership-changes.ts+++ b/server/core/middlewares/validators/videos/video-ownership-changes.ts@@ -105,7 +105,7 @@ async function checkCanAccept (video: MVideoWithAllFiles, req: express.Request,if (video.state !== VideoState.WAITING_FOR_LIVE) {res.fail({status: HttpStatusCode.BAD_REQUEST_400,- message: req.t('You can accept an ownership change of a published live.')+ message: req.t('You cannot accept an ownership change of a published live.')})return false@@ -114,9 +114,9 @@ async function checkCanAccept (video: MVideoWithAllFiles, req: express.Request,return true}- const user = res.locals.oauth.token.User+ const channelUser = res.locals.oauth.token.User- if (!await checkUserQuota({ user, videoFileSize: video.getMaxQualityBytes(), req, res })) return false+ if (!await checkUserQuota({ channelUser, videoFileSize: video.getMaxQualityBytes(), req, res })) return falsereturn true}diff --git a/server/core/middlewares/validators/videos/video-source.ts b/server/core/middlewares/validators/videos/video-source.tsindex c14eaa9ba0..47c6d3857f 100644--- a/server/core/middlewares/validators/videos/video-source.ts+++ b/server/core/middlewares/validators/videos/video-source.ts@@ -68,13 +68,13 @@ export const replaceVideoSourceResumableValidator = [export const replaceVideoSourceResumableInitValidator = [async (req: express.Request, res: express.Response, next: express.NextFunction) => {- const user = res.locals.oauth.token.User-if (!await checkCanUpdateVideoFile({ req, res })) returnconst fileMetadata = res.locals.uploadVideoFileResumableMetadataconst files = { videofile: [ fileMetadata ] }- if (await commonVideoFileChecks({ req, res, user, videoFileSize: fileMetadata.size, files }) === false) return+ const channelUser = { id: res.locals.videoAll.VideoChannel.Account.userId }++ if (await commonVideoFileChecks({ req, res, channelUser, videoFileSize: fileMetadata.size, files }) === false) returnreturn next()}diff --git a/server/core/middlewares/validators/videos/video-studio.ts b/server/core/middlewares/validators/videos/video-studio.tsindex 5fa0eec5ac..dbf9d23c2d 100644--- a/server/core/middlewares/validators/videos/video-studio.ts+++ b/server/core/middlewares/validators/videos/video-studio.ts@@ -88,7 +88,8 @@ const videoStudioAddEditionValidator = [// Try to make an approximation of bytes added by the intro/outroconst additionalBytes = await approximateIntroOutroAdditionalSize(video, body.tasks, i => getTaskFileFromReq(files, i).path)- if (await checkUserQuota({ user, videoFileSize: additionalBytes, req, res }) === false) return cleanUpReqFiles(req)+ const channelUser = { id: res.locals.videoAll.VideoChannel.Account.userId }+ if (await checkUserQuota({ channelUser, videoFileSize: additionalBytes, req, res }) === false) return cleanUpReqFiles(req)return next()}diff --git a/server/core/middlewares/validators/videos/videos.ts b/server/core/middlewares/validators/videos/videos.tsindex 1367262374..0fd4da838e 100644--- a/server/core/middlewares/validators/videos/videos.ts+++ b/server/core/middlewares/validators/videos/videos.ts@@ -13,7 +13,7 @@ import { Redis } from '@server/lib/redis.js'import { buildUploadXFile, safeUploadXCleanup } from '@server/lib/uploadx.js'import { VideoChangeOwnershipModel } from '@server/models/video/video-change-ownership.js'import { ExpressPromiseHandler } from '@server/types/express-handler.js'-import { MUserAccountId, MVideoFullLight } from '@server/types/models/index.js'+import { MVideoFullLight } from '@server/types/models/index.js'import express from 'express'import { body, param, query, ValidationChain } from 'express-validator'import {@@ -60,6 +60,7 @@ import {checkCanAccessVideoStaticFiles,checkCanManageVideo,checkCanSeeVideo,+ checkUserQuota,doesChannelIdExist,doesVideoExist,doesVideoFileOfVideoExist,@@ -102,10 +103,9 @@ export const videosAddLegacyValidator = [if (areValidationErrors(req, res)) return cleanUpReqFiles(req)const videoFile: express.VideoLegacyUploadFile = req.files['videofile'][0]- const user = res.locals.oauth.token.Userif (- !await commonVideoChecksPass({ req, res, user, videoFileSize: videoFile.size, files: req.files }) ||+ !await commonVideoChecks({ req, res, videoFileSize: videoFile.size, files: req.files }) ||!isValidPasswordProtectedPrivacy(req, res) ||!await addDurationToVideoFileIfNeeded({ videoFile, res, middlewareName: 'videosAddLegacyValidator' }) ||!await isVideoFileAccepted({ req, res, videoFile, hook: 'filter:api.video.upload.accept.result' })@@ -174,7 +174,6 @@ export const videosAddResumableInitValidator = [.custom(isVideoSourceFilenameValid),async (req: express.Request, res: express.Response, next: express.NextFunction) => {- const user = res.locals.oauth.token.Userconst cleanup = () => cleanUpReqFiles(req)logger.debug('Checking videosAddResumableInitValidator body and headers', {@@ -187,7 +186,7 @@ export const videosAddResumableInitValidator = [const fileMetadata = res.locals.uploadVideoFileResumableMetadataconst files = { videofile: [ fileMetadata ] }- if (!await commonVideoChecksPass({ req, res, user, videoFileSize: fileMetadata.size, files })) return cleanup()+ if (!await commonVideoChecks({ req, res, videoFileSize: fileMetadata.size, files })) return cleanup()if (!isValidPasswordProtectedPrivacy(req, res)) return cleanup()@@ -246,11 +245,10 @@ export const videosUpdateValidator = getCommonVideoEditAttributes().concat([return cleanUpReqFiles(req)}+ const targetChannel = res.locals.videoChannel+// Not the same account as original video channel- if (- res.locals.videoChannel &&- res.locals.videoChannel.accountId !== video.VideoChannel.accountId- ) {+ if (targetChannel && targetChannel.accountId !== video.VideoChannel.accountId) {const ownershipChange = await VideoChangeOwnershipModel.loadPendingByVideo(video.id)if (ownershipChange) {@@ -261,6 +259,12 @@ export const videosUpdateValidator = getCommonVideoEditAttributes().concat([return cleanUpReqFiles(req)}++ // Check quota of the target channel+ const channelUser = { id: targetChannel.Account.userId }+ if (!await checkUserQuota({ channelUser, videoFileSize: video.getMaxQualityBytes(), req, res })) {+ return false+ }}return next()@@ -644,10 +648,9 @@ function areErrorsInScheduleUpdate (req: express.Request, res: express.Response)return false}-async function commonVideoChecksPass (options: {+async function commonVideoChecks (options: {req: express.Requestres: express.Response- user: MUserAccountIdvideoFileSize: numberfiles: express.UploadFilesForCheck}): Promise<boolean> {@@ -660,7 +663,15 @@ async function commonVideoChecksPass (options: {return false}- if (!await commonVideoFileChecks(options)) return false+ if (+ !await commonVideoFileChecks({+ req,+ res,+ channelUser: { id: res.locals.videoChannel.Account.userId },+ videoFileSize: options.videoFileSize,+ files: options.files+ })+ ) return falsereturn true}