From a6a79eae0d8564099b6957e76d7a18528d9ef124 Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Mon, 5 Jul 2021 14:57:03 +0200 Subject: Introduce bulk command --- server/tests/api/server/bulk.ts | 13 ++++---- shared/extra-utils/bulk/bulk.ts | 35 ++++++++++---------- shared/extra-utils/shared/abstract-command.ts | 47 +++++++++++++++++++++++++++ shared/extra-utils/shared/index.ts | 1 + 4 files changed, 72 insertions(+), 24 deletions(-) create mode 100644 shared/extra-utils/shared/abstract-command.ts create mode 100644 shared/extra-utils/shared/index.ts diff --git a/server/tests/api/server/bulk.ts b/server/tests/api/server/bulk.ts index 80fa7fce6..ca98a2eb2 100644 --- a/server/tests/api/server/bulk.ts +++ b/server/tests/api/server/bulk.ts @@ -6,7 +6,7 @@ import { Video, VideoComment } from '@shared/models' import { addVideoCommentReply, addVideoCommentThread, - bulkRemoveCommentsOf, + BulkCommand, cleanupTests, createUser, doubleFollow, @@ -30,6 +30,8 @@ describe('Test bulk actions', function () { let user2AccessToken: string let user3AccessToken: string + let bulkCommand: BulkCommand + before(async function () { this.timeout(30000) @@ -60,6 +62,8 @@ describe('Test bulk actions', function () { } await doubleFollow(servers[0], servers[1]) + + bulkCommand = new BulkCommand(servers[0]) }) describe('Bulk remove comments', function () { @@ -133,8 +137,7 @@ describe('Test bulk actions', function () { it('Should delete comments of an account on my videos', async function () { this.timeout(60000) - await bulkRemoveCommentsOf({ - url: servers[0].url, + await bulkCommand.removeCommentsOf({ token: user1AccessToken, attributes: { accountName: 'user2', @@ -164,9 +167,7 @@ describe('Test bulk actions', function () { it('Should delete comments of an account on the instance', async function () { this.timeout(60000) - await bulkRemoveCommentsOf({ - url: servers[0].url, - token: servers[0].accessToken, + await bulkCommand.removeCommentsOf({ attributes: { accountName: 'user3@localhost:' + servers[1].port, scope: 'instance' diff --git a/shared/extra-utils/bulk/bulk.ts b/shared/extra-utils/bulk/bulk.ts index b6f437b8b..c102383e3 100644 --- a/shared/extra-utils/bulk/bulk.ts +++ b/shared/extra-utils/bulk/bulk.ts @@ -1,25 +1,24 @@ -import { BulkRemoveCommentsOfBody } from "@shared/models/bulk/bulk-remove-comments-of-body.model" -import { makePostBodyRequest } from "../requests/requests" + +import { BulkRemoveCommentsOfBody } from '@shared/models/bulk/bulk-remove-comments-of-body.model' import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' +import { AbstractCommand, CommonCommandOptions } from '../shared' + +class BulkCommand extends AbstractCommand { -function bulkRemoveCommentsOf (options: { - url: string - token: string - attributes: BulkRemoveCommentsOfBody - expectedStatus?: number -}) { - const { url, token, attributes, expectedStatus } = options - const path = '/api/v1/bulk/remove-comments-of' + removeCommentsOf (options: CommonCommandOptions & { + attributes: BulkRemoveCommentsOfBody + }) { + const { attributes } = options - return makePostBodyRequest({ - url, - path, - token, - fields: attributes, - statusCodeExpected: expectedStatus || HttpStatusCode.NO_CONTENT_204 - }) + return this.postBodyRequest({ + ...options, + path: '/api/v1/bulk/remove-comments-of', + fields: attributes, + defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 + }) + } } export { - bulkRemoveCommentsOf + BulkCommand } diff --git a/shared/extra-utils/shared/abstract-command.ts b/shared/extra-utils/shared/abstract-command.ts new file mode 100644 index 000000000..bb06b6bdb --- /dev/null +++ b/shared/extra-utils/shared/abstract-command.ts @@ -0,0 +1,47 @@ +import { HttpStatusCode } from '@shared/core-utils' +import { makePostBodyRequest } from '../requests/requests' +import { ServerInfo } from '../server/servers' + +export interface CommonCommandOptions { + token?: string + expectedStatus?: number +} + +abstract class AbstractCommand { + + private expectedStatus = HttpStatusCode.OK_200 + + constructor ( + protected server: ServerInfo + ) { + + } + + setServer (server: ServerInfo) { + this.server = server + } + + setExpectedStatus (status: HttpStatusCode) { + this.expectedStatus = status + } + + protected postBodyRequest (options: CommonCommandOptions & { + path: string + defaultExpectedStatus: number + fields?: { [ fieldName: string ]: any } + }) { + const { token, fields, expectedStatus, defaultExpectedStatus, path } = options + + return makePostBodyRequest({ + url: this.server.url, + path, + token: token ?? this.server.accessToken, + fields, + statusCodeExpected: expectedStatus ?? this.expectedStatus ?? defaultExpectedStatus + }) + } +} + +export { + AbstractCommand +} diff --git a/shared/extra-utils/shared/index.ts b/shared/extra-utils/shared/index.ts new file mode 100644 index 000000000..e807ab4f7 --- /dev/null +++ b/shared/extra-utils/shared/index.ts @@ -0,0 +1 @@ +export * from './abstract-command' -- cgit v1.2.3 From 329619b3453479f76c049816b7403b86e9d45cb5 Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Mon, 5 Jul 2021 16:37:50 +0200 Subject: Introduce CLI command --- scripts/generate-code-contributors.ts | 4 +- server/tests/cli/create-import-video-file-job.ts | 14 ++-- server/tests/cli/create-transcoding-job.ts | 23 ++----- server/tests/cli/optimize-old-videos.ts | 6 +- server/tests/cli/peertube.ts | 82 ++++++++---------------- server/tests/cli/plugins.ts | 13 ++-- server/tests/cli/print-transcode-command.ts | 7 +- server/tests/cli/prune-storage.ts | 7 +- server/tests/cli/regenerate-thumbnails.ts | 5 +- server/tests/cli/reset-password.ts | 10 ++- server/tests/cli/update-host.ts | 14 ++-- shared/extra-utils/bulk/index.ts | 1 + shared/extra-utils/cli/cli.ts | 33 +++++----- shared/extra-utils/cli/index.ts | 1 + shared/extra-utils/index.ts | 4 +- shared/extra-utils/server/servers.ts | 8 +++ 16 files changed, 94 insertions(+), 138 deletions(-) create mode 100644 shared/extra-utils/bulk/index.ts create mode 100644 shared/extra-utils/cli/index.ts diff --git a/scripts/generate-code-contributors.ts b/scripts/generate-code-contributors.ts index db5af3f91..935ed3c5a 100755 --- a/scripts/generate-code-contributors.ts +++ b/scripts/generate-code-contributors.ts @@ -1,7 +1,7 @@ import { registerTSPaths } from '../server/helpers/register-ts-paths' registerTSPaths() -import { execCLI } from '@shared/extra-utils' +import { CLICommand } from '@shared/extra-utils' run() .then(() => process.exit(0)) @@ -59,7 +59,7 @@ async function run () { } async function getGitContributors () { - const output = await execCLI(`git --no-pager shortlog -sn < /dev/tty | sed 's/^\\s\\+[0-9]\\+\\s\\+//g'`) + const output = await CLICommand.exec(`git --no-pager shortlog -sn < /dev/tty | sed 's/^\\s\\+[0-9]\\+\\s\\+//g'`) return output.split('\n') .filter(l => !!l) diff --git a/server/tests/cli/create-import-video-file-job.ts b/server/tests/cli/create-import-video-file-job.ts index 49758ff56..8a23a94de 100644 --- a/server/tests/cli/create-import-video-file-job.ts +++ b/server/tests/cli/create-import-video-file-job.ts @@ -6,9 +6,7 @@ import { VideoFile } from '@shared/models/videos/video-file.model' import { cleanupTests, doubleFollow, - execCLI, flushAndRunMultipleServers, - getEnvCli, getVideo, getVideosList, ServerInfo, @@ -57,8 +55,8 @@ describe('Test create import video jobs', function () { }) it('Should run a import job on video 1 with a lower resolution', async function () { - const env = getEnvCli(servers[0]) - await execCLI(`${env} npm run create-import-video-file-job -- -v ${video1UUID} -i server/tests/fixtures/video_short-480.webm`) + const command = `npm run create-import-video-file-job -- -v ${video1UUID} -i server/tests/fixtures/video_short-480.webm` + await servers[0].cliCommand.execWithEnv(command) await waitJobs(servers) @@ -77,8 +75,8 @@ describe('Test create import video jobs', function () { }) it('Should run a import job on video 2 with the same resolution and a different extension', async function () { - const env = getEnvCli(servers[1]) - await execCLI(`${env} npm run create-import-video-file-job -- -v ${video2UUID} -i server/tests/fixtures/video_short.ogv`) + const command = `npm run create-import-video-file-job -- -v ${video2UUID} -i server/tests/fixtures/video_short.ogv` + await servers[1].cliCommand.execWithEnv(command) await waitJobs(servers) @@ -99,8 +97,8 @@ describe('Test create import video jobs', function () { }) it('Should run a import job on video 2 with the same resolution and the same extension', async function () { - const env = getEnvCli(servers[0]) - await execCLI(`${env} npm run create-import-video-file-job -- -v ${video1UUID} -i server/tests/fixtures/video_short2.webm`) + const command = `npm run create-import-video-file-job -- -v ${video1UUID} -i server/tests/fixtures/video_short2.webm` + await servers[0].cliCommand.execWithEnv(command) await waitJobs(servers) diff --git a/server/tests/cli/create-transcoding-job.ts b/server/tests/cli/create-transcoding-job.ts index 5bc1687cd..be46dec25 100644 --- a/server/tests/cli/create-transcoding-job.ts +++ b/server/tests/cli/create-transcoding-job.ts @@ -2,13 +2,10 @@ import 'mocha' import * as chai from 'chai' -import { VideoDetails } from '../../../shared/models/videos' import { cleanupTests, doubleFollow, - execCLI, flushAndRunMultipleServers, - getEnvCli, getVideo, getVideosList, ServerInfo, @@ -17,6 +14,7 @@ import { uploadVideo } from '../../../shared/extra-utils' import { waitJobs } from '../../../shared/extra-utils/server/jobs' +import { VideoDetails } from '../../../shared/models/videos' const expect = chai.expect @@ -81,9 +79,7 @@ describe('Test create transcoding jobs', function () { it('Should run a transcoding job on video 2', async function () { this.timeout(60000) - const env = getEnvCli(servers[0]) - await execCLI(`${env} npm run create-transcoding-job -- -v ${videosUUID[1]}`) - + await servers[0].cliCommand.execWithEnv(`npm run create-transcoding-job -- -v ${videosUUID[1]}`) await waitJobs(servers) for (const server of servers) { @@ -123,8 +119,7 @@ describe('Test create transcoding jobs', function () { it('Should run a transcoding job on video 1 with resolution', async function () { this.timeout(60000) - const env = getEnvCli(servers[0]) - await execCLI(`${env} npm run create-transcoding-job -- -v ${videosUUID[0]} -r 480`) + await servers[0].cliCommand.execWithEnv(`npm run create-transcoding-job -- -v ${videosUUID[0]} -r 480`) await waitJobs(servers) @@ -147,8 +142,7 @@ describe('Test create transcoding jobs', function () { it('Should generate an HLS resolution', async function () { this.timeout(120000) - const env = getEnvCli(servers[0]) - await execCLI(`${env} npm run create-transcoding-job -- -v ${videosUUID[2]} --generate-hls -r 480`) + await servers[0].cliCommand.execWithEnv(`npm run create-transcoding-job -- -v ${videosUUID[2]} --generate-hls -r 480`) await waitJobs(servers) @@ -168,8 +162,7 @@ describe('Test create transcoding jobs', function () { it('Should not duplicate an HLS resolution', async function () { this.timeout(120000) - const env = getEnvCli(servers[0]) - await execCLI(`${env} npm run create-transcoding-job -- -v ${videosUUID[2]} --generate-hls -r 480`) + await servers[0].cliCommand.execWithEnv(`npm run create-transcoding-job -- -v ${videosUUID[2]} --generate-hls -r 480`) await waitJobs(servers) @@ -186,8 +179,7 @@ describe('Test create transcoding jobs', function () { it('Should generate all HLS resolutions', async function () { this.timeout(120000) - const env = getEnvCli(servers[0]) - await execCLI(`${env} npm run create-transcoding-job -- -v ${videosUUID[3]} --generate-hls`) + await servers[0].cliCommand.execWithEnv(`npm run create-transcoding-job -- -v ${videosUUID[3]} --generate-hls`) await waitJobs(servers) @@ -209,8 +201,7 @@ describe('Test create transcoding jobs', function () { config.transcoding.hls.enabled = true await updateCustomSubConfig(servers[0].url, servers[0].accessToken, config) - const env = getEnvCli(servers[0]) - await execCLI(`${env} npm run create-transcoding-job -- -v ${videosUUID[4]}`) + await servers[0].cliCommand.execWithEnv(`npm run create-transcoding-job -- -v ${videosUUID[4]}`) await waitJobs(servers) diff --git a/server/tests/cli/optimize-old-videos.ts b/server/tests/cli/optimize-old-videos.ts index 91a1c9cc4..bd15012fe 100644 --- a/server/tests/cli/optimize-old-videos.ts +++ b/server/tests/cli/optimize-old-videos.ts @@ -7,10 +7,8 @@ import { buildServerDirectory, cleanupTests, doubleFollow, - execCLI, flushAndRunMultipleServers, generateHighBitrateVideo, - getEnvCli, getVideo, getVideosList, ServerInfo, @@ -73,9 +71,7 @@ describe('Test optimize old videos', function () { it('Should run optimize script', async function () { this.timeout(200000) - const env = getEnvCli(servers[0]) - await execCLI(`${env} npm run optimize-old-videos`) - + await servers[0].cliCommand.execWithEnv('npm run optimize-old-videos') await waitJobs(servers) for (const server of servers) { diff --git a/server/tests/cli/peertube.ts b/server/tests/cli/peertube.ts index fcf7e2e2e..0a4f54ffa 100644 --- a/server/tests/cli/peertube.ts +++ b/server/tests/cli/peertube.ts @@ -8,11 +8,10 @@ import { areHttpImportTestsDisabled, buildAbsoluteFixturePath, cleanupTests, + CLICommand, createUser, doubleFollow, - execCLI, flushAndRunServer, - getEnvCli, getLocalIdByUUID, getVideo, getVideosList, @@ -30,6 +29,8 @@ describe('Test CLI wrapper', function () { let server: ServerInfo let userAccessToken: string + let cliCommand: CLICommand + const cmd = 'node ./dist/server/tools/peertube.js' before(async function () { @@ -46,6 +47,8 @@ describe('Test CLI wrapper', function () { const args = { name: 'user_channel', displayName: 'User channel', support: 'super support text' } await addVideoChannel(server.url, userAccessToken, args) } + + cliCommand = server.cliCommand }) describe('Authentication and instance selection', function () { @@ -53,46 +56,38 @@ describe('Test CLI wrapper', function () { it('Should display no selected instance', async function () { this.timeout(60000) - const env = getEnvCli(server) - const stdout = await execCLI(`${env} ${cmd} --help`) - + const stdout = await cliCommand.execWithEnv(`${cmd} --help`) expect(stdout).to.contain('no instance selected') }) it('Should add a user', async function () { this.timeout(60000) - const env = getEnvCli(server) - await execCLI(`${env} ${cmd} auth add -u ${server.url} -U user_1 -p super_password`) + await cliCommand.execWithEnv(`${cmd} auth add -u ${server.url} -U user_1 -p super_password`) }) it('Should not fail to add a user if there is a slash at the end of the instance URL', async function () { this.timeout(60000) - const env = getEnvCli(server) - let fullServerURL - fullServerURL = server.url + '/' - await execCLI(`${env} ${cmd} auth add -u ${fullServerURL} -U user_1 -p super_password`) + let fullServerURL = server.url + '/' + + await cliCommand.execWithEnv(`${cmd} auth add -u ${fullServerURL} -U user_1 -p super_password`) fullServerURL = server.url + '/asdfasdf' - await execCLI(`${env} ${cmd} auth add -u ${fullServerURL} -U user_1 -p super_password`) + await cliCommand.execWithEnv(`${cmd} auth add -u ${fullServerURL} -U user_1 -p super_password`) }) it('Should default to this user', async function () { this.timeout(60000) - const env = getEnvCli(server) - const stdout = await execCLI(`${env} ${cmd} --help`) - + const stdout = await cliCommand.execWithEnv(`${cmd} --help`) expect(stdout).to.contain(`instance ${server.url} selected`) }) it('Should remember the user', async function () { this.timeout(60000) - const env = getEnvCli(server) - const stdout = await execCLI(`${env} ${cmd} auth list`) - + const stdout = await cliCommand.execWithEnv(`${cmd} auth list`) expect(stdout).to.contain(server.url) }) }) @@ -102,13 +97,10 @@ describe('Test CLI wrapper', function () { it('Should upload a video', async function () { this.timeout(60000) - const env = getEnvCli(server) - const fixture = buildAbsoluteFixturePath('60fps_720p_small.mp4') - const params = `-f ${fixture} --video-name 'test upload' --channel-name user_channel --support 'support_text'` - await execCLI(`${env} ${cmd} upload ${params}`) + await cliCommand.execWithEnv(`${cmd} upload ${params}`) }) it('Should have the video uploaded', async function () { @@ -130,11 +122,8 @@ describe('Test CLI wrapper', function () { this.timeout(60000) - const env = getEnvCli(server) - const params = `--target-url ${getYoutubeVideoUrl()} --channel-name user_channel` - - await execCLI(`${env} ${cmd} import ${params}`) + await cliCommand.execWithEnv(`${cmd} import ${params}`) }) it('Should have imported the video', async function () { @@ -166,11 +155,8 @@ describe('Test CLI wrapper', function () { this.timeout(60000) - const env = getEnvCli(server) - const params = `--target-url ${getYoutubeVideoUrl()} --channel-name user_channel --video-name toto --nsfw --support support` - - await execCLI(`${env} ${cmd} import ${params}`) + await cliCommand.execWithEnv(`${cmd} import ${params}`) await waitJobs([ server ]) @@ -194,18 +180,14 @@ describe('Test CLI wrapper', function () { describe('Admin auth', function () { it('Should remove the auth user', async function () { - const env = getEnvCli(server) - - await execCLI(`${env} ${cmd} auth del ${server.url}`) - - const stdout = await execCLI(`${env} ${cmd} --help`) + await cliCommand.execWithEnv(`${cmd} auth del ${server.url}`) + const stdout = await cliCommand.execWithEnv(`${cmd} --help`) expect(stdout).to.contain('no instance selected') }) it('Should add the admin user', async function () { - const env = getEnvCli(server) - await execCLI(`${env} ${cmd} auth add -u ${server.url} -U root -p test${server.internalServerNumber}`) + await cliCommand.execWithEnv(`${cmd} auth add -u ${server.url} -U root -p test${server.internalServerNumber}`) }) }) @@ -214,8 +196,7 @@ describe('Test CLI wrapper', function () { it('Should install a plugin', async function () { this.timeout(60000) - const env = getEnvCli(server) - await execCLI(`${env} ${cmd} plugins install --npm-name peertube-plugin-hello-world`) + await cliCommand.execWithEnv(`${cmd} plugins install --npm-name peertube-plugin-hello-world`) }) it('Should have registered settings', async function () { @@ -223,15 +204,13 @@ describe('Test CLI wrapper', function () { }) it('Should list installed plugins', async function () { - const env = getEnvCli(server) - const res = await execCLI(`${env} ${cmd} plugins list`) + const res = await cliCommand.execWithEnv(`${cmd} plugins list`) expect(res).to.contain('peertube-plugin-hello-world') }) it('Should uninstall the plugin', async function () { - const env = getEnvCli(server) - const res = await execCLI(`${env} ${cmd} plugins uninstall --npm-name peertube-plugin-hello-world`) + const res = await cliCommand.execWithEnv(`${cmd} plugins uninstall --npm-name peertube-plugin-hello-world`) expect(res).to.not.contain('peertube-plugin-hello-world') }) @@ -262,11 +241,8 @@ describe('Test CLI wrapper', function () { it('Should add a redundancy', async function () { this.timeout(60000) - const env = getEnvCli(server) - const params = `add --video ${video1Server2}` - - await execCLI(`${env} ${cmd} redundancy ${params}`) + await cliCommand.execWithEnv(`${cmd} redundancy ${params}`) await waitJobs(servers) }) @@ -275,10 +251,8 @@ describe('Test CLI wrapper', function () { this.timeout(60000) { - const env = getEnvCli(server) - const params = 'list-my-redundancies' - const stdout = await execCLI(`${env} ${cmd} redundancy ${params}`) + const stdout = await cliCommand.execWithEnv(`${cmd} redundancy ${params}`) expect(stdout).to.contain('super video') expect(stdout).to.contain(`localhost:${server.port}`) @@ -288,18 +262,14 @@ describe('Test CLI wrapper', function () { it('Should remove a redundancy', async function () { this.timeout(60000) - const env = getEnvCli(server) - const params = `remove --video ${video1Server2}` - - await execCLI(`${env} ${cmd} redundancy ${params}`) + await cliCommand.execWithEnv(`${cmd} redundancy ${params}`) await waitJobs(servers) { - const env = getEnvCli(server) const params = 'list-my-redundancies' - const stdout = await execCLI(`${env} ${cmd} redundancy ${params}`) + const stdout = await cliCommand.execWithEnv(`${cmd} redundancy ${params}`) expect(stdout).to.not.contain('super video') } diff --git a/server/tests/cli/plugins.ts b/server/tests/cli/plugins.ts index 7f19f14b7..efdc20748 100644 --- a/server/tests/cli/plugins.ts +++ b/server/tests/cli/plugins.ts @@ -1,12 +1,11 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ import 'mocha' +import { expect } from 'chai' import { cleanupTests, - execCLI, flushAndRunServer, getConfig, - getEnvCli, getPluginTestPath, killallServers, reRunServer, @@ -14,7 +13,6 @@ import { setAccessTokensToServers } from '../../../shared/extra-utils' import { ServerConfig } from '../../../shared/models/server' -import { expect } from 'chai' describe('Test plugin scripts', function () { let server: ServerInfo @@ -31,15 +29,13 @@ describe('Test plugin scripts', function () { const packagePath = getPluginTestPath() - const env = getEnvCli(server) - await execCLI(`${env} npm run plugin:install -- --plugin-path ${packagePath}`) + await server.cliCommand.execWithEnv(`npm run plugin:install -- --plugin-path ${packagePath}`) }) it('Should install a theme from stateless CLI', async function () { this.timeout(60000) - const env = getEnvCli(server) - await execCLI(`${env} npm run plugin:install -- --npm-name peertube-theme-background-red`) + await server.cliCommand.execWithEnv(`npm run plugin:install -- --npm-name peertube-theme-background-red`) }) it('Should have the theme and the plugin registered when we restart peertube', async function () { @@ -63,8 +59,7 @@ describe('Test plugin scripts', function () { it('Should uninstall a plugin from stateless CLI', async function () { this.timeout(60000) - const env = getEnvCli(server) - await execCLI(`${env} npm run plugin:uninstall -- --npm-name peertube-plugin-test`) + await server.cliCommand.execWithEnv(`npm run plugin:uninstall -- --npm-name peertube-plugin-test`) }) it('Should have removed the plugin on another peertube restart', async function () { diff --git a/server/tests/cli/print-transcode-command.ts b/server/tests/cli/print-transcode-command.ts index 2d7255db7..3a7969e68 100644 --- a/server/tests/cli/print-transcode-command.ts +++ b/server/tests/cli/print-transcode-command.ts @@ -2,14 +2,15 @@ import 'mocha' import * as chai from 'chai' -import { execCLI } from '../../../shared/extra-utils' +import { getVideoFileBitrate, getVideoFileFPS } from '@server/helpers/ffprobe-utils' +import { CLICommand } from '@shared/extra-utils' import { getTargetBitrate, VideoResolution } from '../../../shared/models/videos' import { VIDEO_TRANSCODING_FPS } from '../../initializers/constants' -import { getVideoFileBitrate, getVideoFileFPS } from '@server/helpers/ffprobe-utils' const expect = chai.expect describe('Test create transcoding jobs', function () { + it('Should print the correct command for each resolution', async function () { const fixturePath = 'server/tests/fixtures/video_short.webm' const fps = await getVideoFileFPS(fixturePath) @@ -19,7 +20,7 @@ describe('Test create transcoding jobs', function () { VideoResolution.H_720P, VideoResolution.H_1080P ]) { - const command = await execCLI(`npm run print-transcode-command -- ${fixturePath} -r ${resolution}`) + const command = await CLICommand.exec(`npm run print-transcode-command -- ${fixturePath} -r ${resolution}`) const targetBitrate = Math.min(getTargetBitrate(resolution, fps, VIDEO_TRANSCODING_FPS), bitrate) expect(command).to.includes(`-vf scale=w=-2:h=${resolution}`) diff --git a/server/tests/cli/prune-storage.ts b/server/tests/cli/prune-storage.ts index a0af09de8..81f91105c 100644 --- a/server/tests/cli/prune-storage.ts +++ b/server/tests/cli/prune-storage.ts @@ -9,12 +9,11 @@ import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-code import { buildServerDirectory, cleanupTests, + CLICommand, createVideoPlaylist, doubleFollow, - execCLI, flushAndRunMultipleServers, getAccount, - getEnvCli, killallServers, makeGetRequest, ServerInfo, @@ -193,8 +192,8 @@ describe('Test prune storage scripts', function () { it('Should run prune storage', async function () { this.timeout(30000) - const env = getEnvCli(servers[0]) - await execCLI(`echo y | ${env} npm run prune-storage`) + const env = servers[0].cliCommand.getEnv() + await CLICommand.exec(`echo y | ${env} npm run prune-storage`) }) it('Should have removed files', async function () { diff --git a/server/tests/cli/regenerate-thumbnails.ts b/server/tests/cli/regenerate-thumbnails.ts index 8acb9f263..1b460e9c0 100644 --- a/server/tests/cli/regenerate-thumbnails.ts +++ b/server/tests/cli/regenerate-thumbnails.ts @@ -7,9 +7,7 @@ import { buildServerDirectory, cleanupTests, doubleFollow, - execCLI, flushAndRunMultipleServers, - getEnvCli, getVideo, makeRawRequest, ServerInfo, @@ -91,8 +89,7 @@ describe('Test regenerate thumbnails script', function () { it('Should regenerate local thumbnails from the CLI', async function () { this.timeout(15000) - const env = getEnvCli(servers[0]) - await execCLI(`${env} npm run regenerate-thumbnails`) + await servers[0].cliCommand.execWithEnv(`npm run regenerate-thumbnails`) }) it('Should have generated new thumbnail files', async function () { diff --git a/server/tests/cli/reset-password.ts b/server/tests/cli/reset-password.ts index a84463b33..97a6eae15 100644 --- a/server/tests/cli/reset-password.ts +++ b/server/tests/cli/reset-password.ts @@ -1,16 +1,14 @@ import 'mocha' - +import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' import { cleanupTests, + CLICommand, createUser, - execCLI, flushAndRunServer, - getEnvCli, login, ServerInfo, setAccessTokensToServers } from '../../../shared/extra-utils' -import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' describe('Test reset password scripts', function () { let server: ServerInfo @@ -26,8 +24,8 @@ describe('Test reset password scripts', function () { it('Should change the user password from CLI', async function () { this.timeout(60000) - const env = getEnvCli(server) - await execCLI(`echo coucou | ${env} npm run reset-password -- -u user_1`) + const env = server.cliCommand.getEnv() + await CLICommand.exec(`echo coucou | ${env} npm run reset-password -- -u user_1`) await login(server.url, server.client, { username: 'user_1', password: 'coucou' }, HttpStatusCode.OK_200) }) diff --git a/server/tests/cli/update-host.ts b/server/tests/cli/update-host.ts index 2070f16f5..1b1a76aef 100644 --- a/server/tests/cli/update-host.ts +++ b/server/tests/cli/update-host.ts @@ -2,27 +2,26 @@ import 'mocha' import * as chai from 'chai' -import { VideoDetails } from '../../../shared/models/videos' -import { waitJobs } from '../../../shared/extra-utils/server/jobs' -import { addVideoCommentThread } from '../../../shared/extra-utils/videos/video-comments' import { addVideoChannel, cleanupTests, createUser, - execCLI, flushAndRunServer, - getEnvCli, getVideo, getVideoChannelsList, getVideosList, killallServers, makeActivityPubGetRequest, - parseTorrentVideo, reRunServer, + parseTorrentVideo, + reRunServer, ServerInfo, setAccessTokensToServers, uploadVideo } from '../../../shared/extra-utils' +import { waitJobs } from '../../../shared/extra-utils/server/jobs' import { getAccountsList } from '../../../shared/extra-utils/users/accounts' +import { addVideoCommentThread } from '../../../shared/extra-utils/videos/video-comments' +import { VideoDetails } from '../../../shared/models/videos' const expect = chai.expect @@ -72,8 +71,7 @@ describe('Test update host scripts', function () { // Run server with standard configuration await reRunServer(server) - const env = getEnvCli(server) - await execCLI(`${env} npm run update-host`) + await server.cliCommand.execWithEnv(`npm run update-host`) }) it('Should have updated videos url', async function () { diff --git a/shared/extra-utils/bulk/index.ts b/shared/extra-utils/bulk/index.ts new file mode 100644 index 000000000..5d2f9d3ad --- /dev/null +++ b/shared/extra-utils/bulk/index.ts @@ -0,0 +1 @@ +export * from './bulk' diff --git a/shared/extra-utils/cli/cli.ts b/shared/extra-utils/cli/cli.ts index c62e170bb..1bf100869 100644 --- a/shared/extra-utils/cli/cli.ts +++ b/shared/extra-utils/cli/cli.ts @@ -1,24 +1,27 @@ import { exec } from 'child_process' +import { AbstractCommand } from '../shared' -import { ServerInfo } from '../server/servers' +class CLICommand extends AbstractCommand { -function getEnvCli (server?: ServerInfo) { - return `NODE_ENV=test NODE_APP_INSTANCE=${server.internalServerNumber}` -} - -async function execCLI (command: string) { - return new Promise((res, rej) => { - exec(command, (err, stdout, stderr) => { - if (err) return rej(err) + static exec (command: string) { + return new Promise((res, rej) => { + exec(command, (err, stdout, _stderr) => { + if (err) return rej(err) - return res(stdout) + return res(stdout) + }) }) - }) -} + } -// --------------------------------------------------------------------------- + getEnv () { + return `NODE_ENV=test NODE_APP_INSTANCE=${this.server.internalServerNumber}` + } + + async execWithEnv (command: string) { + return CLICommand.exec(`${this.getEnv()} ${command}`) + } +} export { - execCLI, - getEnvCli + CLICommand } diff --git a/shared/extra-utils/cli/index.ts b/shared/extra-utils/cli/index.ts new file mode 100644 index 000000000..8a3f31e2f --- /dev/null +++ b/shared/extra-utils/cli/index.ts @@ -0,0 +1 @@ +export * from './cli' diff --git a/shared/extra-utils/index.ts b/shared/extra-utils/index.ts index 87ee8abba..4bf057492 100644 --- a/shared/extra-utils/index.ts +++ b/shared/extra-utils/index.ts @@ -1,6 +1,6 @@ -export * from './bulk/bulk' +export * from './bulk' -export * from './cli/cli' +export * from './cli' export * from './custom-pages/custom-pages' diff --git a/shared/extra-utils/server/servers.ts b/shared/extra-utils/server/servers.ts index 28e431e94..1b0775421 100644 --- a/shared/extra-utils/server/servers.ts +++ b/shared/extra-utils/server/servers.ts @@ -6,6 +6,8 @@ import { copy, ensureDir, pathExists, readdir, readFile, remove } from 'fs-extra import { join } from 'path' import { randomInt } from '../../core-utils/miscs/miscs' import { VideoChannel } from '../../models/videos' +import { BulkCommand } from '../bulk' +import { CLICommand } from '../cli' import { buildServerDirectory, getFileSize, isGithubCI, root, wait } from '../miscs/miscs' import { makeGetRequest } from '../requests/requests' @@ -60,6 +62,9 @@ interface ServerInfo { } videos?: { id: number, uuid: string }[] + + bulkCommand?: BulkCommand + cliCommand?: CLICommand } function parallelTests () { @@ -265,6 +270,9 @@ async function runServer (server: ServerInfo, configOverrideArg?: any, args = [] } catch { /* empty */ } }) + server.bulkCommand = new BulkCommand(server) + server.cliCommand = new CLICommand(server) + res(server) }) }) -- cgit v1.2.3 From e8bd7ce7ccafe3e064b03978e9b512c1a4cc99e6 Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Tue, 6 Jul 2021 09:55:05 +0200 Subject: Introduce CustomPage command --- server/tests/api/server/homepage.ts | 25 +++++++------ shared/extra-utils/bulk/bulk.ts | 10 ++---- shared/extra-utils/cli/cli.ts | 6 +--- shared/extra-utils/custom-pages/custom-pages.ts | 47 ++++++++++++------------- shared/extra-utils/custom-pages/index.ts | 1 + shared/extra-utils/index.ts | 2 +- shared/extra-utils/requests/requests.ts | 5 +++ shared/extra-utils/server/servers.ts | 3 ++ shared/extra-utils/shared/abstract-command.ts | 44 ++++++++++++++++++----- 9 files changed, 85 insertions(+), 58 deletions(-) create mode 100644 shared/extra-utils/custom-pages/index.ts diff --git a/server/tests/api/server/homepage.ts b/server/tests/api/server/homepage.ts index e8ba89ca6..4a3ec0479 100644 --- a/server/tests/api/server/homepage.ts +++ b/server/tests/api/server/homepage.ts @@ -3,17 +3,16 @@ import 'mocha' import * as chai from 'chai' import { HttpStatusCode } from '@shared/core-utils' -import { CustomPage, ServerConfig } from '@shared/models' +import { ServerConfig } from '@shared/models' import { cleanupTests, + CustomPagesCommand, flushAndRunServer, getConfig, - getInstanceHomepage, killallServers, reRunServer, ServerInfo, - setAccessTokensToServers, - updateInstanceHomepage + setAccessTokensToServers } from '../../../../shared/extra-utils/index' const expect = chai.expect @@ -27,26 +26,28 @@ async function getHomepageState (server: ServerInfo) { describe('Test instance homepage actions', function () { let server: ServerInfo + let command: CustomPagesCommand before(async function () { this.timeout(30000) server = await flushAndRunServer(1) await setAccessTokensToServers([ server ]) + + command = server.customPageCommand }) it('Should not have a homepage', async function () { const state = await getHomepageState(server) expect(state).to.be.false - await getInstanceHomepage(server.url, HttpStatusCode.NOT_FOUND_404) + await command.getInstanceHomepage({ expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) it('Should set a homepage', async function () { - await updateInstanceHomepage(server.url, server.accessToken, '') + await command.updateInstanceHomepage({ content: '' }) - const res = await getInstanceHomepage(server.url) - const page: CustomPage = res.body + const page = await command.getInstanceHomepage() expect(page.content).to.equal('') const state = await getHomepageState(server) @@ -60,8 +61,7 @@ describe('Test instance homepage actions', function () { await reRunServer(server) - const res = await getInstanceHomepage(server.url) - const page: CustomPage = res.body + const page = await command.getInstanceHomepage() expect(page.content).to.equal('') const state = await getHomepageState(server) @@ -69,10 +69,9 @@ describe('Test instance homepage actions', function () { }) it('Should empty the homepage', async function () { - await updateInstanceHomepage(server.url, server.accessToken, '') + await command.updateInstanceHomepage({ content: '' }) - const res = await getInstanceHomepage(server.url) - const page: CustomPage = res.body + const page = await command.getInstanceHomepage() expect(page.content).to.be.empty const state = await getHomepageState(server) diff --git a/shared/extra-utils/bulk/bulk.ts b/shared/extra-utils/bulk/bulk.ts index c102383e3..a58fb3fbb 100644 --- a/shared/extra-utils/bulk/bulk.ts +++ b/shared/extra-utils/bulk/bulk.ts @@ -1,11 +1,11 @@ import { BulkRemoveCommentsOfBody } from '@shared/models/bulk/bulk-remove-comments-of-body.model' import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' -import { AbstractCommand, CommonCommandOptions } from '../shared' +import { AbstractCommand, OverrideCommandOptions } from '../shared' -class BulkCommand extends AbstractCommand { +export class BulkCommand extends AbstractCommand { - removeCommentsOf (options: CommonCommandOptions & { + removeCommentsOf (options: OverrideCommandOptions & { attributes: BulkRemoveCommentsOfBody }) { const { attributes } = options @@ -18,7 +18,3 @@ class BulkCommand extends AbstractCommand { }) } } - -export { - BulkCommand -} diff --git a/shared/extra-utils/cli/cli.ts b/shared/extra-utils/cli/cli.ts index 1bf100869..bc1dddc68 100644 --- a/shared/extra-utils/cli/cli.ts +++ b/shared/extra-utils/cli/cli.ts @@ -1,7 +1,7 @@ import { exec } from 'child_process' import { AbstractCommand } from '../shared' -class CLICommand extends AbstractCommand { +export class CLICommand extends AbstractCommand { static exec (command: string) { return new Promise((res, rej) => { @@ -21,7 +21,3 @@ class CLICommand extends AbstractCommand { return CLICommand.exec(`${this.getEnv()} ${command}`) } } - -export { - CLICommand -} diff --git a/shared/extra-utils/custom-pages/custom-pages.ts b/shared/extra-utils/custom-pages/custom-pages.ts index bf2d16c70..56dabdc0f 100644 --- a/shared/extra-utils/custom-pages/custom-pages.ts +++ b/shared/extra-utils/custom-pages/custom-pages.ts @@ -1,31 +1,30 @@ +import { CustomPage } from '@shared/models' import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' -import { makeGetRequest, makePutBodyRequest } from '../requests/requests' +import { AbstractCommand, OverrideCommandOptions } from '../shared' -function getInstanceHomepage (url: string, statusCodeExpected = HttpStatusCode.OK_200) { - const path = '/api/v1/custom-pages/homepage/instance' +export class CustomPagesCommand extends AbstractCommand { - return makeGetRequest({ - url, - path, - statusCodeExpected - }) -} - -function updateInstanceHomepage (url: string, token: string, content: string) { - const path = '/api/v1/custom-pages/homepage/instance' + getInstanceHomepage (options: OverrideCommandOptions = {}) { + const path = '/api/v1/custom-pages/homepage/instance' - return makePutBodyRequest({ - url, - path, - token, - fields: { content }, - statusCodeExpected: HttpStatusCode.NO_CONTENT_204 - }) -} + return this.getRequestBody({ + ...options, + path, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } -// --------------------------------------------------------------------------- + updateInstanceHomepage (options: OverrideCommandOptions & { + content: string + }) { + const { content } = options + const path = '/api/v1/custom-pages/homepage/instance' -export { - getInstanceHomepage, - updateInstanceHomepage + return this.putBodyRequest({ + ...options, + path, + fields: { content }, + defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 + }) + } } diff --git a/shared/extra-utils/custom-pages/index.ts b/shared/extra-utils/custom-pages/index.ts new file mode 100644 index 000000000..5e70778f8 --- /dev/null +++ b/shared/extra-utils/custom-pages/index.ts @@ -0,0 +1 @@ +export * from './custom-pages' diff --git a/shared/extra-utils/index.ts b/shared/extra-utils/index.ts index 4bf057492..10781d049 100644 --- a/shared/extra-utils/index.ts +++ b/shared/extra-utils/index.ts @@ -2,7 +2,7 @@ export * from './bulk' export * from './cli' -export * from './custom-pages/custom-pages' +export * from './custom-pages' export * from './feeds/feeds' diff --git a/shared/extra-utils/requests/requests.ts b/shared/extra-utils/requests/requests.ts index 38e24d897..eb59ca600 100644 --- a/shared/extra-utils/requests/requests.ts +++ b/shared/extra-utils/requests/requests.ts @@ -182,6 +182,10 @@ function decodeQueryString (path: string) { return decode(path.split('?')[1]) } +function unwrap (test: request.Test): Promise { + return test.then(res => res.body) +} + // --------------------------------------------------------------------------- export { @@ -194,5 +198,6 @@ export { makePutBodyRequest, makeDeleteRequest, makeRawRequest, + unwrap, updateImageRequest } diff --git a/shared/extra-utils/server/servers.ts b/shared/extra-utils/server/servers.ts index 1b0775421..e07926065 100644 --- a/shared/extra-utils/server/servers.ts +++ b/shared/extra-utils/server/servers.ts @@ -8,6 +8,7 @@ import { randomInt } from '../../core-utils/miscs/miscs' import { VideoChannel } from '../../models/videos' import { BulkCommand } from '../bulk' import { CLICommand } from '../cli' +import { CustomPagesCommand } from '../custom-pages' import { buildServerDirectory, getFileSize, isGithubCI, root, wait } from '../miscs/miscs' import { makeGetRequest } from '../requests/requests' @@ -65,6 +66,7 @@ interface ServerInfo { bulkCommand?: BulkCommand cliCommand?: CLICommand + customPageCommand?: CustomPagesCommand } function parallelTests () { @@ -272,6 +274,7 @@ async function runServer (server: ServerInfo, configOverrideArg?: any, args = [] server.bulkCommand = new BulkCommand(server) server.cliCommand = new CLICommand(server) + server.customPageCommand = new CustomPagesCommand(server) res(server) }) diff --git a/shared/extra-utils/shared/abstract-command.ts b/shared/extra-utils/shared/abstract-command.ts index bb06b6bdb..d8eba373d 100644 --- a/shared/extra-utils/shared/abstract-command.ts +++ b/shared/extra-utils/shared/abstract-command.ts @@ -1,15 +1,20 @@ import { HttpStatusCode } from '@shared/core-utils' -import { makePostBodyRequest } from '../requests/requests' +import { makeGetRequest, makePostBodyRequest, makePutBodyRequest, unwrap } from '../requests/requests' import { ServerInfo } from '../server/servers' -export interface CommonCommandOptions { +export interface OverrideCommandOptions { token?: string expectedStatus?: number } +interface CommonCommandOptions extends OverrideCommandOptions { + path: string + defaultExpectedStatus: number +} + abstract class AbstractCommand { - private expectedStatus = HttpStatusCode.OK_200 + private expectedStatus: HttpStatusCode constructor ( protected server: ServerInfo @@ -25,20 +30,43 @@ abstract class AbstractCommand { this.expectedStatus = status } + protected getRequestBody (options: CommonCommandOptions) { + return unwrap(makeGetRequest(this.buildCommonRequestOptions(options))) + } + + protected putBodyRequest (options: CommonCommandOptions & { + fields?: { [ fieldName: string ]: any } + }) { + const { fields } = options + + return makePutBodyRequest({ + ...this.buildCommonRequestOptions(options), + + fields + }) + } + protected postBodyRequest (options: CommonCommandOptions & { - path: string - defaultExpectedStatus: number fields?: { [ fieldName: string ]: any } }) { - const { token, fields, expectedStatus, defaultExpectedStatus, path } = options + const { fields } = options return makePostBodyRequest({ + ...this.buildCommonRequestOptions(options), + + fields + }) + } + + private buildCommonRequestOptions (options: CommonCommandOptions) { + const { token, expectedStatus, defaultExpectedStatus, path } = options + + return { url: this.server.url, path, token: token ?? this.server.accessToken, - fields, statusCodeExpected: expectedStatus ?? this.expectedStatus ?? defaultExpectedStatus - }) + } } } -- cgit v1.2.3 From c1bc8ee4783d6ce3102524e6c2a02b2f0f6aab6d Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Tue, 6 Jul 2021 10:21:35 +0200 Subject: Introduce feed command --- server/tests/feeds/feeds.ts | 122 +++++++++++++------------- shared/extra-utils/feeds/feeds.ts | 55 +++++++----- shared/extra-utils/feeds/index.ts | 1 + shared/extra-utils/requests/requests.ts | 9 +- shared/extra-utils/server/servers.ts | 3 + shared/extra-utils/shared/abstract-command.ts | 28 +++++- 6 files changed, 128 insertions(+), 90 deletions(-) create mode 100644 shared/extra-utils/feeds/index.ts diff --git a/server/tests/feeds/feeds.ts b/server/tests/feeds/feeds.ts index 7bad81751..4d29a2e39 100644 --- a/server/tests/feeds/feeds.ts +++ b/server/tests/feeds/feeds.ts @@ -11,16 +11,15 @@ import { import { addUserSubscription, listUserSubscriptionVideos } from '@shared/extra-utils/users/user-subscriptions' import { VideoPrivacy } from '@shared/models' import { ScopedToken } from '@shared/models/users/user-scoped-token' +import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' import { cleanupTests, createUser, doubleFollow, flushAndRunMultipleServers, flushAndRunServer, - getJSONfeed, getMyUserInformation, getUserScopedTokens, - getXMLfeed, renewUserScopedTokens, ServerInfo, setAccessTokensToServers, @@ -31,7 +30,6 @@ import { import { waitJobs } from '../../../shared/extra-utils/server/jobs' import { addVideoCommentThread } from '../../../shared/extra-utils/videos/video-comments' import { User } from '../../../shared/models/users' -import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' chai.use(require('chai-xml')) chai.use(require('chai-json-schema')) @@ -118,18 +116,18 @@ describe('Test syndication feeds', () => { it('Should be well formed XML (covers RSS 2.0 and ATOM 1.0 endpoints)', async function () { for (const feed of [ 'video-comments' as 'video-comments', 'videos' as 'videos' ]) { - const rss = await getXMLfeed(servers[0].url, feed) - expect(rss.text).xml.to.be.valid() + const rss = await servers[0].feedCommand.getXML({ feed }) + expect(rss).xml.to.be.valid() - const atom = await getXMLfeed(servers[0].url, feed, 'atom') - expect(atom.text).xml.to.be.valid() + const atom = await servers[0].feedCommand.getXML({ feed, format: 'atom' }) + expect(atom).xml.to.be.valid() } }) it('Should be well formed JSON (covers JSON feed 1.0 endpoint)', async function () { for (const feed of [ 'video-comments' as 'video-comments', 'videos' as 'videos' ]) { - const json = await getJSONfeed(servers[0].url, feed) - expect(JSON.parse(json.text)).to.be.jsonSchema({ type: 'object' }) + const jsonText = await servers[0].feedCommand.getJSON({ feed }) + expect(JSON.parse(jsonText)).to.be.jsonSchema({ type: 'object' }) } }) }) @@ -138,10 +136,10 @@ describe('Test syndication feeds', () => { it('Should contain a valid enclosure (covers RSS 2.0 endpoint)', async function () { for (const server of servers) { - const rss = await getXMLfeed(server.url, 'videos') - expect(xmlParser.validate(rss.text)).to.be.true + const rss = await server.feedCommand.getXML({ feed: 'videos' }) + expect(xmlParser.validate(rss)).to.be.true - const xmlDoc = xmlParser.parse(rss.text, { parseAttributeValue: true, ignoreAttributes: false }) + const xmlDoc = xmlParser.parse(rss, { parseAttributeValue: true, ignoreAttributes: false }) const enclosure = xmlDoc.rss.channel.item[0].enclosure expect(enclosure).to.exist @@ -153,8 +151,8 @@ describe('Test syndication feeds', () => { it('Should contain a valid \'attachments\' object (covers JSON feed 1.0 endpoint)', async function () { for (const server of servers) { - const json = await getJSONfeed(server.url, 'videos') - const jsonObj = JSON.parse(json.text) + const json = await server.feedCommand.getJSON({ feed: 'videos' }) + const jsonObj = JSON.parse(json) expect(jsonObj.items.length).to.be.equal(2) expect(jsonObj.items[0].attachments).to.exist expect(jsonObj.items[0].attachments.length).to.be.eq(1) @@ -166,16 +164,16 @@ describe('Test syndication feeds', () => { it('Should filter by account', async function () { { - const json = await getJSONfeed(servers[0].url, 'videos', { accountId: rootAccountId }) - const jsonObj = JSON.parse(json.text) + const json = await servers[0].feedCommand.getJSON({ feed: 'videos', query: { accountId: rootAccountId } }) + const jsonObj = JSON.parse(json) expect(jsonObj.items.length).to.be.equal(1) expect(jsonObj.items[0].title).to.equal('my super name for server 1') expect(jsonObj.items[0].author.name).to.equal('root') } { - const json = await getJSONfeed(servers[0].url, 'videos', { accountId: userAccountId }) - const jsonObj = JSON.parse(json.text) + const json = await servers[0].feedCommand.getJSON({ feed: 'videos', query: { accountId: userAccountId } }) + const jsonObj = JSON.parse(json) expect(jsonObj.items.length).to.be.equal(1) expect(jsonObj.items[0].title).to.equal('user video') expect(jsonObj.items[0].author.name).to.equal('john') @@ -183,15 +181,15 @@ describe('Test syndication feeds', () => { for (const server of servers) { { - const json = await getJSONfeed(server.url, 'videos', { accountName: 'root@localhost:' + servers[0].port }) - const jsonObj = JSON.parse(json.text) + const json = await server.feedCommand.getJSON({ feed: 'videos', query: { accountName: 'root@localhost:' + servers[0].port } }) + const jsonObj = JSON.parse(json) expect(jsonObj.items.length).to.be.equal(1) expect(jsonObj.items[0].title).to.equal('my super name for server 1') } { - const json = await getJSONfeed(server.url, 'videos', { accountName: 'john@localhost:' + servers[0].port }) - const jsonObj = JSON.parse(json.text) + const json = await server.feedCommand.getJSON({ feed: 'videos', query: { accountName: 'john@localhost:' + servers[0].port } }) + const jsonObj = JSON.parse(json) expect(jsonObj.items.length).to.be.equal(1) expect(jsonObj.items[0].title).to.equal('user video') } @@ -200,16 +198,16 @@ describe('Test syndication feeds', () => { it('Should filter by video channel', async function () { { - const json = await getJSONfeed(servers[0].url, 'videos', { videoChannelId: rootChannelId }) - const jsonObj = JSON.parse(json.text) + const json = await servers[0].feedCommand.getJSON({ feed: 'videos', query: { videoChannelId: rootChannelId } }) + const jsonObj = JSON.parse(json) expect(jsonObj.items.length).to.be.equal(1) expect(jsonObj.items[0].title).to.equal('my super name for server 1') expect(jsonObj.items[0].author.name).to.equal('root') } { - const json = await getJSONfeed(servers[0].url, 'videos', { videoChannelId: userChannelId }) - const jsonObj = JSON.parse(json.text) + const json = await servers[0].feedCommand.getJSON({ feed: 'videos', query: { videoChannelId: userChannelId } }) + const jsonObj = JSON.parse(json) expect(jsonObj.items.length).to.be.equal(1) expect(jsonObj.items[0].title).to.equal('user video') expect(jsonObj.items[0].author.name).to.equal('john') @@ -217,15 +215,17 @@ describe('Test syndication feeds', () => { for (const server of servers) { { - const json = await getJSONfeed(server.url, 'videos', { videoChannelName: 'root_channel@localhost:' + servers[0].port }) - const jsonObj = JSON.parse(json.text) + const query = { videoChannelName: 'root_channel@localhost:' + servers[0].port } + const json = await server.feedCommand.getJSON({ feed: 'videos', query }) + const jsonObj = JSON.parse(json) expect(jsonObj.items.length).to.be.equal(1) expect(jsonObj.items[0].title).to.equal('my super name for server 1') } { - const json = await getJSONfeed(server.url, 'videos', { videoChannelName: 'john_channel@localhost:' + servers[0].port }) - const jsonObj = JSON.parse(json.text) + const query = { videoChannelName: 'john_channel@localhost:' + servers[0].port } + const json = await server.feedCommand.getJSON({ feed: 'videos', query }) + const jsonObj = JSON.parse(json) expect(jsonObj.items.length).to.be.equal(1) expect(jsonObj.items[0].title).to.equal('user video') } @@ -239,8 +239,8 @@ describe('Test syndication feeds', () => { await waitJobs([ serverHLSOnly ]) - const json = await getJSONfeed(serverHLSOnly.url, 'videos') - const jsonObj = JSON.parse(json.text) + const json = await serverHLSOnly.feedCommand.getJSON({ feed: 'videos' }) + const jsonObj = JSON.parse(json) expect(jsonObj.items.length).to.be.equal(1) expect(jsonObj.items[0].attachments).to.exist expect(jsonObj.items[0].attachments.length).to.be.eq(4) @@ -257,9 +257,9 @@ describe('Test syndication feeds', () => { it('Should contain valid comments (covers JSON feed 1.0 endpoint) and not from unlisted videos', async function () { for (const server of servers) { - const json = await getJSONfeed(server.url, 'video-comments') + const json = await server.feedCommand.getJSON({ feed: 'video-comments' }) - const jsonObj = JSON.parse(json.text) + const jsonObj = JSON.parse(json) expect(jsonObj.items.length).to.be.equal(2) expect(jsonObj.items[0].html_content).to.equal('super comment 2') expect(jsonObj.items[1].html_content).to.equal('super comment 1') @@ -274,8 +274,8 @@ describe('Test syndication feeds', () => { await addAccountToServerBlocklist(servers[1].url, servers[1].accessToken, remoteHandle) { - const json = await getJSONfeed(servers[1].url, 'video-comments', { version: 2 }) - const jsonObj = JSON.parse(json.text) + const json = await servers[1].feedCommand.getJSON({ feed: 'video-comments', query: { version: 2 } }) + const jsonObj = JSON.parse(json) expect(jsonObj.items.length).to.be.equal(0) } @@ -287,16 +287,16 @@ describe('Test syndication feeds', () => { await addVideoCommentThread(servers[0].url, servers[0].accessToken, videoUUID, 'super comment') await waitJobs(servers) - const json = await getJSONfeed(servers[1].url, 'video-comments', { version: 3 }) - const jsonObj = JSON.parse(json.text) + const json = await servers[1].feedCommand.getJSON({ feed: 'video-comments', query: { version: 3 } }) + const jsonObj = JSON.parse(json) expect(jsonObj.items.length).to.be.equal(3) } await addAccountToAccountBlocklist(servers[1].url, servers[1].accessToken, remoteHandle) { - const json = await getJSONfeed(servers[1].url, 'video-comments', { version: 4 }) - const jsonObj = JSON.parse(json.text) + const json = await servers[1].feedCommand.getJSON({ feed: 'video-comments', query: { version: 4 } }) + const jsonObj = JSON.parse(json) expect(jsonObj.items.length).to.be.equal(2) } }) @@ -327,31 +327,30 @@ describe('Test syndication feeds', () => { const res = await listUserSubscriptionVideos(servers[0].url, feeduserAccessToken) expect(res.body.total).to.equal(0) - const json = await getJSONfeed(servers[0].url, 'subscriptions', { accountId: feeduserAccountId, token: feeduserFeedToken }) - const jsonObj = JSON.parse(json.text) + const query = { accountId: feeduserAccountId, token: feeduserFeedToken } + const json = await servers[0].feedCommand.getJSON({ feed: 'subscriptions', query }) + const jsonObj = JSON.parse(json) expect(jsonObj.items.length).to.be.equal(0) // no subscription, it should not list the instance's videos but list 0 videos } }) it('Should fail with an invalid token', async function () { - await getJSONfeed(servers[0].url, 'subscriptions', { accountId: feeduserAccountId, token: 'toto' }, HttpStatusCode.FORBIDDEN_403) + const query = { accountId: feeduserAccountId, token: 'toto' } + await servers[0].feedCommand.getJSON({ feed: 'subscriptions', query, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) it('Should fail with a token of another user', async function () { - await getJSONfeed( - servers[0].url, - 'subscriptions', - { accountId: feeduserAccountId, token: userFeedToken }, - HttpStatusCode.FORBIDDEN_403 - ) + const query = { accountId: feeduserAccountId, token: userFeedToken } + await servers[0].feedCommand.getJSON({ feed: 'subscriptions', query, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) it('Should list no videos for a user with videos but no subscriptions', async function () { const res = await listUserSubscriptionVideos(servers[0].url, userAccessToken) expect(res.body.total).to.equal(0) - const json = await getJSONfeed(servers[0].url, 'subscriptions', { accountId: userAccountId, token: userFeedToken }) - const jsonObj = JSON.parse(json.text) + const query = { accountId: userAccountId, token: userFeedToken } + const json = await servers[0].feedCommand.getJSON({ feed: 'subscriptions', query }) + const jsonObj = JSON.parse(json) expect(jsonObj.items.length).to.be.equal(0) // no subscription, it should not list the instance's videos but list 0 videos }) @@ -366,8 +365,9 @@ describe('Test syndication feeds', () => { expect(res.body.total).to.equal(1) expect(res.body.data[0].name).to.equal('user video') - const json = await getJSONfeed(servers[0].url, 'subscriptions', { accountId: userAccountId, token: userFeedToken, version: 1 }) - const jsonObj = JSON.parse(json.text) + const query = { accountId: userAccountId, token: userFeedToken, version: 1 } + const json = await servers[0].feedCommand.getJSON({ feed: 'subscriptions', query }) + const jsonObj = JSON.parse(json) expect(jsonObj.items.length).to.be.equal(1) // subscribed to self, it should not list the instance's videos but list john's } }) @@ -382,8 +382,9 @@ describe('Test syndication feeds', () => { const res = await listUserSubscriptionVideos(servers[0].url, userAccessToken) expect(res.body.total).to.equal(2, "there should be 2 videos part of the subscription") - const json = await getJSONfeed(servers[0].url, 'subscriptions', { accountId: userAccountId, token: userFeedToken, version: 2 }) - const jsonObj = JSON.parse(json.text) + const query = { accountId: userAccountId, token: userFeedToken, version: 2 } + const json = await servers[0].feedCommand.getJSON({ feed: 'subscriptions', query }) + const jsonObj = JSON.parse(json) expect(jsonObj.items.length).to.be.equal(2) // subscribed to root, it should not list the instance's videos but list root/john's } }) @@ -391,12 +392,8 @@ describe('Test syndication feeds', () => { it('Should renew the token, and so have an invalid old token', async function () { await renewUserScopedTokens(servers[0].url, userAccessToken) - await getJSONfeed( - servers[0].url, - 'subscriptions', - { accountId: userAccountId, token: userFeedToken, version: 3 }, - HttpStatusCode.FORBIDDEN_403 - ) + const query = { accountId: userAccountId, token: userFeedToken, version: 3 } + await servers[0].feedCommand.getJSON({ feed: 'subscriptions', query, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) it('Should succeed with the new token', async function () { @@ -404,7 +401,8 @@ describe('Test syndication feeds', () => { const token: ScopedToken = res2.body userFeedToken = token.feedToken - await getJSONfeed(servers[0].url, 'subscriptions', { accountId: userAccountId, token: userFeedToken, version: 4 }) + const query = { accountId: userAccountId, token: userFeedToken, version: 4 } + await servers[0].feedCommand.getJSON({ feed: 'subscriptions', query }) }) }) diff --git a/shared/extra-utils/feeds/feeds.ts b/shared/extra-utils/feeds/feeds.ts index ce0a98c6d..012ce6cfe 100644 --- a/shared/extra-utils/feeds/feeds.ts +++ b/shared/extra-utils/feeds/feeds.ts @@ -1,33 +1,42 @@ -import * as request from 'supertest' + import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' +import { AbstractCommand, OverrideCommandOptions } from '../shared' type FeedType = 'videos' | 'video-comments' | 'subscriptions' -function getXMLfeed (url: string, feed: FeedType, format?: string) { - const path = '/feeds/' + feed + '.xml' +export class FeedCommand extends AbstractCommand { - return request(url) - .get(path) - .query((format) ? { format: format } : {}) - .set('Accept', 'application/xml') - .expect(HttpStatusCode.OK_200) - .expect('Content-Type', /xml/) -} + getXML (options: OverrideCommandOptions & { + feed: FeedType + format?: string + }) { + const { feed, format } = options + const path = '/feeds/' + feed + '.xml' -function getJSONfeed (url: string, feed: FeedType, query: any = {}, statusCodeExpected = HttpStatusCode.OK_200) { - const path = '/feeds/' + feed + '.json' + return this.getRequestText({ + ...options, - return request(url) - .get(path) - .query(query) - .set('Accept', 'application/json') - .expect(statusCodeExpected) - .expect('Content-Type', /json/) -} + path, + query: format ? { format } : undefined, + accept: 'application/xml', + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } + + getJSON (options: OverrideCommandOptions & { + feed: FeedType + query?: { [ id: string ]: any } + }) { + const { feed, query } = options + const path = '/feeds/' + feed + '.json' -// --------------------------------------------------------------------------- + return this.getRequestText({ + ...options, -export { - getXMLfeed, - getJSONfeed + path, + query, + accept: 'application/json', + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } } diff --git a/shared/extra-utils/feeds/index.ts b/shared/extra-utils/feeds/index.ts new file mode 100644 index 000000000..4634cb163 --- /dev/null +++ b/shared/extra-utils/feeds/index.ts @@ -0,0 +1 @@ +export * from './feeds' diff --git a/shared/extra-utils/requests/requests.ts b/shared/extra-utils/requests/requests.ts index eb59ca600..8c26a3699 100644 --- a/shared/extra-utils/requests/requests.ts +++ b/shared/extra-utils/requests/requests.ts @@ -182,10 +182,14 @@ function decodeQueryString (path: string) { return decode(path.split('?')[1]) } -function unwrap (test: request.Test): Promise { +function unwrapBody (test: request.Test): Promise { return test.then(res => res.body) } +function unwrapText (test: request.Test): Promise { + return test.then(res => res.text) +} + // --------------------------------------------------------------------------- export { @@ -198,6 +202,7 @@ export { makePutBodyRequest, makeDeleteRequest, makeRawRequest, - unwrap, + unwrapBody, + unwrapText, updateImageRequest } diff --git a/shared/extra-utils/server/servers.ts b/shared/extra-utils/server/servers.ts index e07926065..b64c9eec6 100644 --- a/shared/extra-utils/server/servers.ts +++ b/shared/extra-utils/server/servers.ts @@ -9,6 +9,7 @@ import { VideoChannel } from '../../models/videos' import { BulkCommand } from '../bulk' import { CLICommand } from '../cli' import { CustomPagesCommand } from '../custom-pages' +import { FeedCommand } from '../feeds' import { buildServerDirectory, getFileSize, isGithubCI, root, wait } from '../miscs/miscs' import { makeGetRequest } from '../requests/requests' @@ -67,6 +68,7 @@ interface ServerInfo { bulkCommand?: BulkCommand cliCommand?: CLICommand customPageCommand?: CustomPagesCommand + feedCommand?: FeedCommand } function parallelTests () { @@ -275,6 +277,7 @@ async function runServer (server: ServerInfo, configOverrideArg?: any, args = [] server.bulkCommand = new BulkCommand(server) server.cliCommand = new CLICommand(server) server.customPageCommand = new CustomPagesCommand(server) + server.feedCommand = new FeedCommand(server) res(server) }) diff --git a/shared/extra-utils/shared/abstract-command.ts b/shared/extra-utils/shared/abstract-command.ts index d8eba373d..53c644124 100644 --- a/shared/extra-utils/shared/abstract-command.ts +++ b/shared/extra-utils/shared/abstract-command.ts @@ -1,5 +1,5 @@ import { HttpStatusCode } from '@shared/core-utils' -import { makeGetRequest, makePostBodyRequest, makePutBodyRequest, unwrap } from '../requests/requests' +import { makeGetRequest, makePostBodyRequest, makePutBodyRequest, unwrap, unwrapBody, unwrapText } from '../requests/requests' import { ServerInfo } from '../server/servers' export interface OverrideCommandOptions { @@ -12,6 +12,12 @@ interface CommonCommandOptions extends OverrideCommandOptions { defaultExpectedStatus: number } +interface GetCommandOptions extends CommonCommandOptions { + query?: { [ id: string ]: string } + contentType?: string + accept?: string +} + abstract class AbstractCommand { private expectedStatus: HttpStatusCode @@ -30,8 +36,12 @@ abstract class AbstractCommand { this.expectedStatus = status } - protected getRequestBody (options: CommonCommandOptions) { - return unwrap(makeGetRequest(this.buildCommonRequestOptions(options))) + protected getRequestBody (options: GetCommandOptions) { + return unwrapBody(this.getRequest(options)) + } + + protected getRequestText (options: GetCommandOptions) { + return unwrapText(this.getRequest(options)) } protected putBodyRequest (options: CommonCommandOptions & { @@ -68,6 +78,18 @@ abstract class AbstractCommand { statusCodeExpected: expectedStatus ?? this.expectedStatus ?? defaultExpectedStatus } } + + private getRequest (options: GetCommandOptions) { + const { query, contentType, accept } = options + + return makeGetRequest({ + ...this.buildCommonRequestOptions(options), + + query, + contentType, + accept + }) + } } export { -- cgit v1.2.3 From f59545d97a80bf06025bf6343a80d834c7eb237f Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Tue, 6 Jul 2021 10:22:37 +0200 Subject: Rename command files --- shared/extra-utils/bulk/bulk-command.ts | 20 +++++++++++ shared/extra-utils/bulk/bulk.ts | 20 ----------- shared/extra-utils/bulk/index.ts | 2 +- shared/extra-utils/cli/cli-command.ts | 23 ++++++++++++ shared/extra-utils/cli/cli.ts | 23 ------------ shared/extra-utils/cli/index.ts | 2 +- .../custom-pages/custom-pages-command.ts | 30 ++++++++++++++++ shared/extra-utils/custom-pages/custom-pages.ts | 30 ---------------- shared/extra-utils/custom-pages/index.ts | 2 +- shared/extra-utils/feeds/feeds-command.ts | 42 ++++++++++++++++++++++ shared/extra-utils/feeds/feeds.ts | 42 ---------------------- shared/extra-utils/feeds/index.ts | 2 +- shared/extra-utils/index.ts | 2 +- shared/extra-utils/shared/abstract-command.ts | 2 +- 14 files changed, 121 insertions(+), 121 deletions(-) create mode 100644 shared/extra-utils/bulk/bulk-command.ts delete mode 100644 shared/extra-utils/bulk/bulk.ts create mode 100644 shared/extra-utils/cli/cli-command.ts delete mode 100644 shared/extra-utils/cli/cli.ts create mode 100644 shared/extra-utils/custom-pages/custom-pages-command.ts delete mode 100644 shared/extra-utils/custom-pages/custom-pages.ts create mode 100644 shared/extra-utils/feeds/feeds-command.ts delete mode 100644 shared/extra-utils/feeds/feeds.ts diff --git a/shared/extra-utils/bulk/bulk-command.ts b/shared/extra-utils/bulk/bulk-command.ts new file mode 100644 index 000000000..fcbf04164 --- /dev/null +++ b/shared/extra-utils/bulk/bulk-command.ts @@ -0,0 +1,20 @@ + +import { BulkRemoveCommentsOfBody } from '@shared/models/bulk/bulk-remove-comments-of-body.model' +import { HttpStatusCode } from '../../core-utils/miscs/http-error-codes' +import { AbstractCommand, OverrideCommandOptions } from '../shared' + +export class BulkCommand extends AbstractCommand { + + removeCommentsOf (options: OverrideCommandOptions & { + attributes: BulkRemoveCommentsOfBody + }) { + const { attributes } = options + + return this.postBodyRequest({ + ...options, + path: '/api/v1/bulk/remove-comments-of', + fields: attributes, + defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 + }) + } +} diff --git a/shared/extra-utils/bulk/bulk.ts b/shared/extra-utils/bulk/bulk.ts deleted file mode 100644 index a58fb3fbb..000000000 --- a/shared/extra-utils/bulk/bulk.ts +++ /dev/null @@ -1,20 +0,0 @@ - -import { BulkRemoveCommentsOfBody } from '@shared/models/bulk/bulk-remove-comments-of-body.model' -import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' -import { AbstractCommand, OverrideCommandOptions } from '../shared' - -export class BulkCommand extends AbstractCommand { - - removeCommentsOf (options: OverrideCommandOptions & { - attributes: BulkRemoveCommentsOfBody - }) { - const { attributes } = options - - return this.postBodyRequest({ - ...options, - path: '/api/v1/bulk/remove-comments-of', - fields: attributes, - defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 - }) - } -} diff --git a/shared/extra-utils/bulk/index.ts b/shared/extra-utils/bulk/index.ts index 5d2f9d3ad..391597243 100644 --- a/shared/extra-utils/bulk/index.ts +++ b/shared/extra-utils/bulk/index.ts @@ -1 +1 @@ -export * from './bulk' +export * from './bulk-command' diff --git a/shared/extra-utils/cli/cli-command.ts b/shared/extra-utils/cli/cli-command.ts new file mode 100644 index 000000000..bc1dddc68 --- /dev/null +++ b/shared/extra-utils/cli/cli-command.ts @@ -0,0 +1,23 @@ +import { exec } from 'child_process' +import { AbstractCommand } from '../shared' + +export class CLICommand extends AbstractCommand { + + static exec (command: string) { + return new Promise((res, rej) => { + exec(command, (err, stdout, _stderr) => { + if (err) return rej(err) + + return res(stdout) + }) + }) + } + + getEnv () { + return `NODE_ENV=test NODE_APP_INSTANCE=${this.server.internalServerNumber}` + } + + async execWithEnv (command: string) { + return CLICommand.exec(`${this.getEnv()} ${command}`) + } +} diff --git a/shared/extra-utils/cli/cli.ts b/shared/extra-utils/cli/cli.ts deleted file mode 100644 index bc1dddc68..000000000 --- a/shared/extra-utils/cli/cli.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { exec } from 'child_process' -import { AbstractCommand } from '../shared' - -export class CLICommand extends AbstractCommand { - - static exec (command: string) { - return new Promise((res, rej) => { - exec(command, (err, stdout, _stderr) => { - if (err) return rej(err) - - return res(stdout) - }) - }) - } - - getEnv () { - return `NODE_ENV=test NODE_APP_INSTANCE=${this.server.internalServerNumber}` - } - - async execWithEnv (command: string) { - return CLICommand.exec(`${this.getEnv()} ${command}`) - } -} diff --git a/shared/extra-utils/cli/index.ts b/shared/extra-utils/cli/index.ts index 8a3f31e2f..91b5abfbe 100644 --- a/shared/extra-utils/cli/index.ts +++ b/shared/extra-utils/cli/index.ts @@ -1 +1 @@ -export * from './cli' +export * from './cli-command' diff --git a/shared/extra-utils/custom-pages/custom-pages-command.ts b/shared/extra-utils/custom-pages/custom-pages-command.ts new file mode 100644 index 000000000..a062c9774 --- /dev/null +++ b/shared/extra-utils/custom-pages/custom-pages-command.ts @@ -0,0 +1,30 @@ +import { CustomPage } from '@shared/models' +import { HttpStatusCode } from '../../core-utils/miscs/http-error-codes' +import { AbstractCommand, OverrideCommandOptions } from '../shared' + +export class CustomPagesCommand extends AbstractCommand { + + getInstanceHomepage (options: OverrideCommandOptions = {}) { + const path = '/api/v1/custom-pages/homepage/instance' + + return this.getRequestBody({ + ...options, + path, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } + + updateInstanceHomepage (options: OverrideCommandOptions & { + content: string + }) { + const { content } = options + const path = '/api/v1/custom-pages/homepage/instance' + + return this.putBodyRequest({ + ...options, + path, + fields: { content }, + defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 + }) + } +} diff --git a/shared/extra-utils/custom-pages/custom-pages.ts b/shared/extra-utils/custom-pages/custom-pages.ts deleted file mode 100644 index 56dabdc0f..000000000 --- a/shared/extra-utils/custom-pages/custom-pages.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { CustomPage } from '@shared/models' -import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' -import { AbstractCommand, OverrideCommandOptions } from '../shared' - -export class CustomPagesCommand extends AbstractCommand { - - getInstanceHomepage (options: OverrideCommandOptions = {}) { - const path = '/api/v1/custom-pages/homepage/instance' - - return this.getRequestBody({ - ...options, - path, - defaultExpectedStatus: HttpStatusCode.OK_200 - }) - } - - updateInstanceHomepage (options: OverrideCommandOptions & { - content: string - }) { - const { content } = options - const path = '/api/v1/custom-pages/homepage/instance' - - return this.putBodyRequest({ - ...options, - path, - fields: { content }, - defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 - }) - } -} diff --git a/shared/extra-utils/custom-pages/index.ts b/shared/extra-utils/custom-pages/index.ts index 5e70778f8..58aed04f2 100644 --- a/shared/extra-utils/custom-pages/index.ts +++ b/shared/extra-utils/custom-pages/index.ts @@ -1 +1 @@ -export * from './custom-pages' +export * from './custom-pages-command' diff --git a/shared/extra-utils/feeds/feeds-command.ts b/shared/extra-utils/feeds/feeds-command.ts new file mode 100644 index 000000000..8031adf92 --- /dev/null +++ b/shared/extra-utils/feeds/feeds-command.ts @@ -0,0 +1,42 @@ + +import { HttpStatusCode } from '../../core-utils/miscs/http-error-codes' +import { AbstractCommand, OverrideCommandOptions } from '../shared' + +type FeedType = 'videos' | 'video-comments' | 'subscriptions' + +export class FeedCommand extends AbstractCommand { + + getXML (options: OverrideCommandOptions & { + feed: FeedType + format?: string + }) { + const { feed, format } = options + const path = '/feeds/' + feed + '.xml' + + return this.getRequestText({ + ...options, + + path, + query: format ? { format } : undefined, + accept: 'application/xml', + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } + + getJSON (options: OverrideCommandOptions & { + feed: FeedType + query?: { [ id: string ]: any } + }) { + const { feed, query } = options + const path = '/feeds/' + feed + '.json' + + return this.getRequestText({ + ...options, + + path, + query, + accept: 'application/json', + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } +} diff --git a/shared/extra-utils/feeds/feeds.ts b/shared/extra-utils/feeds/feeds.ts deleted file mode 100644 index 012ce6cfe..000000000 --- a/shared/extra-utils/feeds/feeds.ts +++ /dev/null @@ -1,42 +0,0 @@ - -import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' -import { AbstractCommand, OverrideCommandOptions } from '../shared' - -type FeedType = 'videos' | 'video-comments' | 'subscriptions' - -export class FeedCommand extends AbstractCommand { - - getXML (options: OverrideCommandOptions & { - feed: FeedType - format?: string - }) { - const { feed, format } = options - const path = '/feeds/' + feed + '.xml' - - return this.getRequestText({ - ...options, - - path, - query: format ? { format } : undefined, - accept: 'application/xml', - defaultExpectedStatus: HttpStatusCode.OK_200 - }) - } - - getJSON (options: OverrideCommandOptions & { - feed: FeedType - query?: { [ id: string ]: any } - }) { - const { feed, query } = options - const path = '/feeds/' + feed + '.json' - - return this.getRequestText({ - ...options, - - path, - query, - accept: 'application/json', - defaultExpectedStatus: HttpStatusCode.OK_200 - }) - } -} diff --git a/shared/extra-utils/feeds/index.ts b/shared/extra-utils/feeds/index.ts index 4634cb163..662a22b6f 100644 --- a/shared/extra-utils/feeds/index.ts +++ b/shared/extra-utils/feeds/index.ts @@ -1 +1 @@ -export * from './feeds' +export * from './feeds-command' diff --git a/shared/extra-utils/index.ts b/shared/extra-utils/index.ts index 10781d049..c4f0afdc4 100644 --- a/shared/extra-utils/index.ts +++ b/shared/extra-utils/index.ts @@ -4,7 +4,7 @@ export * from './cli' export * from './custom-pages' -export * from './feeds/feeds' +export * from './feeds' export * from './mock-servers/mock-instances-index' diff --git a/shared/extra-utils/shared/abstract-command.ts b/shared/extra-utils/shared/abstract-command.ts index 53c644124..7f812daa8 100644 --- a/shared/extra-utils/shared/abstract-command.ts +++ b/shared/extra-utils/shared/abstract-command.ts @@ -1,5 +1,5 @@ import { HttpStatusCode } from '@shared/core-utils' -import { makeGetRequest, makePostBodyRequest, makePutBodyRequest, unwrap, unwrapBody, unwrapText } from '../requests/requests' +import { makeGetRequest, makePostBodyRequest, makePutBodyRequest, unwrapBody, unwrapText } from '../requests/requests' import { ServerInfo } from '../server/servers' export interface OverrideCommandOptions { -- cgit v1.2.3 From a92ddacb38a4a17e117ca9ed41680a03580fb81d Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Tue, 6 Jul 2021 10:34:29 +0200 Subject: Introduce logs command --- server/tests/api/server/logs.ts | 49 ++++++++++++++------------- shared/extra-utils/index.ts | 2 ++ shared/extra-utils/logs/index.ts | 1 + shared/extra-utils/logs/logs-command.ts | 41 ++++++++++++++++++++++ shared/extra-utils/logs/logs.ts | 32 ----------------- shared/extra-utils/server/servers.ts | 3 ++ shared/extra-utils/shared/abstract-command.ts | 2 +- 7 files changed, 74 insertions(+), 56 deletions(-) create mode 100644 shared/extra-utils/logs/index.ts create mode 100644 shared/extra-utils/logs/logs-command.ts delete mode 100644 shared/extra-utils/logs/logs.ts diff --git a/server/tests/api/server/logs.ts b/server/tests/api/server/logs.ts index bc398ea73..ab83a329f 100644 --- a/server/tests/api/server/logs.ts +++ b/server/tests/api/server/logs.ts @@ -6,25 +6,28 @@ import { cleanupTests, flushAndRunServer, killallServers, + LogsCommand, makePingRequest, reRunServer, ServerInfo, - setAccessTokensToServers -} from '../../../../shared/extra-utils/index' -import { getAuditLogs, getLogs } from '../../../../shared/extra-utils/logs/logs' -import { waitJobs } from '../../../../shared/extra-utils/server/jobs' -import { uploadVideo } from '../../../../shared/extra-utils/videos/videos' + setAccessTokensToServers, + uploadVideo, + waitJobs +} from '@shared/extra-utils' const expect = chai.expect describe('Test logs', function () { let server: ServerInfo + let logsCommand: LogsCommand before(async function () { this.timeout(30000) server = await flushAndRunServer(1) await setAccessTokensToServers([ server ]) + + logsCommand = server.logsCommand }) describe('With the standard log file', function () { @@ -40,8 +43,8 @@ describe('Test logs', function () { await uploadVideo(server.url, server.accessToken, { name: 'video 2' }) await waitJobs([ server ]) - const res = await getLogs(server.url, server.accessToken, now) - const logsString = JSON.stringify(res.body) + const body = await logsCommand.getLogs({ startDate: now }) + const logsString = JSON.stringify(body) expect(logsString.includes('video 1')).to.be.false expect(logsString.includes('video 2')).to.be.true @@ -63,8 +66,8 @@ describe('Test logs', function () { await uploadVideo(server.url, server.accessToken, { name: 'video 5' }) await waitJobs([ server ]) - const res = await getLogs(server.url, server.accessToken, now1, now2) - const logsString = JSON.stringify(res.body) + const body = await logsCommand.getLogs({ startDate: now1, endDate: now2 }) + const logsString = JSON.stringify(body) expect(logsString.includes('video 3')).to.be.false expect(logsString.includes('video 4')).to.be.true @@ -80,15 +83,15 @@ describe('Test logs', function () { await waitJobs([ server ]) { - const res = await getLogs(server.url, server.accessToken, now, undefined, 'info') - const logsString = JSON.stringify(res.body) + const body = await logsCommand.getLogs({ startDate: now, level: 'info' }) + const logsString = JSON.stringify(body) expect(logsString.includes('video 6')).to.be.true } { - const res = await getLogs(server.url, server.accessToken, now, undefined, 'warn') - const logsString = JSON.stringify(res.body) + const body = await logsCommand.getLogs({ startDate: now, level: 'warn' }) + const logsString = JSON.stringify(body) expect(logsString.includes('video 6')).to.be.false } @@ -101,8 +104,8 @@ describe('Test logs', function () { await makePingRequest(server) - const res = await getLogs(server.url, server.accessToken, now, undefined, 'info') - const logsString = JSON.stringify(res.body) + const body = await logsCommand.getLogs({ startDate: now, level: 'info' }) + const logsString = JSON.stringify(body) expect(logsString.includes('/api/v1/ping')).to.be.true }) @@ -118,8 +121,8 @@ describe('Test logs', function () { await makePingRequest(server) - const res = await getLogs(server.url, server.accessToken, now, undefined, 'info') - const logsString = JSON.stringify(res.body) + const body = await logsCommand.getLogs({ startDate: now, level: 'info' }) + const logsString = JSON.stringify(body) expect(logsString.includes('/api/v1/ping')).to.be.false }) @@ -137,15 +140,15 @@ describe('Test logs', function () { await uploadVideo(server.url, server.accessToken, { name: 'video 8' }) await waitJobs([ server ]) - const res = await getAuditLogs(server.url, server.accessToken, now) - const logsString = JSON.stringify(res.body) + const body = await logsCommand.getAuditLogs({ startDate: now }) + const logsString = JSON.stringify(body) expect(logsString.includes('video 7')).to.be.false expect(logsString.includes('video 8')).to.be.true - expect(res.body).to.have.lengthOf(1) + expect(body).to.have.lengthOf(1) - const item = res.body[0] + const item = body[0] const message = JSON.parse(item.message) expect(message.domain).to.equal('videos') @@ -168,8 +171,8 @@ describe('Test logs', function () { await uploadVideo(server.url, server.accessToken, { name: 'video 11' }) await waitJobs([ server ]) - const res = await getAuditLogs(server.url, server.accessToken, now1, now2) - const logsString = JSON.stringify(res.body) + const body = await logsCommand.getAuditLogs({ startDate: now1, endDate: now2 }) + const logsString = JSON.stringify(body) expect(logsString.includes('video 9')).to.be.false expect(logsString.includes('video 10')).to.be.true diff --git a/shared/extra-utils/index.ts b/shared/extra-utils/index.ts index c4f0afdc4..a3d3970af 100644 --- a/shared/extra-utils/index.ts +++ b/shared/extra-utils/index.ts @@ -6,6 +6,8 @@ export * from './custom-pages' export * from './feeds' +export * from './logs' + export * from './mock-servers/mock-instances-index' export * from './miscs/email' diff --git a/shared/extra-utils/logs/index.ts b/shared/extra-utils/logs/index.ts new file mode 100644 index 000000000..69452d7f0 --- /dev/null +++ b/shared/extra-utils/logs/index.ts @@ -0,0 +1 @@ +export * from './logs-command' diff --git a/shared/extra-utils/logs/logs-command.ts b/shared/extra-utils/logs/logs-command.ts new file mode 100644 index 000000000..f7594734d --- /dev/null +++ b/shared/extra-utils/logs/logs-command.ts @@ -0,0 +1,41 @@ +import { HttpStatusCode } from '../../core-utils/miscs/http-error-codes' +import { LogLevel } from '../../models/server/log-level.type' +import { AbstractCommand, OverrideCommandOptions } from '../shared' + +export class LogsCommand extends AbstractCommand { + + getLogs (options: OverrideCommandOptions & { + startDate: Date + endDate?: Date + level?: LogLevel + }) { + const { startDate, endDate, level } = options + const path = '/api/v1/server/logs' + + return this.getRequestBody({ + ...options, + + path, + query: { startDate, endDate, level }, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } + + getAuditLogs (options: OverrideCommandOptions & { + startDate: Date + endDate?: Date + }) { + const { startDate, endDate } = options + + const path = '/api/v1/server/audit-logs' + + return this.getRequestBody({ + ...options, + + path, + query: { startDate, endDate }, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } + +} diff --git a/shared/extra-utils/logs/logs.ts b/shared/extra-utils/logs/logs.ts deleted file mode 100644 index 8d741276c..000000000 --- a/shared/extra-utils/logs/logs.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { makeGetRequest } from '../requests/requests' -import { LogLevel } from '../../models/server/log-level.type' -import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' - -function getLogs (url: string, accessToken: string, startDate: Date, endDate?: Date, level?: LogLevel) { - const path = '/api/v1/server/logs' - - return makeGetRequest({ - url, - path, - token: accessToken, - query: { startDate, endDate, level }, - statusCodeExpected: HttpStatusCode.OK_200 - }) -} - -function getAuditLogs (url: string, accessToken: string, startDate: Date, endDate?: Date) { - const path = '/api/v1/server/audit-logs' - - return makeGetRequest({ - url, - path, - token: accessToken, - query: { startDate, endDate }, - statusCodeExpected: HttpStatusCode.OK_200 - }) -} - -export { - getLogs, - getAuditLogs -} diff --git a/shared/extra-utils/server/servers.ts b/shared/extra-utils/server/servers.ts index b64c9eec6..4343eab93 100644 --- a/shared/extra-utils/server/servers.ts +++ b/shared/extra-utils/server/servers.ts @@ -10,6 +10,7 @@ import { BulkCommand } from '../bulk' import { CLICommand } from '../cli' import { CustomPagesCommand } from '../custom-pages' import { FeedCommand } from '../feeds' +import { LogsCommand } from '../logs' import { buildServerDirectory, getFileSize, isGithubCI, root, wait } from '../miscs/miscs' import { makeGetRequest } from '../requests/requests' @@ -69,6 +70,7 @@ interface ServerInfo { cliCommand?: CLICommand customPageCommand?: CustomPagesCommand feedCommand?: FeedCommand + logsCommand?: LogsCommand } function parallelTests () { @@ -278,6 +280,7 @@ async function runServer (server: ServerInfo, configOverrideArg?: any, args = [] server.cliCommand = new CLICommand(server) server.customPageCommand = new CustomPagesCommand(server) server.feedCommand = new FeedCommand(server) + server.logsCommand = new LogsCommand(server) res(server) }) diff --git a/shared/extra-utils/shared/abstract-command.ts b/shared/extra-utils/shared/abstract-command.ts index 7f812daa8..a57222216 100644 --- a/shared/extra-utils/shared/abstract-command.ts +++ b/shared/extra-utils/shared/abstract-command.ts @@ -13,7 +13,7 @@ interface CommonCommandOptions extends OverrideCommandOptions { } interface GetCommandOptions extends CommonCommandOptions { - query?: { [ id: string ]: string } + query?: { [ id: string ]: any } contentType?: string accept?: string } -- cgit v1.2.3 From c8fc9b47188b33cfc33184b1ee7e680a093244f1 Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Tue, 6 Jul 2021 10:35:35 +0200 Subject: Rename mock server files --- .../tests/api/notifications/admin-notifications.ts | 2 +- shared/extra-utils/index.ts | 2 +- shared/extra-utils/mock-servers/index.ts | 2 ++ .../mock-servers/joinpeertube-versions.ts | 33 ---------------------- .../mock-servers/mock-joinpeertube-versions.ts | 33 ++++++++++++++++++++++ 5 files changed, 37 insertions(+), 35 deletions(-) create mode 100644 shared/extra-utils/mock-servers/index.ts delete mode 100644 shared/extra-utils/mock-servers/joinpeertube-versions.ts create mode 100644 shared/extra-utils/mock-servers/mock-joinpeertube-versions.ts diff --git a/server/tests/api/notifications/admin-notifications.ts b/server/tests/api/notifications/admin-notifications.ts index cfe0bd2bb..170aa4532 100644 --- a/server/tests/api/notifications/admin-notifications.ts +++ b/server/tests/api/notifications/admin-notifications.ts @@ -2,7 +2,7 @@ import 'mocha' import { expect } from 'chai' -import { MockJoinPeerTubeVersions } from '@shared/extra-utils/mock-servers/joinpeertube-versions' +import { MockJoinPeerTubeVersions } from '@shared/extra-utils' import { PluginType } from '@shared/models' import { cleanupTests, installPlugin, setPluginLatestVersion, setPluginVersion, wait } from '../../../../shared/extra-utils' import { ServerInfo } from '../../../../shared/extra-utils/index' diff --git a/shared/extra-utils/index.ts b/shared/extra-utils/index.ts index a3d3970af..30f44dfc2 100644 --- a/shared/extra-utils/index.ts +++ b/shared/extra-utils/index.ts @@ -8,7 +8,7 @@ export * from './feeds' export * from './logs' -export * from './mock-servers/mock-instances-index' +export * from './mock-servers' export * from './miscs/email' export * from './miscs/sql' diff --git a/shared/extra-utils/mock-servers/index.ts b/shared/extra-utils/mock-servers/index.ts new file mode 100644 index 000000000..47679c818 --- /dev/null +++ b/shared/extra-utils/mock-servers/index.ts @@ -0,0 +1,2 @@ +export * from './mock-instances-index' +export * from './mock-joinpeertube-versions' diff --git a/shared/extra-utils/mock-servers/joinpeertube-versions.ts b/shared/extra-utils/mock-servers/joinpeertube-versions.ts deleted file mode 100644 index 5ea432ecf..000000000 --- a/shared/extra-utils/mock-servers/joinpeertube-versions.ts +++ /dev/null @@ -1,33 +0,0 @@ -import * as express from 'express' -import { randomInt } from '@shared/core-utils' - -export class MockJoinPeerTubeVersions { - private latestVersion: string - - initialize () { - return new Promise(res => { - const app = express() - - app.use('/', (req: express.Request, res: express.Response, next: express.NextFunction) => { - if (process.env.DEBUG) console.log('Receiving request on mocked server %s.', req.url) - - return next() - }) - - app.get('/versions.json', (req: express.Request, res: express.Response) => { - return res.json({ - peertube: { - latestVersion: this.latestVersion - } - }) - }) - - const port = 42201 + randomInt(1, 100) - app.listen(port, () => res(port)) - }) - } - - setLatestVersion (latestVersion: string) { - this.latestVersion = latestVersion - } -} diff --git a/shared/extra-utils/mock-servers/mock-joinpeertube-versions.ts b/shared/extra-utils/mock-servers/mock-joinpeertube-versions.ts new file mode 100644 index 000000000..5ea432ecf --- /dev/null +++ b/shared/extra-utils/mock-servers/mock-joinpeertube-versions.ts @@ -0,0 +1,33 @@ +import * as express from 'express' +import { randomInt } from '@shared/core-utils' + +export class MockJoinPeerTubeVersions { + private latestVersion: string + + initialize () { + return new Promise(res => { + const app = express() + + app.use('/', (req: express.Request, res: express.Response, next: express.NextFunction) => { + if (process.env.DEBUG) console.log('Receiving request on mocked server %s.', req.url) + + return next() + }) + + app.get('/versions.json', (req: express.Request, res: express.Response) => { + return res.json({ + peertube: { + latestVersion: this.latestVersion + } + }) + }) + + const port = 42201 + randomInt(1, 100) + app.listen(port, () => res(port)) + }) + } + + setLatestVersion (latestVersion: string) { + this.latestVersion = latestVersion + } +} -- cgit v1.2.3 From 8ef9457fdee7812b1a8cc3b3bdeff94130819003 Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Tue, 6 Jul 2021 10:36:54 +0200 Subject: Correctly export misc files --- server/tests/api/check-params/contact-form.ts | 5 +- server/tests/api/check-params/users.ts | 2 +- .../tests/api/notifications/admin-notifications.ts | 2 +- .../api/notifications/moderation-notifications.ts | 2 +- .../tests/api/notifications/notifications-api.ts | 2 +- .../tests/api/notifications/user-notifications.ts | 2 +- server/tests/api/server/contact-form.ts | 8 +-- server/tests/api/server/email.ts | 4 +- server/tests/api/users/users-verification.ts | 8 +-- shared/extra-utils/index.ts | 11 +--- shared/extra-utils/miscs/email.ts | 64 ---------------------- shared/extra-utils/miscs/index.ts | 3 + shared/extra-utils/mock-servers/index.ts | 1 + shared/extra-utils/mock-servers/mock-email.ts | 64 ++++++++++++++++++++++ shared/extra-utils/users/user-notifications.ts | 2 +- 15 files changed, 87 insertions(+), 93 deletions(-) delete mode 100644 shared/extra-utils/miscs/email.ts create mode 100644 shared/extra-utils/miscs/index.ts create mode 100644 shared/extra-utils/mock-servers/mock-email.ts diff --git a/server/tests/api/check-params/contact-form.ts b/server/tests/api/check-params/contact-form.ts index c7f9c1b47..274562cbb 100644 --- a/server/tests/api/check-params/contact-form.ts +++ b/server/tests/api/check-params/contact-form.ts @@ -1,11 +1,10 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ import 'mocha' - +import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' import { cleanupTests, flushAndRunServer, immutableAssign, killallServers, reRunServer, ServerInfo } from '../../../../shared/extra-utils' +import { MockSmtpServer } from '../../../../shared/extra-utils/mock-servers/mock-email' import { sendContactForm } from '../../../../shared/extra-utils/server/contact-form' -import { MockSmtpServer } from '../../../../shared/extra-utils/miscs/email' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' describe('Test contact form API validators', function () { let server: ServerInfo diff --git a/server/tests/api/check-params/users.ts b/server/tests/api/check-params/users.ts index 70a872ce5..da0f55bf8 100644 --- a/server/tests/api/check-params/users.ts +++ b/server/tests/api/check-params/users.ts @@ -32,7 +32,7 @@ import { uploadVideo, userLogin } from '../../../../shared/extra-utils' -import { MockSmtpServer } from '../../../../shared/extra-utils/miscs/email' +import { MockSmtpServer } from '../../../../shared/extra-utils/mock-servers/mock-email' import { checkBadCountPagination, checkBadSortPagination, diff --git a/server/tests/api/notifications/admin-notifications.ts b/server/tests/api/notifications/admin-notifications.ts index 170aa4532..91681c9d6 100644 --- a/server/tests/api/notifications/admin-notifications.ts +++ b/server/tests/api/notifications/admin-notifications.ts @@ -6,7 +6,7 @@ import { MockJoinPeerTubeVersions } from '@shared/extra-utils' import { PluginType } from '@shared/models' import { cleanupTests, installPlugin, setPluginLatestVersion, setPluginVersion, wait } from '../../../../shared/extra-utils' import { ServerInfo } from '../../../../shared/extra-utils/index' -import { MockSmtpServer } from '../../../../shared/extra-utils/miscs/email' +import { MockSmtpServer } from '../../../../shared/extra-utils/mock-servers/mock-email' import { CheckerBaseParams, checkNewPeerTubeVersion, diff --git a/server/tests/api/notifications/moderation-notifications.ts b/server/tests/api/notifications/moderation-notifications.ts index 3425480ae..a7671696f 100644 --- a/server/tests/api/notifications/moderation-notifications.ts +++ b/server/tests/api/notifications/moderation-notifications.ts @@ -27,7 +27,7 @@ import { wait } from '../../../../shared/extra-utils' import { ServerInfo, uploadVideo } from '../../../../shared/extra-utils/index' -import { MockSmtpServer } from '../../../../shared/extra-utils/miscs/email' +import { MockSmtpServer } from '../../../../shared/extra-utils/mock-servers/mock-email' import { waitJobs } from '../../../../shared/extra-utils/server/jobs' import { checkAbuseStateChange, diff --git a/server/tests/api/notifications/notifications-api.ts b/server/tests/api/notifications/notifications-api.ts index b81995449..19f9dbbab 100644 --- a/server/tests/api/notifications/notifications-api.ts +++ b/server/tests/api/notifications/notifications-api.ts @@ -5,7 +5,7 @@ import * as chai from 'chai' import { addUserSubscription } from '@shared/extra-utils/users/user-subscriptions' import { cleanupTests, getMyUserInformation, immutableAssign, uploadRandomVideo, waitJobs } from '../../../../shared/extra-utils' import { ServerInfo } from '../../../../shared/extra-utils/index' -import { MockSmtpServer } from '../../../../shared/extra-utils/miscs/email' +import { MockSmtpServer } from '../../../../shared/extra-utils/mock-servers/mock-email' import { CheckerBaseParams, checkNewVideoFromSubscription, diff --git a/server/tests/api/notifications/user-notifications.ts b/server/tests/api/notifications/user-notifications.ts index e981c1718..ace7e48c7 100644 --- a/server/tests/api/notifications/user-notifications.ts +++ b/server/tests/api/notifications/user-notifications.ts @@ -12,7 +12,7 @@ import { wait } from '../../../../shared/extra-utils' import { ServerInfo } from '../../../../shared/extra-utils/index' -import { MockSmtpServer } from '../../../../shared/extra-utils/miscs/email' +import { MockSmtpServer } from '../../../../shared/extra-utils/mock-servers/mock-email' import { waitJobs } from '../../../../shared/extra-utils/server/jobs' import { CheckerBaseParams, diff --git a/server/tests/api/server/contact-form.ts b/server/tests/api/server/contact-form.ts index 8851ad55e..71205723d 100644 --- a/server/tests/api/server/contact-form.ts +++ b/server/tests/api/server/contact-form.ts @@ -1,12 +1,12 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ -import * as chai from 'chai' import 'mocha' +import * as chai from 'chai' +import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' import { cleanupTests, flushAndRunServer, ServerInfo, setAccessTokensToServers, wait } from '../../../../shared/extra-utils' -import { MockSmtpServer } from '../../../../shared/extra-utils/miscs/email' -import { waitJobs } from '../../../../shared/extra-utils/server/jobs' +import { MockSmtpServer } from '../../../../shared/extra-utils/mock-servers/mock-email' import { sendContactForm } from '../../../../shared/extra-utils/server/contact-form' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' +import { waitJobs } from '../../../../shared/extra-utils/server/jobs' const expect = chai.expect diff --git a/server/tests/api/server/email.ts b/server/tests/api/server/email.ts index 92768d9df..41071692a 100644 --- a/server/tests/api/server/email.ts +++ b/server/tests/api/server/email.ts @@ -2,6 +2,7 @@ import 'mocha' import * as chai from 'chai' +import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' import { addVideoToBlacklist, askResetPassword, @@ -20,9 +21,8 @@ import { userLogin, verifyEmail } from '../../../../shared/extra-utils' -import { MockSmtpServer } from '../../../../shared/extra-utils/miscs/email' +import { MockSmtpServer } from '../../../../shared/extra-utils/mock-servers/mock-email' import { waitJobs } from '../../../../shared/extra-utils/server/jobs' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' const expect = chai.expect diff --git a/server/tests/api/users/users-verification.ts b/server/tests/api/users/users-verification.ts index e0f2f2112..265cd6050 100644 --- a/server/tests/api/users/users-verification.ts +++ b/server/tests/api/users/users-verification.ts @@ -1,7 +1,8 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ -import * as chai from 'chai' import 'mocha' +import * as chai from 'chai' +import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' import { cleanupTests, flushAndRunServer, @@ -15,11 +16,10 @@ import { userLogin, verifyEmail } from '../../../../shared/extra-utils' -import { setAccessTokensToServers } from '../../../../shared/extra-utils/users/login' -import { MockSmtpServer } from '../../../../shared/extra-utils/miscs/email' +import { MockSmtpServer } from '../../../../shared/extra-utils/mock-servers/mock-email' import { waitJobs } from '../../../../shared/extra-utils/server/jobs' +import { setAccessTokensToServers } from '../../../../shared/extra-utils/users/login' import { User } from '../../../../shared/models/users' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' const expect = chai.expect diff --git a/shared/extra-utils/index.ts b/shared/extra-utils/index.ts index 30f44dfc2..7d2887209 100644 --- a/shared/extra-utils/index.ts +++ b/shared/extra-utils/index.ts @@ -1,20 +1,11 @@ export * from './bulk' - export * from './cli' - export * from './custom-pages' - export * from './feeds' - export * from './logs' - +export * from './miscs' export * from './mock-servers' -export * from './miscs/email' -export * from './miscs/sql' -export * from './miscs/miscs' -export * from './miscs/stubs' - export * from './moderation/abuses' export * from './plugins/mock-blocklist' diff --git a/shared/extra-utils/miscs/email.ts b/shared/extra-utils/miscs/email.ts deleted file mode 100644 index 9fc9a5ad0..000000000 --- a/shared/extra-utils/miscs/email.ts +++ /dev/null @@ -1,64 +0,0 @@ -import { ChildProcess } from 'child_process' -import { randomInt } from '../../core-utils/miscs/miscs' -import { parallelTests } from '../server/servers' - -const MailDev = require('maildev') - -class MockSmtpServer { - - private static instance: MockSmtpServer - private started = false - private emailChildProcess: ChildProcess - private emails: object[] - - private constructor () { } - - collectEmails (emailsCollection: object[]) { - return new Promise((res, rej) => { - const port = parallelTests() ? randomInt(1000, 2000) : 1025 - this.emails = emailsCollection - - if (this.started) { - return res(undefined) - } - - const maildev = new MailDev({ - ip: '127.0.0.1', - smtp: port, - disableWeb: true, - silent: true - }) - - maildev.on('new', email => { - this.emails.push(email) - }) - - maildev.listen(err => { - if (err) return rej(err) - - this.started = true - - return res(port) - }) - }) - } - - kill () { - if (!this.emailChildProcess) return - - process.kill(this.emailChildProcess.pid) - - this.emailChildProcess = null - MockSmtpServer.instance = null - } - - static get Instance () { - return this.instance || (this.instance = new this()) - } -} - -// --------------------------------------------------------------------------- - -export { - MockSmtpServer -} diff --git a/shared/extra-utils/miscs/index.ts b/shared/extra-utils/miscs/index.ts new file mode 100644 index 000000000..ccacd4c79 --- /dev/null +++ b/shared/extra-utils/miscs/index.ts @@ -0,0 +1,3 @@ +export * from './miscs' +export * from './sql' +export * from './stubs' diff --git a/shared/extra-utils/mock-servers/index.ts b/shared/extra-utils/mock-servers/index.ts index 47679c818..485757843 100644 --- a/shared/extra-utils/mock-servers/index.ts +++ b/shared/extra-utils/mock-servers/index.ts @@ -1,2 +1,3 @@ +export * from './mock-email' export * from './mock-instances-index' export * from './mock-joinpeertube-versions' diff --git a/shared/extra-utils/mock-servers/mock-email.ts b/shared/extra-utils/mock-servers/mock-email.ts new file mode 100644 index 000000000..9fc9a5ad0 --- /dev/null +++ b/shared/extra-utils/mock-servers/mock-email.ts @@ -0,0 +1,64 @@ +import { ChildProcess } from 'child_process' +import { randomInt } from '../../core-utils/miscs/miscs' +import { parallelTests } from '../server/servers' + +const MailDev = require('maildev') + +class MockSmtpServer { + + private static instance: MockSmtpServer + private started = false + private emailChildProcess: ChildProcess + private emails: object[] + + private constructor () { } + + collectEmails (emailsCollection: object[]) { + return new Promise((res, rej) => { + const port = parallelTests() ? randomInt(1000, 2000) : 1025 + this.emails = emailsCollection + + if (this.started) { + return res(undefined) + } + + const maildev = new MailDev({ + ip: '127.0.0.1', + smtp: port, + disableWeb: true, + silent: true + }) + + maildev.on('new', email => { + this.emails.push(email) + }) + + maildev.listen(err => { + if (err) return rej(err) + + this.started = true + + return res(port) + }) + }) + } + + kill () { + if (!this.emailChildProcess) return + + process.kill(this.emailChildProcess.pid) + + this.emailChildProcess = null + MockSmtpServer.instance = null + } + + static get Instance () { + return this.instance || (this.instance = new this()) + } +} + +// --------------------------------------------------------------------------- + +export { + MockSmtpServer +} diff --git a/shared/extra-utils/users/user-notifications.ts b/shared/extra-utils/users/user-notifications.ts index 844f4442d..e75946eec 100644 --- a/shared/extra-utils/users/user-notifications.ts +++ b/shared/extra-utils/users/user-notifications.ts @@ -5,7 +5,7 @@ import { inspect } from 'util' import { AbuseState, PluginType } from '@shared/models' import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' import { UserNotification, UserNotificationSetting, UserNotificationSettingValue, UserNotificationType } from '../../models/users' -import { MockSmtpServer } from '../miscs/email' +import { MockSmtpServer } from '../mock-servers/mock-email' import { makeGetRequest, makePostBodyRequest, makePutBodyRequest } from '../requests/requests' import { doubleFollow } from '../server/follows' import { flushAndRunMultipleServers, ServerInfo } from '../server/servers' -- cgit v1.2.3 From 0c1a77e9ccf915184c431145a8b326d4ce271b46 Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Tue, 6 Jul 2021 12:01:59 +0200 Subject: Introduce abuse command --- server/tests/api/check-params/abuses.ts | 146 +++-- server/tests/api/moderation/abuses.ts | 631 ++++++++++----------- .../api/notifications/moderation-notifications.ts | 88 ++- server/tests/api/server/email.ts | 3 +- server/tests/api/users/users.ts | 28 +- shared/extra-utils/index.ts | 2 +- shared/extra-utils/moderation/abuses-command.ts | 205 +++++++ shared/extra-utils/moderation/abuses.ts | 244 -------- shared/extra-utils/moderation/index.ts | 1 + shared/extra-utils/server/servers.ts | 3 + shared/extra-utils/shared/abstract-command.ts | 6 +- tsconfig.json | 1 + 12 files changed, 631 insertions(+), 727 deletions(-) create mode 100644 shared/extra-utils/moderation/abuses-command.ts delete mode 100644 shared/extra-utils/moderation/abuses.ts create mode 100644 shared/extra-utils/moderation/index.ts diff --git a/server/tests/api/check-params/abuses.ts b/server/tests/api/check-params/abuses.ts index 2054776cc..e158e50dc 100644 --- a/server/tests/api/check-params/abuses.ts +++ b/server/tests/api/check-params/abuses.ts @@ -1,46 +1,40 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ import 'mocha' -import { AbuseCreate, AbuseState } from '@shared/models' +import { HttpStatusCode } from '@shared/core-utils' import { - addAbuseMessage, + AbusesCommand, + checkBadCountPagination, + checkBadSortPagination, + checkBadStartPagination, cleanupTests, createUser, - deleteAbuse, - deleteAbuseMessage, doubleFollow, flushAndRunServer, generateUserAccessToken, - getAdminAbusesList, getVideoIdFromUUID, - listAbuseMessages, makeGetRequest, makePostBodyRequest, - reportAbuse, ServerInfo, setAccessTokensToServers, - updateAbuse, uploadVideo, userLogin, waitJobs -} from '../../../../shared/extra-utils' -import { - checkBadCountPagination, - checkBadSortPagination, - checkBadStartPagination -} from '../../../../shared/extra-utils/requests/check-api-params' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' +} from '@shared/extra-utils' +import { AbuseCreate, AbuseState } from '@shared/models' describe('Test abuses API validators', function () { const basePath = '/api/v1/abuses/' let server: ServerInfo - let userAccessToken = '' - let userAccessToken2 = '' + let userToken = '' + let userToken2 = '' let abuseId: number let messageId: number + let command: AbusesCommand + // --------------------------------------------------------------- before(async function () { @@ -53,14 +47,14 @@ describe('Test abuses API validators', function () { const username = 'user1' const password = 'my super password' await createUser({ url: server.url, accessToken: server.accessToken, username: username, password: password }) - userAccessToken = await userLogin(server, { username, password }) + userToken = await userLogin(server, { username, password }) - { - userAccessToken2 = await generateUserAccessToken(server, 'user_2') - } + userToken2 = await generateUserAccessToken(server, 'user_2') const res = await uploadVideo(server.url, server.accessToken, {}) server.video = res.body.video + + command = server.abusesCommand }) describe('When listing abuses for admins', function () { @@ -90,7 +84,7 @@ describe('Test abuses API validators', function () { await makeGetRequest({ url: server.url, path, - token: userAccessToken, + token: userToken, statusCodeExpected: HttpStatusCode.FORBIDDEN_403 }) }) @@ -134,15 +128,15 @@ describe('Test abuses API validators', function () { const path = '/api/v1/users/me/abuses' it('Should fail with a bad start pagination', async function () { - await checkBadStartPagination(server.url, path, userAccessToken) + await checkBadStartPagination(server.url, path, userToken) }) it('Should fail with a bad count pagination', async function () { - await checkBadCountPagination(server.url, path, userAccessToken) + await checkBadCountPagination(server.url, path, userToken) }) it('Should fail with an incorrect sort', async function () { - await checkBadSortPagination(server.url, path, userAccessToken) + await checkBadSortPagination(server.url, path, userToken) }) it('Should fail with a non authenticated user', async function () { @@ -154,12 +148,12 @@ describe('Test abuses API validators', function () { }) it('Should fail with a bad id filter', async function () { - await makeGetRequest({ url: server.url, path, token: userAccessToken, query: { id: 'toto' } }) + await makeGetRequest({ url: server.url, path, token: userToken, query: { id: 'toto' } }) }) it('Should fail with a bad state filter', async function () { - await makeGetRequest({ url: server.url, path, token: userAccessToken, query: { state: 'toto' } }) - await makeGetRequest({ url: server.url, path, token: userAccessToken, query: { state: 0 } }) + await makeGetRequest({ url: server.url, path, token: userToken, query: { state: 'toto' } }) + await makeGetRequest({ url: server.url, path, token: userToken, query: { state: 0 } }) }) it('Should succeed with the correct params', async function () { @@ -168,7 +162,7 @@ describe('Test abuses API validators', function () { state: 2 } - await makeGetRequest({ url: server.url, path, token: userAccessToken, query, statusCodeExpected: HttpStatusCode.OK_200 }) + await makeGetRequest({ url: server.url, path, token: userToken, query, statusCodeExpected: HttpStatusCode.OK_200 }) }) }) @@ -177,12 +171,12 @@ describe('Test abuses API validators', function () { it('Should fail with nothing', async function () { const fields = {} - await makePostBodyRequest({ url: server.url, path, token: userAccessToken, fields }) + await makePostBodyRequest({ url: server.url, path, token: userToken, fields }) }) it('Should fail with a wrong video', async function () { const fields = { video: { id: 'blabla' }, reason: 'my super reason' } - await makePostBodyRequest({ url: server.url, path: path, token: userAccessToken, fields }) + await makePostBodyRequest({ url: server.url, path: path, token: userToken, fields }) }) it('Should fail with an unknown video', async function () { @@ -190,7 +184,7 @@ describe('Test abuses API validators', function () { await makePostBodyRequest({ url: server.url, path, - token: userAccessToken, + token: userToken, fields, statusCodeExpected: HttpStatusCode.NOT_FOUND_404 }) @@ -198,7 +192,7 @@ describe('Test abuses API validators', function () { it('Should fail with a wrong comment', async function () { const fields = { comment: { id: 'blabla' }, reason: 'my super reason' } - await makePostBodyRequest({ url: server.url, path: path, token: userAccessToken, fields }) + await makePostBodyRequest({ url: server.url, path: path, token: userToken, fields }) }) it('Should fail with an unknown comment', async function () { @@ -206,7 +200,7 @@ describe('Test abuses API validators', function () { await makePostBodyRequest({ url: server.url, path, - token: userAccessToken, + token: userToken, fields, statusCodeExpected: HttpStatusCode.NOT_FOUND_404 }) @@ -214,7 +208,7 @@ describe('Test abuses API validators', function () { it('Should fail with a wrong account', async function () { const fields = { account: { id: 'blabla' }, reason: 'my super reason' } - await makePostBodyRequest({ url: server.url, path: path, token: userAccessToken, fields }) + await makePostBodyRequest({ url: server.url, path: path, token: userToken, fields }) }) it('Should fail with an unknown account', async function () { @@ -222,7 +216,7 @@ describe('Test abuses API validators', function () { await makePostBodyRequest({ url: server.url, path, - token: userAccessToken, + token: userToken, fields, statusCodeExpected: HttpStatusCode.NOT_FOUND_404 }) @@ -233,7 +227,7 @@ describe('Test abuses API validators', function () { await makePostBodyRequest({ url: server.url, path, - token: userAccessToken, + token: userToken, fields, statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) @@ -248,13 +242,13 @@ describe('Test abuses API validators', function () { it('Should fail with a reason too short', async function () { const fields = { video: { id: server.video.id }, reason: 'h' } - await makePostBodyRequest({ url: server.url, path, token: userAccessToken, fields }) + await makePostBodyRequest({ url: server.url, path, token: userToken, fields }) }) it('Should fail with a too big reason', async function () { const fields = { video: { id: server.video.id }, reason: 'super'.repeat(605) } - await makePostBodyRequest({ url: server.url, path, token: userAccessToken, fields }) + await makePostBodyRequest({ url: server.url, path, token: userToken, fields }) }) it('Should succeed with the correct parameters (basic)', async function () { @@ -263,7 +257,7 @@ describe('Test abuses API validators', function () { const res = await makePostBodyRequest({ url: server.url, path, - token: userAccessToken, + token: userToken, fields, statusCodeExpected: HttpStatusCode.OK_200 }) @@ -273,19 +267,19 @@ describe('Test abuses API validators', function () { it('Should fail with a wrong predefined reason', async function () { const fields = { video: { id: server.video.id }, reason: 'my super reason', predefinedReasons: [ 'wrongPredefinedReason' ] } - await makePostBodyRequest({ url: server.url, path, token: userAccessToken, fields }) + await makePostBodyRequest({ url: server.url, path, token: userToken, fields }) }) it('Should fail with negative timestamps', async function () { const fields = { video: { id: server.video.id, startAt: -1 }, reason: 'my super reason' } - await makePostBodyRequest({ url: server.url, path, token: userAccessToken, fields }) + await makePostBodyRequest({ url: server.url, path, token: userToken, fields }) }) it('Should fail mith misordered startAt/endAt', async function () { const fields = { video: { id: server.video.id, startAt: 5, endAt: 1 }, reason: 'my super reason' } - await makePostBodyRequest({ url: server.url, path, token: userAccessToken, fields }) + await makePostBodyRequest({ url: server.url, path, token: userToken, fields }) }) it('Should succeed with the corret parameters (advanced)', async function () { @@ -299,37 +293,37 @@ describe('Test abuses API validators', function () { predefinedReasons: [ 'serverRules' ] } - await makePostBodyRequest({ url: server.url, path, token: userAccessToken, fields, statusCodeExpected: HttpStatusCode.OK_200 }) + await makePostBodyRequest({ url: server.url, path, token: userToken, fields, statusCodeExpected: HttpStatusCode.OK_200 }) }) }) describe('When updating an abuse', function () { it('Should fail with a non authenticated user', async function () { - await updateAbuse(server.url, 'blabla', abuseId, {}, HttpStatusCode.UNAUTHORIZED_401) + await command.update({ token: 'blabla', abuseId, body: {}, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should fail with a non admin user', async function () { - await updateAbuse(server.url, userAccessToken, abuseId, {}, HttpStatusCode.FORBIDDEN_403) + await command.update({ token: userToken, abuseId, body: {}, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) it('Should fail with a bad abuse id', async function () { - await updateAbuse(server.url, server.accessToken, 45, {}, HttpStatusCode.NOT_FOUND_404) + await command.update({ abuseId: 45, body: {}, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) it('Should fail with a bad state', async function () { const body = { state: 5 } - await updateAbuse(server.url, server.accessToken, abuseId, body, HttpStatusCode.BAD_REQUEST_400) + await command.update({ abuseId, body, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) it('Should fail with a bad moderation comment', async function () { const body = { moderationComment: 'b'.repeat(3001) } - await updateAbuse(server.url, server.accessToken, abuseId, body, HttpStatusCode.BAD_REQUEST_400) + await command.update({ abuseId, body, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) it('Should succeed with the correct params', async function () { const body = { state: AbuseState.ACCEPTED } - await updateAbuse(server.url, server.accessToken, abuseId, body) + await command.update({ abuseId, body }) }) }) @@ -337,23 +331,23 @@ describe('Test abuses API validators', function () { const message = 'my super message' it('Should fail with an invalid abuse id', async function () { - await addAbuseMessage(server.url, userAccessToken2, 888, message, HttpStatusCode.NOT_FOUND_404) + await command.addMessage({ token: userToken2, abuseId: 888, message, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) it('Should fail with a non authenticated user', async function () { - await addAbuseMessage(server.url, 'fake_token', abuseId, message, HttpStatusCode.UNAUTHORIZED_401) + await command.addMessage({ token: 'fake_token', abuseId, message, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should fail with an invalid logged in user', async function () { - await addAbuseMessage(server.url, userAccessToken2, abuseId, message, HttpStatusCode.FORBIDDEN_403) + await command.addMessage({ token: userToken2, abuseId, message, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) it('Should fail with an invalid message', async function () { - await addAbuseMessage(server.url, userAccessToken, abuseId, 'a'.repeat(5000), HttpStatusCode.BAD_REQUEST_400) + await command.addMessage({ token: userToken, abuseId, message: 'a'.repeat(5000), expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) it('Should suceed with the correct params', async function () { - const res = await addAbuseMessage(server.url, userAccessToken, abuseId, message) + const res = await command.addMessage({ token: userToken, abuseId, message }) messageId = res.body.abuseMessage.id }) }) @@ -361,61 +355,60 @@ describe('Test abuses API validators', function () { describe('When listing abuse messages', function () { it('Should fail with an invalid abuse id', async function () { - await listAbuseMessages(server.url, userAccessToken, 888, HttpStatusCode.NOT_FOUND_404) + await command.listMessages({ token: userToken, abuseId: 888, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) it('Should fail with a non authenticated user', async function () { - await listAbuseMessages(server.url, 'fake_token', abuseId, HttpStatusCode.UNAUTHORIZED_401) + await command.listMessages({ token: 'fake_token', abuseId, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should fail with an invalid logged in user', async function () { - await listAbuseMessages(server.url, userAccessToken2, abuseId, HttpStatusCode.FORBIDDEN_403) + await command.listMessages({ token: userToken2, abuseId, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) it('Should succeed with the correct params', async function () { - await listAbuseMessages(server.url, userAccessToken, abuseId) + await command.listMessages({ token: userToken, abuseId }) }) }) describe('When deleting an abuse message', function () { - it('Should fail with an invalid abuse id', async function () { - await deleteAbuseMessage(server.url, userAccessToken, 888, messageId, HttpStatusCode.NOT_FOUND_404) + await command.deleteMessage({ token: userToken, abuseId: 888, messageId, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) it('Should fail with an invalid message id', async function () { - await deleteAbuseMessage(server.url, userAccessToken, abuseId, 888, HttpStatusCode.NOT_FOUND_404) + await command.deleteMessage({ token: userToken, abuseId, messageId: 888, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) it('Should fail with a non authenticated user', async function () { - await deleteAbuseMessage(server.url, 'fake_token', abuseId, messageId, HttpStatusCode.UNAUTHORIZED_401) + await command.deleteMessage({ token: 'fake_token', abuseId, messageId, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should fail with an invalid logged in user', async function () { - await deleteAbuseMessage(server.url, userAccessToken2, abuseId, messageId, HttpStatusCode.FORBIDDEN_403) + await command.deleteMessage({ token: userToken2, abuseId, messageId, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) it('Should succeed with the correct params', async function () { - await deleteAbuseMessage(server.url, userAccessToken, abuseId, messageId) + await command.deleteMessage({ token: userToken, abuseId, messageId }) }) }) describe('When deleting a video abuse', function () { it('Should fail with a non authenticated user', async function () { - await deleteAbuse(server.url, 'blabla', abuseId, HttpStatusCode.UNAUTHORIZED_401) + await command.delete({ token: 'blabla', abuseId, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should fail with a non admin user', async function () { - await deleteAbuse(server.url, userAccessToken, abuseId, HttpStatusCode.FORBIDDEN_403) + await command.delete({ token: userToken, abuseId, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) it('Should fail with a bad abuse id', async function () { - await deleteAbuse(server.url, server.accessToken, 45, HttpStatusCode.NOT_FOUND_404) + await command.delete({ abuseId: 45, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) it('Should succeed with the correct params', async function () { - await deleteAbuse(server.url, server.accessToken, abuseId) + await command.delete({ abuseId }) }) }) @@ -432,25 +425,20 @@ describe('Test abuses API validators', function () { await doubleFollow(anotherServer, server) const server2VideoId = await getVideoIdFromUUID(anotherServer.url, server.video.uuid) - await reportAbuse({ - url: anotherServer.url, - token: anotherServer.accessToken, - reason: 'remote server', - videoId: server2VideoId - }) + await anotherServer.abusesCommand.report({ reason: 'remote server', videoId: server2VideoId }) await waitJobs([ server, anotherServer ]) - const res = await getAdminAbusesList({ url: server.url, token: server.accessToken, sort: '-createdAt' }) - remoteAbuseId = res.body.data[0].id + const body = await command.getAdminList({ sort: '-createdAt' }) + remoteAbuseId = body.data[0].id }) it('Should fail when listing abuse messages of a remote abuse', async function () { - await listAbuseMessages(server.url, server.accessToken, remoteAbuseId, HttpStatusCode.BAD_REQUEST_400) + await command.listMessages({ abuseId: remoteAbuseId, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) it('Should fail when creating abuse message of a remote abuse', async function () { - await addAbuseMessage(server.url, server.accessToken, remoteAbuseId, 'message', HttpStatusCode.BAD_REQUEST_400) + await command.addMessage({ abuseId: remoteAbuseId, message: 'message', expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) after(async function () { diff --git a/server/tests/api/moderation/abuses.ts b/server/tests/api/moderation/abuses.ts index fb765e7e3..a9f5332ce 100644 --- a/server/tests/api/moderation/abuses.ts +++ b/server/tests/api/moderation/abuses.ts @@ -3,51 +3,32 @@ import 'mocha' import * as chai from 'chai' import { - AbuseFilter, - AbuseMessage, - AbusePredefinedReasonsString, - AbuseState, - Account, - AdminAbuse, - UserAbuse, - VideoComment -} from '@shared/models' -import { - addAbuseMessage, + AbusesCommand, + addAccountToServerBlocklist, + addServerToServerBlocklist, addVideoCommentThread, cleanupTests, createUser, - deleteAbuse, - deleteAbuseMessage, deleteVideoComment, + doubleFollow, flushAndRunMultipleServers, generateUserAccessToken, getAccount, - getAdminAbusesList, - getUserAbusesList, getVideoCommentThreads, getVideoIdFromUUID, getVideosList, - immutableAssign, - listAbuseMessages, + removeAccountFromServerBlocklist, + removeServerFromServerBlocklist, removeUser, removeVideo, - reportAbuse, ServerInfo, setAccessTokensToServers, - updateAbuse, uploadVideo, uploadVideoAndGetId, - userLogin -} from '../../../../shared/extra-utils/index' -import { doubleFollow } from '../../../../shared/extra-utils/server/follows' -import { waitJobs } from '../../../../shared/extra-utils/server/jobs' -import { - addAccountToServerBlocklist, - addServerToServerBlocklist, - removeAccountFromServerBlocklist, - removeServerFromServerBlocklist -} from '../../../../shared/extra-utils/users/blocklist' + userLogin, + waitJobs +} from '@shared/extra-utils' +import { AbuseMessage, AbusePredefinedReasonsString, AbuseState, Account, AdminAbuse, UserAbuse, VideoComment } from '@shared/models' const expect = chai.expect @@ -55,6 +36,7 @@ describe('Test abuses', function () { let servers: ServerInfo[] = [] let abuseServer1: AdminAbuse let abuseServer2: AdminAbuse + let commands: AbusesCommand[] before(async function () { this.timeout(50000) @@ -67,6 +49,8 @@ describe('Test abuses', function () { // Server 1 and server 2 follow each other await doubleFollow(servers[0], servers[1]) + + commands = servers.map(s => s.abusesCommand) }) describe('Video abuses', function () { @@ -100,54 +84,58 @@ describe('Test abuses', function () { }) it('Should not have abuses', async function () { - const res = await getAdminAbusesList({ url: servers[0].url, token: servers[0].accessToken }) + const body = await commands[0].getAdminList() - expect(res.body.total).to.equal(0) - expect(res.body.data).to.be.an('array') - expect(res.body.data.length).to.equal(0) + expect(body.total).to.equal(0) + expect(body.data).to.be.an('array') + expect(body.data.length).to.equal(0) }) it('Should report abuse on a local video', async function () { this.timeout(15000) const reason = 'my super bad reason' - await reportAbuse({ url: servers[0].url, token: servers[0].accessToken, videoId: servers[0].video.id, reason }) + await commands[0].report({ videoId: servers[0].video.id, reason }) // We wait requests propagation, even if the server 1 is not supposed to make a request to server 2 await waitJobs(servers) }) it('Should have 1 video abuses on server 1 and 0 on server 2', async function () { - const res1 = await getAdminAbusesList({ url: servers[0].url, token: servers[0].accessToken }) + { + const body = await commands[0].getAdminList() - expect(res1.body.total).to.equal(1) - expect(res1.body.data).to.be.an('array') - expect(res1.body.data.length).to.equal(1) + expect(body.total).to.equal(1) + expect(body.data).to.be.an('array') + expect(body.data.length).to.equal(1) - const abuse: AdminAbuse = res1.body.data[0] - expect(abuse.reason).to.equal('my super bad reason') + const abuse = body.data[0] + expect(abuse.reason).to.equal('my super bad reason') - expect(abuse.reporterAccount.name).to.equal('root') - expect(abuse.reporterAccount.host).to.equal(servers[0].host) + expect(abuse.reporterAccount.name).to.equal('root') + expect(abuse.reporterAccount.host).to.equal(servers[0].host) - expect(abuse.video.id).to.equal(servers[0].video.id) - expect(abuse.video.channel).to.exist + expect(abuse.video.id).to.equal(servers[0].video.id) + expect(abuse.video.channel).to.exist - expect(abuse.comment).to.be.null + expect(abuse.comment).to.be.null - expect(abuse.flaggedAccount.name).to.equal('root') - expect(abuse.flaggedAccount.host).to.equal(servers[0].host) + expect(abuse.flaggedAccount.name).to.equal('root') + expect(abuse.flaggedAccount.host).to.equal(servers[0].host) - expect(abuse.video.countReports).to.equal(1) - expect(abuse.video.nthReport).to.equal(1) + expect(abuse.video.countReports).to.equal(1) + expect(abuse.video.nthReport).to.equal(1) - expect(abuse.countReportsForReporter).to.equal(1) - expect(abuse.countReportsForReportee).to.equal(1) + expect(abuse.countReportsForReporter).to.equal(1) + expect(abuse.countReportsForReportee).to.equal(1) + } - const res2 = await getAdminAbusesList({ url: servers[1].url, token: servers[1].accessToken }) - expect(res2.body.total).to.equal(0) - expect(res2.body.data).to.be.an('array') - expect(res2.body.data.length).to.equal(0) + { + const body = await commands[1].getAdminList() + expect(body.total).to.equal(0) + expect(body.data).to.be.an('array') + expect(body.data.length).to.equal(0) + } }) it('Should report abuse on a remote video', async function () { @@ -155,68 +143,72 @@ describe('Test abuses', function () { const reason = 'my super bad reason 2' const videoId = await getVideoIdFromUUID(servers[0].url, servers[1].video.uuid) - await reportAbuse({ url: servers[0].url, token: servers[0].accessToken, videoId, reason }) + await commands[0].report({ videoId, reason }) // We wait requests propagation await waitJobs(servers) }) it('Should have 2 video abuses on server 1 and 1 on server 2', async function () { - const res1 = await getAdminAbusesList({ url: servers[0].url, token: servers[0].accessToken }) + { + const body = await commands[0].getAdminList() - expect(res1.body.total).to.equal(2) - expect(res1.body.data.length).to.equal(2) + expect(body.total).to.equal(2) + expect(body.data.length).to.equal(2) - const abuse1: AdminAbuse = res1.body.data[0] - expect(abuse1.reason).to.equal('my super bad reason') - expect(abuse1.reporterAccount.name).to.equal('root') - expect(abuse1.reporterAccount.host).to.equal(servers[0].host) + const abuse1 = body.data[0] + expect(abuse1.reason).to.equal('my super bad reason') + expect(abuse1.reporterAccount.name).to.equal('root') + expect(abuse1.reporterAccount.host).to.equal(servers[0].host) - expect(abuse1.video.id).to.equal(servers[0].video.id) - expect(abuse1.video.countReports).to.equal(1) - expect(abuse1.video.nthReport).to.equal(1) + expect(abuse1.video.id).to.equal(servers[0].video.id) + expect(abuse1.video.countReports).to.equal(1) + expect(abuse1.video.nthReport).to.equal(1) - expect(abuse1.comment).to.be.null + expect(abuse1.comment).to.be.null - expect(abuse1.flaggedAccount.name).to.equal('root') - expect(abuse1.flaggedAccount.host).to.equal(servers[0].host) + expect(abuse1.flaggedAccount.name).to.equal('root') + expect(abuse1.flaggedAccount.host).to.equal(servers[0].host) - expect(abuse1.state.id).to.equal(AbuseState.PENDING) - expect(abuse1.state.label).to.equal('Pending') - expect(abuse1.moderationComment).to.be.null + expect(abuse1.state.id).to.equal(AbuseState.PENDING) + expect(abuse1.state.label).to.equal('Pending') + expect(abuse1.moderationComment).to.be.null - const abuse2: AdminAbuse = res1.body.data[1] - expect(abuse2.reason).to.equal('my super bad reason 2') + const abuse2 = body.data[1] + expect(abuse2.reason).to.equal('my super bad reason 2') - expect(abuse2.reporterAccount.name).to.equal('root') - expect(abuse2.reporterAccount.host).to.equal(servers[0].host) + expect(abuse2.reporterAccount.name).to.equal('root') + expect(abuse2.reporterAccount.host).to.equal(servers[0].host) - expect(abuse2.video.id).to.equal(servers[1].video.id) + expect(abuse2.video.id).to.equal(servers[1].video.id) - expect(abuse2.comment).to.be.null + expect(abuse2.comment).to.be.null - expect(abuse2.flaggedAccount.name).to.equal('root') - expect(abuse2.flaggedAccount.host).to.equal(servers[1].host) + expect(abuse2.flaggedAccount.name).to.equal('root') + expect(abuse2.flaggedAccount.host).to.equal(servers[1].host) - expect(abuse2.state.id).to.equal(AbuseState.PENDING) - expect(abuse2.state.label).to.equal('Pending') - expect(abuse2.moderationComment).to.be.null + expect(abuse2.state.id).to.equal(AbuseState.PENDING) + expect(abuse2.state.label).to.equal('Pending') + expect(abuse2.moderationComment).to.be.null + } - const res2 = await getAdminAbusesList({ url: servers[1].url, token: servers[1].accessToken }) - expect(res2.body.total).to.equal(1) - expect(res2.body.data.length).to.equal(1) + { + const body = await commands[1].getAdminList() + expect(body.total).to.equal(1) + expect(body.data.length).to.equal(1) - abuseServer2 = res2.body.data[0] - expect(abuseServer2.reason).to.equal('my super bad reason 2') - expect(abuseServer2.reporterAccount.name).to.equal('root') - expect(abuseServer2.reporterAccount.host).to.equal(servers[0].host) + abuseServer2 = body.data[0] + expect(abuseServer2.reason).to.equal('my super bad reason 2') + expect(abuseServer2.reporterAccount.name).to.equal('root') + expect(abuseServer2.reporterAccount.host).to.equal(servers[0].host) - expect(abuse2.flaggedAccount.name).to.equal('root') - expect(abuse2.flaggedAccount.host).to.equal(servers[1].host) + expect(abuseServer2.flaggedAccount.name).to.equal('root') + expect(abuseServer2.flaggedAccount.host).to.equal(servers[1].host) - expect(abuseServer2.state.id).to.equal(AbuseState.PENDING) - expect(abuseServer2.state.label).to.equal('Pending') - expect(abuseServer2.moderationComment).to.be.null + expect(abuseServer2.state.id).to.equal(AbuseState.PENDING) + expect(abuseServer2.state.label).to.equal('Pending') + expect(abuseServer2.moderationComment).to.be.null + } }) it('Should hide video abuses from blocked accounts', async function () { @@ -224,11 +216,11 @@ describe('Test abuses', function () { { const videoId = await getVideoIdFromUUID(servers[1].url, servers[0].video.uuid) - await reportAbuse({ url: servers[1].url, token: servers[1].accessToken, videoId, reason: 'will mute this' }) + await commands[1].report({ videoId, reason: 'will mute this' }) await waitJobs(servers) - const res = await getAdminAbusesList({ url: servers[0].url, token: servers[0].accessToken }) - expect(res.body.total).to.equal(3) + const body = await commands[0].getAdminList() + expect(body.total).to.equal(3) } const accountToBlock = 'root@' + servers[1].host @@ -236,18 +228,18 @@ describe('Test abuses', function () { { await addAccountToServerBlocklist(servers[0].url, servers[0].accessToken, accountToBlock) - const res = await getAdminAbusesList({ url: servers[0].url, token: servers[0].accessToken }) - expect(res.body.total).to.equal(2) + const body = await commands[0].getAdminList() + expect(body.total).to.equal(2) - const abuse = res.body.data.find(a => a.reason === 'will mute this') + const abuse = body.data.find(a => a.reason === 'will mute this') expect(abuse).to.be.undefined } { await removeAccountFromServerBlocklist(servers[0].url, servers[0].accessToken, accountToBlock) - const res = await getAdminAbusesList({ url: servers[0].url, token: servers[0].accessToken }) - expect(res.body.total).to.equal(3) + const body = await commands[0].getAdminList() + expect(body.total).to.equal(3) } }) @@ -257,18 +249,18 @@ describe('Test abuses', function () { { await addServerToServerBlocklist(servers[0].url, servers[0].accessToken, servers[1].host) - const res = await getAdminAbusesList({ url: servers[0].url, token: servers[0].accessToken }) - expect(res.body.total).to.equal(2) + const body = await commands[0].getAdminList() + expect(body.total).to.equal(2) - const abuse = res.body.data.find(a => a.reason === 'will mute this') + const abuse = body.data.find(a => a.reason === 'will mute this') expect(abuse).to.be.undefined } { await removeServerFromServerBlocklist(servers[0].url, servers[0].accessToken, serverToBlock) - const res = await getAdminAbusesList({ url: servers[0].url, token: servers[0].accessToken }) - expect(res.body.total).to.equal(3) + const body = await commands[0].getAdminList() + expect(body.total).to.equal(3) } }) @@ -279,11 +271,11 @@ describe('Test abuses', function () { await waitJobs(servers) - const res = await getAdminAbusesList({ url: servers[1].url, token: servers[1].accessToken }) - expect(res.body.total).to.equal(2, "wrong number of videos returned") - expect(res.body.data).to.have.lengthOf(2, "wrong number of videos returned") + const body = await commands[1].getAdminList() + expect(body.total).to.equal(2, "wrong number of videos returned") + expect(body.data).to.have.lengthOf(2, "wrong number of videos returned") - const abuse: AdminAbuse = res.body.data[0] + const abuse = body.data[0] expect(abuse.id).to.equal(abuseServer2.id, "wrong origin server id for first video") expect(abuse.video.id).to.equal(abuseServer2.video.id, "wrong video id") expect(abuse.video.channel).to.exist @@ -303,24 +295,21 @@ describe('Test abuses', function () { name: 'my second super name for server 1', description: 'my second super description for server 1' } - await uploadVideo(servers[0].url, userAccessToken, video3Attributes) - - const res1 = await getVideosList(servers[0].url) - const videos = res1.body.data - const video3 = videos.find(video => video.name === 'my second super name for server 1') + const resUpload = await uploadVideo(servers[0].url, userAccessToken, video3Attributes) + const video3Id = resUpload.body.video.id // resume with the test const reason3 = 'my super bad reason 3' - await reportAbuse({ url: servers[0].url, token: servers[0].accessToken, videoId: video3.id, reason: reason3 }) + await commands[0].report({ videoId: video3Id, reason: reason3 }) const reason4 = 'my super bad reason 4' - await reportAbuse({ url: servers[0].url, token: userAccessToken, videoId: servers[0].video.id, reason: reason4 }) + await commands[0].report({ token: userAccessToken, videoId: servers[0].video.id, reason: reason4 }) { - const res2 = await getAdminAbusesList({ url: servers[0].url, token: servers[0].accessToken }) - const abuses = res2.body.data as AdminAbuse[] + const body = await commands[0].getAdminList() + const abuses = body.data - const abuseVideo3 = res2.body.data.find(a => a.video.id === video3.id) + const abuseVideo3 = body.data.find(a => a.video.id === video3Id) expect(abuseVideo3).to.not.be.undefined expect(abuseVideo3.video.countReports).to.equal(1, "wrong reports count for video 3") expect(abuseVideo3.video.nthReport).to.equal(1, "wrong report position in report list for video 3") @@ -337,20 +326,18 @@ describe('Test abuses', function () { const reason5 = 'my super bad reason 5' const predefinedReasons5: AbusePredefinedReasonsString[] = [ 'violentOrRepulsive', 'captions' ] - const createdAbuse = (await reportAbuse({ - url: servers[0].url, - token: servers[0].accessToken, + const createRes = await commands[0].report({ videoId: servers[0].video.id, reason: reason5, predefinedReasons: predefinedReasons5, startAt: 1, endAt: 5 - })).body.abuse + }) - const res = await getAdminAbusesList({ url: servers[0].url, token: servers[0].accessToken }) + const body = await commands[0].getAdminList() { - const abuse = (res.body.data as AdminAbuse[]).find(a => a.id === createdAbuse.id) + const abuse = body.data.find(a => a.id === createRes.abuse.id) expect(abuse.reason).to.equals(reason5) expect(abuse.predefinedReasons).to.deep.equals(predefinedReasons5, "predefined reasons do not match the one reported") expect(abuse.video.startAt).to.equal(1, "starting timestamp doesn't match the one reported") @@ -361,37 +348,30 @@ describe('Test abuses', function () { it('Should delete the video abuse', async function () { this.timeout(10000) - await deleteAbuse(servers[1].url, servers[1].accessToken, abuseServer2.id) + await commands[1].delete({ abuseId: abuseServer2.id }) await waitJobs(servers) { - const res = await getAdminAbusesList({ url: servers[1].url, token: servers[1].accessToken }) - expect(res.body.total).to.equal(1) - expect(res.body.data.length).to.equal(1) - expect(res.body.data[0].id).to.not.equal(abuseServer2.id) + const body = await commands[1].getAdminList() + expect(body.total).to.equal(1) + expect(body.data.length).to.equal(1) + expect(body.data[0].id).to.not.equal(abuseServer2.id) } { - const res = await getAdminAbusesList({ url: servers[0].url, token: servers[0].accessToken }) - expect(res.body.total).to.equal(6) + const body = await commands[0].getAdminList() + expect(body.total).to.equal(6) } }) it('Should list and filter video abuses', async function () { this.timeout(10000) - async function list (query: Omit[0], 'url' | 'token'>) { - const options = { - url: servers[0].url, - token: servers[0].accessToken - } - - Object.assign(options, query) + async function list (query: Parameters[0]) { + const body = await commands[0].getAdminList(query) - const res = await getAdminAbusesList(options) - - return res.body.data as AdminAbuse[] + return body.data } expect(await list({ id: 56 })).to.have.lengthOf(0) @@ -452,7 +432,7 @@ describe('Test abuses', function () { const comment = await getComment(servers[0].url, servers[0].video.id) const reason = 'it is a bad comment' - await reportAbuse({ url: servers[0].url, token: servers[0].accessToken, commentId: comment.id, reason }) + await commands[0].report({ commentId: comment.id, reason }) await waitJobs(servers) }) @@ -460,12 +440,12 @@ describe('Test abuses', function () { it('Should have 1 comment abuse on server 1 and 0 on server 2', async function () { { const comment = await getComment(servers[0].url, servers[0].video.id) - const res = await getAdminAbusesList({ url: servers[0].url, token: servers[0].accessToken, filter: 'comment' }) + const body = await commands[0].getAdminList({ filter: 'comment' }) - expect(res.body.total).to.equal(1) - expect(res.body.data).to.have.lengthOf(1) + expect(body.total).to.equal(1) + expect(body.data).to.have.lengthOf(1) - const abuse: AdminAbuse = res.body.data[0] + const abuse = body.data[0] expect(abuse.reason).to.equal('it is a bad comment') expect(abuse.reporterAccount.name).to.equal('root') @@ -485,9 +465,9 @@ describe('Test abuses', function () { } { - const res = await getAdminAbusesList({ url: servers[1].url, token: servers[1].accessToken, filter: 'comment' }) - expect(res.body.total).to.equal(0) - expect(res.body.data.length).to.equal(0) + const body = await commands[1].getAdminList({ filter: 'comment' }) + expect(body.total).to.equal(0) + expect(body.data.length).to.equal(0) } }) @@ -497,7 +477,7 @@ describe('Test abuses', function () { const comment = await getComment(servers[0].url, servers[1].video.uuid) const reason = 'it is a really bad comment' - await reportAbuse({ url: servers[0].url, token: servers[0].accessToken, commentId: comment.id, reason }) + await commands[0].report({ commentId: comment.id, reason }) await waitJobs(servers) }) @@ -505,54 +485,58 @@ describe('Test abuses', function () { it('Should have 2 comment abuses on server 1 and 1 on server 2', async function () { const commentServer2 = await getComment(servers[0].url, servers[1].video.id) - const res1 = await getAdminAbusesList({ url: servers[0].url, token: servers[0].accessToken, filter: 'comment' }) - expect(res1.body.total).to.equal(2) - expect(res1.body.data.length).to.equal(2) + { + const body = await commands[0].getAdminList({ filter: 'comment' }) + expect(body.total).to.equal(2) + expect(body.data.length).to.equal(2) - const abuse: AdminAbuse = res1.body.data[0] - expect(abuse.reason).to.equal('it is a bad comment') - expect(abuse.countReportsForReporter).to.equal(6) - expect(abuse.countReportsForReportee).to.equal(5) + const abuse = body.data[0] + expect(abuse.reason).to.equal('it is a bad comment') + expect(abuse.countReportsForReporter).to.equal(6) + expect(abuse.countReportsForReportee).to.equal(5) - const abuse2: AdminAbuse = res1.body.data[1] + const abuse2 = body.data[1] - expect(abuse2.reason).to.equal('it is a really bad comment') + expect(abuse2.reason).to.equal('it is a really bad comment') - expect(abuse2.reporterAccount.name).to.equal('root') - expect(abuse2.reporterAccount.host).to.equal(servers[0].host) + expect(abuse2.reporterAccount.name).to.equal('root') + expect(abuse2.reporterAccount.host).to.equal(servers[0].host) - expect(abuse2.video).to.be.null + expect(abuse2.video).to.be.null - expect(abuse2.comment.deleted).to.be.false - expect(abuse2.comment.id).to.equal(commentServer2.id) - expect(abuse2.comment.text).to.equal(commentServer2.text) - expect(abuse2.comment.video.name).to.equal('server 2') - expect(abuse2.comment.video.uuid).to.equal(servers[1].video.uuid) + expect(abuse2.comment.deleted).to.be.false + expect(abuse2.comment.id).to.equal(commentServer2.id) + expect(abuse2.comment.text).to.equal(commentServer2.text) + expect(abuse2.comment.video.name).to.equal('server 2') + expect(abuse2.comment.video.uuid).to.equal(servers[1].video.uuid) - expect(abuse2.state.id).to.equal(AbuseState.PENDING) - expect(abuse2.state.label).to.equal('Pending') + expect(abuse2.state.id).to.equal(AbuseState.PENDING) + expect(abuse2.state.label).to.equal('Pending') - expect(abuse2.moderationComment).to.be.null + expect(abuse2.moderationComment).to.be.null - expect(abuse2.countReportsForReporter).to.equal(6) - expect(abuse2.countReportsForReportee).to.equal(2) + expect(abuse2.countReportsForReporter).to.equal(6) + expect(abuse2.countReportsForReportee).to.equal(2) + } - const res2 = await getAdminAbusesList({ url: servers[1].url, token: servers[1].accessToken, filter: 'comment' }) - expect(res2.body.total).to.equal(1) - expect(res2.body.data.length).to.equal(1) + { + const body = await commands[1].getAdminList({ filter: 'comment' }) + expect(body.total).to.equal(1) + expect(body.data.length).to.equal(1) - abuseServer2 = res2.body.data[0] - expect(abuseServer2.reason).to.equal('it is a really bad comment') - expect(abuseServer2.reporterAccount.name).to.equal('root') - expect(abuseServer2.reporterAccount.host).to.equal(servers[0].host) + abuseServer2 = body.data[0] + expect(abuseServer2.reason).to.equal('it is a really bad comment') + expect(abuseServer2.reporterAccount.name).to.equal('root') + expect(abuseServer2.reporterAccount.host).to.equal(servers[0].host) - expect(abuseServer2.state.id).to.equal(AbuseState.PENDING) - expect(abuseServer2.state.label).to.equal('Pending') + expect(abuseServer2.state.id).to.equal(AbuseState.PENDING) + expect(abuseServer2.state.label).to.equal('Pending') - expect(abuseServer2.moderationComment).to.be.null + expect(abuseServer2.moderationComment).to.be.null - expect(abuseServer2.countReportsForReporter).to.equal(1) - expect(abuseServer2.countReportsForReportee).to.equal(1) + expect(abuseServer2.countReportsForReporter).to.equal(1) + expect(abuseServer2.countReportsForReportee).to.equal(1) + } }) it('Should keep the comment abuse when deleting the comment', async function () { @@ -564,11 +548,11 @@ describe('Test abuses', function () { await waitJobs(servers) - const res = await getAdminAbusesList({ url: servers[0].url, token: servers[0].accessToken, filter: 'comment' }) - expect(res.body.total).to.equal(2) - expect(res.body.data).to.have.lengthOf(2) + const body = await commands[0].getAdminList({ filter: 'comment' }) + expect(body.total).to.equal(2) + expect(body.data).to.have.lengthOf(2) - const abuse = (res.body.data as AdminAbuse[]).find(a => a.comment?.id === commentServer2.id) + const abuse = body.data.find(a => a.comment?.id === commentServer2.id) expect(abuse).to.not.be.undefined expect(abuse.comment.text).to.be.empty @@ -579,53 +563,43 @@ describe('Test abuses', function () { it('Should delete the comment abuse', async function () { this.timeout(10000) - await deleteAbuse(servers[1].url, servers[1].accessToken, abuseServer2.id) + await commands[1].delete({ abuseId: abuseServer2.id }) await waitJobs(servers) { - const res = await getAdminAbusesList({ url: servers[1].url, token: servers[1].accessToken, filter: 'comment' }) - expect(res.body.total).to.equal(0) - expect(res.body.data.length).to.equal(0) + const body = await commands[1].getAdminList({ filter: 'comment' }) + expect(body.total).to.equal(0) + expect(body.data.length).to.equal(0) } { - const res = await getAdminAbusesList({ url: servers[0].url, token: servers[0].accessToken, filter: 'comment' }) - expect(res.body.total).to.equal(2) + const body = await commands[0].getAdminList({ filter: 'comment' }) + expect(body.total).to.equal(2) } }) it('Should list and filter video abuses', async function () { { - const res = await getAdminAbusesList({ - url: servers[0].url, - token: servers[0].accessToken, - filter: 'comment', - searchReportee: 'foo' - }) - expect(res.body.total).to.equal(0) + const body = await commands[0].getAdminList({ filter: 'comment', searchReportee: 'foo' }) + expect(body.total).to.equal(0) } { - const res = await getAdminAbusesList({ - url: servers[0].url, - token: servers[0].accessToken, - filter: 'comment', - searchReportee: 'ot' - }) - expect(res.body.total).to.equal(2) + const body = await commands[0].getAdminList({ filter: 'comment', searchReportee: 'ot' }) + expect(body.total).to.equal(2) } { - const baseParams = { url: servers[0].url, token: servers[0].accessToken, filter: 'comment' as AbuseFilter, start: 1, count: 1 } - - const res1 = await getAdminAbusesList(immutableAssign(baseParams, { sort: 'createdAt' })) - expect(res1.body.data).to.have.lengthOf(1) - expect(res1.body.data[0].comment.text).to.be.empty + const body = await commands[0].getAdminList({ filter: 'comment', start: 1, count: 1, sort: 'createdAt' }) + expect(body.data).to.have.lengthOf(1) + expect(body.data[0].comment.text).to.be.empty + } - const res2 = await getAdminAbusesList(immutableAssign(baseParams, { sort: '-createdAt' })) - expect(res2.body.data).to.have.lengthOf(1) - expect(res2.body.data[0].comment.text).to.equal('comment server 1') + { + const body = await commands[0].getAdminList({ filter: 'comment', start: 1, count: 1, sort: '-createdAt' }) + expect(body.data).to.have.lengthOf(1) + expect(body.data[0].comment.text).to.equal('comment server 1') } }) }) @@ -655,19 +629,19 @@ describe('Test abuses', function () { const account = await getAccountFromServer(servers[0].url, 'user_1', servers[0]) const reason = 'it is a bad account' - await reportAbuse({ url: servers[0].url, token: servers[0].accessToken, accountId: account.id, reason }) + await commands[0].report({ accountId: account.id, reason }) await waitJobs(servers) }) it('Should have 1 account abuse on server 1 and 0 on server 2', async function () { { - const res = await getAdminAbusesList({ url: servers[0].url, token: servers[0].accessToken, filter: 'account' }) + const body = await commands[0].getAdminList({ filter: 'account' }) - expect(res.body.total).to.equal(1) - expect(res.body.data).to.have.lengthOf(1) + expect(body.total).to.equal(1) + expect(body.data).to.have.lengthOf(1) - const abuse: AdminAbuse = res.body.data[0] + const abuse = body.data[0] expect(abuse.reason).to.equal('it is a bad account') expect(abuse.reporterAccount.name).to.equal('root') @@ -681,9 +655,9 @@ describe('Test abuses', function () { } { - const res = await getAdminAbusesList({ url: servers[1].url, token: servers[1].accessToken, filter: 'comment' }) - expect(res.body.total).to.equal(0) - expect(res.body.data.length).to.equal(0) + const body = await commands[1].getAdminList({ filter: 'comment' }) + expect(body.total).to.equal(0) + expect(body.data.length).to.equal(0) } }) @@ -693,48 +667,52 @@ describe('Test abuses', function () { const account = await getAccountFromServer(servers[0].url, 'user_2', servers[1]) const reason = 'it is a really bad account' - await reportAbuse({ url: servers[0].url, token: servers[0].accessToken, accountId: account.id, reason }) + await commands[0].report({ accountId: account.id, reason }) await waitJobs(servers) }) it('Should have 2 comment abuses on server 1 and 1 on server 2', async function () { - const res1 = await getAdminAbusesList({ url: servers[0].url, token: servers[0].accessToken, filter: 'account' }) - expect(res1.body.total).to.equal(2) - expect(res1.body.data.length).to.equal(2) + { + const body = await commands[0].getAdminList({ filter: 'account' }) + expect(body.total).to.equal(2) + expect(body.data.length).to.equal(2) - const abuse: AdminAbuse = res1.body.data[0] - expect(abuse.reason).to.equal('it is a bad account') + const abuse: AdminAbuse = body.data[0] + expect(abuse.reason).to.equal('it is a bad account') - const abuse2: AdminAbuse = res1.body.data[1] - expect(abuse2.reason).to.equal('it is a really bad account') + const abuse2: AdminAbuse = body.data[1] + expect(abuse2.reason).to.equal('it is a really bad account') - expect(abuse2.reporterAccount.name).to.equal('root') - expect(abuse2.reporterAccount.host).to.equal(servers[0].host) + expect(abuse2.reporterAccount.name).to.equal('root') + expect(abuse2.reporterAccount.host).to.equal(servers[0].host) - expect(abuse2.video).to.be.null - expect(abuse2.comment).to.be.null + expect(abuse2.video).to.be.null + expect(abuse2.comment).to.be.null - expect(abuse2.state.id).to.equal(AbuseState.PENDING) - expect(abuse2.state.label).to.equal('Pending') + expect(abuse2.state.id).to.equal(AbuseState.PENDING) + expect(abuse2.state.label).to.equal('Pending') - expect(abuse2.moderationComment).to.be.null + expect(abuse2.moderationComment).to.be.null + } - const res2 = await getAdminAbusesList({ url: servers[1].url, token: servers[1].accessToken, filter: 'account' }) - expect(res2.body.total).to.equal(1) - expect(res2.body.data.length).to.equal(1) + { + const body = await commands[1].getAdminList({ filter: 'account' }) + expect(body.total).to.equal(1) + expect(body.data.length).to.equal(1) - abuseServer2 = res2.body.data[0] + abuseServer2 = body.data[0] - expect(abuseServer2.reason).to.equal('it is a really bad account') + expect(abuseServer2.reason).to.equal('it is a really bad account') - expect(abuseServer2.reporterAccount.name).to.equal('root') - expect(abuseServer2.reporterAccount.host).to.equal(servers[0].host) + expect(abuseServer2.reporterAccount.name).to.equal('root') + expect(abuseServer2.reporterAccount.host).to.equal(servers[0].host) - expect(abuseServer2.state.id).to.equal(AbuseState.PENDING) - expect(abuseServer2.state.label).to.equal('Pending') + expect(abuseServer2.state.id).to.equal(AbuseState.PENDING) + expect(abuseServer2.state.label).to.equal('Pending') - expect(abuseServer2.moderationComment).to.be.null + expect(abuseServer2.moderationComment).to.be.null + } }) it('Should keep the account abuse when deleting the account', async function () { @@ -745,32 +723,32 @@ describe('Test abuses', function () { await waitJobs(servers) - const res = await getAdminAbusesList({ url: servers[0].url, token: servers[0].accessToken, filter: 'account' }) - expect(res.body.total).to.equal(2) - expect(res.body.data).to.have.lengthOf(2) + const body = await commands[0].getAdminList({ filter: 'account' }) + expect(body.total).to.equal(2) + expect(body.data).to.have.lengthOf(2) - const abuse = (res.body.data as AdminAbuse[]).find(a => a.reason === 'it is a really bad account') + const abuse = body.data.find(a => a.reason === 'it is a really bad account') expect(abuse).to.not.be.undefined }) it('Should delete the account abuse', async function () { this.timeout(10000) - await deleteAbuse(servers[1].url, servers[1].accessToken, abuseServer2.id) + await commands[1].delete({ abuseId: abuseServer2.id }) await waitJobs(servers) { - const res = await getAdminAbusesList({ url: servers[1].url, token: servers[1].accessToken, filter: 'account' }) - expect(res.body.total).to.equal(0) - expect(res.body.data.length).to.equal(0) + const body = await commands[1].getAdminList({ filter: 'account' }) + expect(body.total).to.equal(0) + expect(body.data.length).to.equal(0) } { - const res = await getAdminAbusesList({ url: servers[0].url, token: servers[0].accessToken, filter: 'account' }) - expect(res.body.total).to.equal(2) + const body = await commands[0].getAdminList({ filter: 'account' }) + expect(body.total).to.equal(2) - abuseServer1 = res.body.data[0] + abuseServer1 = body.data[0] } }) }) @@ -778,20 +756,18 @@ describe('Test abuses', function () { describe('Common actions on abuses', function () { it('Should update the state of an abuse', async function () { - const body = { state: AbuseState.REJECTED } - await updateAbuse(servers[0].url, servers[0].accessToken, abuseServer1.id, body) + await commands[0].update({ abuseId: abuseServer1.id, body: { state: AbuseState.REJECTED } }) - const res = await getAdminAbusesList({ url: servers[0].url, token: servers[0].accessToken, id: abuseServer1.id }) - expect(res.body.data[0].state.id).to.equal(AbuseState.REJECTED) + const body = await commands[0].getAdminList({ id: abuseServer1.id }) + expect(body.data[0].state.id).to.equal(AbuseState.REJECTED) }) it('Should add a moderation comment', async function () { - const body = { state: AbuseState.ACCEPTED, moderationComment: 'It is valid' } - await updateAbuse(servers[0].url, servers[0].accessToken, abuseServer1.id, body) + await commands[0].update({ abuseId: abuseServer1.id, body: { state: AbuseState.ACCEPTED, moderationComment: 'Valid' } }) - const res = await getAdminAbusesList({ url: servers[0].url, token: servers[0].accessToken, id: abuseServer1.id }) - expect(res.body.data[0].state.id).to.equal(AbuseState.ACCEPTED) - expect(res.body.data[0].moderationComment).to.equal('It is valid') + const body = await commands[0].getAdminList({ id: abuseServer1.id }) + expect(body.data[0].state.id).to.equal(AbuseState.ACCEPTED) + expect(body.data[0].moderationComment).to.equal('Valid') }) }) @@ -802,18 +778,18 @@ describe('Test abuses', function () { before(async function () { userAccessToken = await generateUserAccessToken(servers[0], 'user_42') - await reportAbuse({ url: servers[0].url, token: userAccessToken, videoId: servers[0].video.id, reason: 'user reason 1' }) + await commands[0].report({ token: userAccessToken, videoId: servers[0].video.id, reason: 'user reason 1' }) const videoId = await getVideoIdFromUUID(servers[0].url, servers[1].video.uuid) - await reportAbuse({ url: servers[0].url, token: userAccessToken, videoId, reason: 'user reason 2' }) + await commands[0].report({ token: userAccessToken, videoId, reason: 'user reason 2' }) }) it('Should correctly list my abuses', async function () { { - const res = await getUserAbusesList({ url: servers[0].url, token: userAccessToken, start: 0, count: 5, sort: 'createdAt' }) - expect(res.body.total).to.equal(2) + const body = await commands[0].getUserList({ token: userAccessToken, start: 0, count: 5, sort: 'createdAt' }) + expect(body.total).to.equal(2) - const abuses: UserAbuse[] = res.body.data + const abuses = body.data expect(abuses[0].reason).to.equal('user reason 1') expect(abuses[1].reason).to.equal('user reason 2') @@ -821,95 +797,77 @@ describe('Test abuses', function () { } { - const res = await getUserAbusesList({ url: servers[0].url, token: userAccessToken, start: 1, count: 1, sort: 'createdAt' }) - expect(res.body.total).to.equal(2) + const body = await commands[0].getUserList({ token: userAccessToken, start: 1, count: 1, sort: 'createdAt' }) + expect(body.total).to.equal(2) - const abuses: UserAbuse[] = res.body.data + const abuses: UserAbuse[] = body.data expect(abuses[0].reason).to.equal('user reason 2') } { - const res = await getUserAbusesList({ url: servers[0].url, token: userAccessToken, start: 1, count: 1, sort: '-createdAt' }) - expect(res.body.total).to.equal(2) + const body = await commands[0].getUserList({ token: userAccessToken, start: 1, count: 1, sort: '-createdAt' }) + expect(body.total).to.equal(2) - const abuses: UserAbuse[] = res.body.data + const abuses: UserAbuse[] = body.data expect(abuses[0].reason).to.equal('user reason 1') } }) it('Should correctly filter my abuses by id', async function () { - const res = await getUserAbusesList({ url: servers[0].url, token: userAccessToken, id: abuseId1 }) - - expect(res.body.total).to.equal(1) + const body = await commands[0].getUserList({ token: userAccessToken, id: abuseId1 }) + expect(body.total).to.equal(1) - const abuses: UserAbuse[] = res.body.data + const abuses: UserAbuse[] = body.data expect(abuses[0].reason).to.equal('user reason 1') }) it('Should correctly filter my abuses by search', async function () { - const res = await getUserAbusesList({ - url: servers[0].url, - token: userAccessToken, - search: 'server 2' - }) - - expect(res.body.total).to.equal(1) + const body = await commands[0].getUserList({ token: userAccessToken, search: 'server 2' }) + expect(body.total).to.equal(1) - const abuses: UserAbuse[] = res.body.data + const abuses: UserAbuse[] = body.data expect(abuses[0].reason).to.equal('user reason 2') }) it('Should correctly filter my abuses by state', async function () { - const body = { state: AbuseState.REJECTED } - await updateAbuse(servers[0].url, servers[0].accessToken, abuseId1, body) - - const res = await getUserAbusesList({ - url: servers[0].url, - token: userAccessToken, - state: AbuseState.REJECTED - }) + await commands[0].update({ abuseId: abuseId1, body: { state: AbuseState.REJECTED } }) - expect(res.body.total).to.equal(1) + const body = await commands[0].getUserList({ token: userAccessToken, state: AbuseState.REJECTED }) + expect(body.total).to.equal(1) - const abuses: UserAbuse[] = res.body.data + const abuses: UserAbuse[] = body.data expect(abuses[0].reason).to.equal('user reason 1') }) }) describe('Abuse messages', async function () { let abuseId: number - let userAccessToken: string + let userToken: string let abuseMessageUserId: number let abuseMessageModerationId: number before(async function () { - userAccessToken = await generateUserAccessToken(servers[0], 'user_43') - - const res = await reportAbuse({ - url: servers[0].url, - token: userAccessToken, - videoId: servers[0].video.id, - reason: 'user 43 reason 1' - }) + userToken = await generateUserAccessToken(servers[0], 'user_43') - abuseId = res.body.abuse.id + const body = await commands[0].report({ token: userToken, videoId: servers[0].video.id, reason: 'user 43 reason 1' }) + abuseId = body.abuse.id }) it('Should create some messages on the abuse', async function () { - await addAbuseMessage(servers[0].url, userAccessToken, abuseId, 'message 1') - await addAbuseMessage(servers[0].url, servers[0].accessToken, abuseId, 'message 2') - await addAbuseMessage(servers[0].url, servers[0].accessToken, abuseId, 'message 3') - await addAbuseMessage(servers[0].url, userAccessToken, abuseId, 'message 4') + await commands[0].addMessage({ token: userToken, abuseId, message: 'message 1' }) + await commands[0].addMessage({ abuseId, message: 'message 2' }) + await commands[0].addMessage({ abuseId, message: 'message 3' }) + await commands[0].addMessage({ token: userToken, abuseId, message: 'message 4' }) }) it('Should have the correct messages count when listing abuses', async function () { const results = await Promise.all([ - getAdminAbusesList({ url: servers[0].url, token: servers[0].accessToken, start: 0, count: 50 }), - getUserAbusesList({ url: servers[0].url, token: userAccessToken, start: 0, count: 50 }) + commands[0].getAdminList({ start: 0, count: 50 }), + commands[0].getUserList({ token: userToken, start: 0, count: 50 }) ]) - for (const res of results) { - const abuses: AdminAbuse[] = res.body.data + for (const body of results) { + const abuses = body.data const abuse = abuses.find(a => a.id === abuseId) expect(abuse.countMessages).to.equal(4) } @@ -917,14 +875,14 @@ describe('Test abuses', function () { it('Should correctly list messages of this abuse', async function () { const results = await Promise.all([ - listAbuseMessages(servers[0].url, servers[0].accessToken, abuseId), - listAbuseMessages(servers[0].url, userAccessToken, abuseId) + commands[0].listMessages({ abuseId }), + commands[0].listMessages({ token: userToken, abuseId }) ]) - for (const res of results) { - expect(res.body.total).to.equal(4) + for (const body of results) { + expect(body.total).to.equal(4) - const abuseMessages: AbuseMessage[] = res.body.data + const abuseMessages: AbuseMessage[] = body.data expect(abuseMessages[0].message).to.equal('message 1') expect(abuseMessages[0].byModerator).to.be.false @@ -948,19 +906,18 @@ describe('Test abuses', function () { }) it('Should delete messages', async function () { - await deleteAbuseMessage(servers[0].url, servers[0].accessToken, abuseId, abuseMessageModerationId) - await deleteAbuseMessage(servers[0].url, userAccessToken, abuseId, abuseMessageUserId) + await commands[0].deleteMessage({ abuseId, messageId: abuseMessageModerationId }) + await commands[0].deleteMessage({ token: userToken, abuseId, messageId: abuseMessageUserId }) const results = await Promise.all([ - listAbuseMessages(servers[0].url, servers[0].accessToken, abuseId), - listAbuseMessages(servers[0].url, userAccessToken, abuseId) + commands[0].listMessages({ abuseId }), + commands[0].listMessages({ token: userToken, abuseId }) ]) - for (const res of results) { - expect(res.body.total).to.equal(2) - - const abuseMessages: AbuseMessage[] = res.body.data + for (const body of results) { + expect(body.total).to.equal(2) + const abuseMessages: AbuseMessage[] = body.data expect(abuseMessages[0].message).to.equal('message 2') expect(abuseMessages[1].message).to.equal('message 4') } diff --git a/server/tests/api/notifications/moderation-notifications.ts b/server/tests/api/notifications/moderation-notifications.ts index a7671696f..f77719c68 100644 --- a/server/tests/api/notifications/moderation-notifications.ts +++ b/server/tests/api/notifications/moderation-notifications.ts @@ -2,11 +2,23 @@ import 'mocha' import { buildUUID } from '@server/helpers/uuid' -import { AbuseState } from '@shared/models' import { - addAbuseMessage, + addUserSubscription, addVideoCommentThread, addVideoToBlacklist, + checkAbuseStateChange, + checkAutoInstanceFollowing, + CheckerBaseParams, + checkNewAbuseMessage, + checkNewAccountAbuseForModerators, + checkNewBlacklistOnMyVideo, + checkNewCommentAbuseForModerators, + checkNewInstanceFollower, + checkNewVideoAbuseForModerators, + checkNewVideoFromSubscription, + checkUserRegistered, + checkVideoAutoBlacklistForModerators, + checkVideoIsPublished, cleanupTests, createUser, follow, @@ -17,38 +29,20 @@ import { getVideoIdFromUUID, immutableAssign, MockInstancesIndex, + MockSmtpServer, + prepareNotificationsTest, registerUser, + removeUserSubscription, removeVideoFromBlacklist, - reportAbuse, + ServerInfo, unfollow, - updateAbuse, updateCustomConfig, updateCustomSubConfig, - wait -} from '../../../../shared/extra-utils' -import { ServerInfo, uploadVideo } from '../../../../shared/extra-utils/index' -import { MockSmtpServer } from '../../../../shared/extra-utils/mock-servers/mock-email' -import { waitJobs } from '../../../../shared/extra-utils/server/jobs' -import { - checkAbuseStateChange, - checkAutoInstanceFollowing, - CheckerBaseParams, - checkNewAbuseMessage, - checkNewAccountAbuseForModerators, - checkNewBlacklistOnMyVideo, - checkNewCommentAbuseForModerators, - checkNewInstanceFollower, - checkNewVideoAbuseForModerators, - checkNewVideoFromSubscription, - checkUserRegistered, - checkVideoAutoBlacklistForModerators, - checkVideoIsPublished, - prepareNotificationsTest -} from '../../../../shared/extra-utils/users/user-notifications' -import { addUserSubscription, removeUserSubscription } from '../../../../shared/extra-utils/users/user-subscriptions' -import { CustomConfig } from '../../../../shared/models/server' -import { UserNotification } from '../../../../shared/models/users' -import { VideoPrivacy } from '../../../../shared/models/videos' + uploadVideo, + wait, + waitJobs +} from '@shared/extra-utils' +import { AbuseState, CustomConfig, UserNotification, VideoPrivacy } from '@shared/models' describe('Test moderation notifications', function () { let servers: ServerInfo[] = [] @@ -89,7 +83,7 @@ describe('Test moderation notifications', function () { const resVideo = await uploadVideo(servers[0].url, userAccessToken, { name }) const video = resVideo.body.video - await reportAbuse({ url: servers[0].url, token: servers[0].accessToken, videoId: video.id, reason: 'super reason' }) + await servers[0].abusesCommand.report({ videoId: video.id, reason: 'super reason' }) await waitJobs(servers) await checkNewVideoAbuseForModerators(baseParams, video.uuid, name, 'presence') @@ -105,7 +99,7 @@ describe('Test moderation notifications', function () { await waitJobs(servers) const videoId = await getVideoIdFromUUID(servers[1].url, video.uuid) - await reportAbuse({ url: servers[1].url, token: servers[1].accessToken, videoId, reason: 'super reason' }) + await servers[1].abusesCommand.report({ videoId, reason: 'super reason' }) await waitJobs(servers) await checkNewVideoAbuseForModerators(baseParams, video.uuid, name, 'presence') @@ -122,7 +116,7 @@ describe('Test moderation notifications', function () { await waitJobs(servers) - await reportAbuse({ url: servers[0].url, token: servers[0].accessToken, commentId: comment.id, reason: 'super reason' }) + await servers[0].abusesCommand.report({ commentId: comment.id, reason: 'super reason' }) await waitJobs(servers) await checkNewCommentAbuseForModerators(baseParams, video.uuid, name, 'presence') @@ -140,7 +134,7 @@ describe('Test moderation notifications', function () { const resComments = await getVideoCommentThreads(servers[1].url, video.uuid, 0, 5) const commentId = resComments.body.data[0].id - await reportAbuse({ url: servers[1].url, token: servers[1].accessToken, commentId, reason: 'super reason' }) + await servers[1].abusesCommand.report({ commentId, reason: 'super reason' }) await waitJobs(servers) await checkNewCommentAbuseForModerators(baseParams, video.uuid, name, 'presence') @@ -153,7 +147,7 @@ describe('Test moderation notifications', function () { const resUser = await createUser({ url: servers[0].url, accessToken: servers[0].accessToken, username, password: 'donald' }) const accountId = resUser.body.user.account.id - await reportAbuse({ url: servers[0].url, token: servers[0].accessToken, accountId, reason: 'super reason' }) + await servers[0].abusesCommand.report({ accountId, reason: 'super reason' }) await waitJobs(servers) await checkNewAccountAbuseForModerators(baseParams, username, 'presence') @@ -169,7 +163,7 @@ describe('Test moderation notifications', function () { await waitJobs(servers) const resAccount = await getAccount(servers[1].url, username + '@' + servers[0].host) - await reportAbuse({ url: servers[1].url, token: servers[1].accessToken, accountId: resAccount.body.id, reason: 'super reason' }) + await servers[1].abusesCommand.report({ accountId: resAccount.body.id, reason: 'super reason' }) await waitJobs(servers) await checkNewAccountAbuseForModerators(baseParams, username, 'presence') @@ -192,14 +186,14 @@ describe('Test moderation notifications', function () { const resVideo = await uploadVideo(servers[0].url, userAccessToken, { name }) const video = resVideo.body.video - const res = await reportAbuse({ url: servers[0].url, token: userAccessToken, videoId: video.id, reason: 'super reason' }) - abuseId = res.body.abuse.id + const body = await servers[0].abusesCommand.report({ token: userAccessToken, videoId: video.id, reason: 'super reason' }) + abuseId = body.abuse.id }) it('Should send a notification to reporter if the abuse has been accepted', async function () { this.timeout(10000) - await updateAbuse(servers[0].url, servers[0].accessToken, abuseId, { state: AbuseState.ACCEPTED }) + await servers[0].abusesCommand.update({ abuseId, body: { state: AbuseState.ACCEPTED } }) await waitJobs(servers) await checkAbuseStateChange(baseParams, abuseId, AbuseState.ACCEPTED, 'presence') @@ -208,7 +202,7 @@ describe('Test moderation notifications', function () { it('Should send a notification to reporter if the abuse has been rejected', async function () { this.timeout(10000) - await updateAbuse(servers[0].url, servers[0].accessToken, abuseId, { state: AbuseState.REJECTED }) + await servers[0].abusesCommand.update({ abuseId, body: { state: AbuseState.REJECTED } }) await waitJobs(servers) await checkAbuseStateChange(baseParams, abuseId, AbuseState.REJECTED, 'presence') @@ -241,13 +235,13 @@ describe('Test moderation notifications', function () { const video = resVideo.body.video { - const res = await reportAbuse({ url: servers[0].url, token: userAccessToken, videoId: video.id, reason: 'super reason' }) - abuseId = res.body.abuse.id + const body = await servers[0].abusesCommand.report({ token: userAccessToken, videoId: video.id, reason: 'super reason' }) + abuseId = body.abuse.id } { - const res = await reportAbuse({ url: servers[0].url, token: userAccessToken, videoId: video.id, reason: 'super reason 2' }) - abuseId2 = res.body.abuse.id + const body = await servers[0].abusesCommand.report({ token: userAccessToken, videoId: video.id, reason: 'super reason 2' }) + abuseId2 = body.abuse.id } }) @@ -255,7 +249,7 @@ describe('Test moderation notifications', function () { this.timeout(10000) const message = 'my super message to users' - await addAbuseMessage(servers[0].url, servers[0].accessToken, abuseId, message) + await servers[0].abusesCommand.addMessage({ abuseId, message }) await waitJobs(servers) await checkNewAbuseMessage(baseParamsUser, abuseId, message, 'user_1@example.com', 'presence') @@ -265,7 +259,7 @@ describe('Test moderation notifications', function () { this.timeout(10000) const message = 'my super message that should not be sent to the admin' - await addAbuseMessage(servers[0].url, servers[0].accessToken, abuseId, message) + await servers[0].abusesCommand.addMessage({ abuseId, message }) await waitJobs(servers) await checkNewAbuseMessage(baseParamsAdmin, abuseId, message, 'admin' + servers[0].internalServerNumber + '@example.com', 'absence') @@ -275,7 +269,7 @@ describe('Test moderation notifications', function () { this.timeout(10000) const message = 'my super message to moderators' - await addAbuseMessage(servers[0].url, userAccessToken, abuseId2, message) + await servers[0].abusesCommand.addMessage({ token: userAccessToken, abuseId: abuseId2, message }) await waitJobs(servers) await checkNewAbuseMessage(baseParamsAdmin, abuseId2, message, 'admin' + servers[0].internalServerNumber + '@example.com', 'presence') @@ -285,7 +279,7 @@ describe('Test moderation notifications', function () { this.timeout(10000) const message = 'my super message that should not be sent to reporter' - await addAbuseMessage(servers[0].url, userAccessToken, abuseId2, message) + await servers[0].abusesCommand.addMessage({ token: userAccessToken, abuseId: abuseId2, message }) await waitJobs(servers) await checkNewAbuseMessage(baseParamsUser, abuseId2, message, 'user_1@example.com', 'absence') diff --git a/server/tests/api/server/email.ts b/server/tests/api/server/email.ts index 41071692a..85844ae9d 100644 --- a/server/tests/api/server/email.ts +++ b/server/tests/api/server/email.ts @@ -12,7 +12,6 @@ import { createUser, flushAndRunServer, removeVideoFromBlacklist, - reportAbuse, resetPassword, ServerInfo, setAccessTokensToServers, @@ -190,7 +189,7 @@ describe('Test emails', function () { this.timeout(10000) const reason = 'my super bad reason' - await reportAbuse({ url: server.url, token: server.accessToken, videoId, reason }) + await server.abusesCommand.report({ videoId, reason }) await waitJobs(server) expect(emails).to.have.lengthOf(3) diff --git a/server/tests/api/users/users.ts b/server/tests/api/users/users.ts index 87ba775f6..6bfc7cfe5 100644 --- a/server/tests/api/users/users.ts +++ b/server/tests/api/users/users.ts @@ -2,9 +2,7 @@ import 'mocha' import * as chai from 'chai' -import { AbuseState, AbuseUpdate, MyUser, User, UserRole, Video, VideoPlaylistType } from '@shared/models' -import { CustomConfig, OAuth2ErrorCode } from '@shared/models/server' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '@shared/core-utils' import { addVideoCommentThread, blockUser, @@ -13,13 +11,14 @@ import { createUser, deleteMe, flushAndRunServer, + follow, getAccountRatings, - getAdminAbusesList, getBlacklistedVideosList, getCustomConfig, getMyUserInformation, getMyUserVideoQuotaUsed, getMyUserVideoRating, + getMyVideos, getUserInformation, getUsersList, getUsersListPaginationAndSort, @@ -28,18 +27,19 @@ import { installPlugin, killallServers, login, + logout, makePutBodyRequest, rateVideo, + refreshToken, registerUserWithChannel, removeUser, removeVideo, - reportAbuse, reRunServer, ServerInfo, + setAccessTokensToServers, setTokenField, testImage, unblockUser, - updateAbuse, updateCustomSubConfig, updateMyAvatar, updateMyUser, @@ -47,11 +47,8 @@ import { uploadVideo, userLogin, waitJobs -} from '../../../../shared/extra-utils' -import { follow } from '../../../../shared/extra-utils/server/follows' -import { logout, refreshToken, setAccessTokensToServers } from '../../../../shared/extra-utils/users/login' -import { getMyVideos } from '../../../../shared/extra-utils/videos/videos' -import { UserAdminFlag } from '../../../../shared/models/users/user-flag.model' +} from '@shared/extra-utils' +import { AbuseState, CustomConfig, MyUser, OAuth2ErrorCode, User, UserAdminFlag, UserRole, Video, VideoPlaylistType } from '@shared/models' const expect = chai.expect @@ -1002,10 +999,10 @@ describe('Test users', function () { it('Should report correct abuses counts', async function () { const reason = 'my super bad reason' - await reportAbuse({ url: server.url, token: user17AccessToken, videoId, reason }) + await server.abusesCommand.report({ token: user17AccessToken, videoId, reason }) - const res1 = await getAdminAbusesList({ url: server.url, token: server.accessToken }) - const abuseId = res1.body.data[0].id + const body1 = await server.abusesCommand.getAdminList() + const abuseId = body1.data[0].id const res2 = await getUserInformation(server.url, server.accessToken, user17Id, true) const user2: User = res2.body @@ -1013,8 +1010,7 @@ describe('Test users', function () { expect(user2.abusesCount).to.equal(1) // number of incriminations expect(user2.abusesCreatedCount).to.equal(1) // number of reports created - const body: AbuseUpdate = { state: AbuseState.ACCEPTED } - await updateAbuse(server.url, server.accessToken, abuseId, body) + await server.abusesCommand.update({ abuseId, body: { state: AbuseState.ACCEPTED } }) const res3 = await getUserInformation(server.url, server.accessToken, user17Id, true) const user3: User = res3.body diff --git a/shared/extra-utils/index.ts b/shared/extra-utils/index.ts index 7d2887209..bde269052 100644 --- a/shared/extra-utils/index.ts +++ b/shared/extra-utils/index.ts @@ -5,8 +5,8 @@ export * from './feeds' export * from './logs' export * from './miscs' export * from './mock-servers' +export * from './moderation' -export * from './moderation/abuses' export * from './plugins/mock-blocklist' export * from './requests/check-api-params' diff --git a/shared/extra-utils/moderation/abuses-command.ts b/shared/extra-utils/moderation/abuses-command.ts new file mode 100644 index 000000000..59126d0a9 --- /dev/null +++ b/shared/extra-utils/moderation/abuses-command.ts @@ -0,0 +1,205 @@ +import { pick } from 'lodash' +import { + AbuseFilter, + AbuseMessage, + AbusePredefinedReasonsString, + AbuseState, + AbuseUpdate, + AbuseVideoIs, + AdminAbuse, + ResultList, + UserAbuse +} from '@shared/models' +import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' +import { AbstractCommand, OverrideCommandOptions } from '../shared' +import { unwrapBody } from '../requests/requests' + +export class AbusesCommand extends AbstractCommand { + + report (options: OverrideCommandOptions & { + reason: string + + accountId?: number + videoId?: number + commentId?: number + + predefinedReasons?: AbusePredefinedReasonsString[] + + startAt?: number + endAt?: number + }) { + const path = '/api/v1/abuses' + + const video = options.videoId + ? { + id: options.videoId, + startAt: options.startAt, + endAt: options.endAt + } + : undefined + + const comment = options.commentId + ? { id: options.commentId } + : undefined + + const account = options.accountId + ? { id: options.accountId } + : undefined + + const body = { + account, + video, + comment, + + reason: options.reason, + predefinedReasons: options.predefinedReasons + } + + return unwrapBody<{ abuse: { id: number } }>(this.postBodyRequest({ + ...options, + + path, + fields: body, + defaultExpectedStatus: HttpStatusCode.OK_200 + })) + } + + getAdminList (options: OverrideCommandOptions & { + start?: number + count?: number + sort?: string + + id?: number + predefinedReason?: AbusePredefinedReasonsString + search?: string + filter?: AbuseFilter + state?: AbuseState + videoIs?: AbuseVideoIs + searchReporter?: string + searchReportee?: string + searchVideo?: string + searchVideoChannel?: string + } = {}) { + const toPick = [ + 'count', + 'filter', + 'id', + 'predefinedReason', + 'search', + 'searchReportee', + 'searchReporter', + 'searchVideo', + 'searchVideoChannel', + 'sort', + 'start', + 'state', + 'videoIs' + ] + + const path = '/api/v1/abuses' + + const defaultQuery = { sort: 'createdAt' } + const query = { ...defaultQuery, ...pick(options, toPick) } + + return this.getRequestBody>({ + ...options, + + path, + query, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } + + getUserList (options: OverrideCommandOptions & { + start?: number + count?: number + sort?: string + + id?: number + search?: string + state?: AbuseState + }) { + const toPick = [ + 'id', + 'search', + 'state', + 'start', + 'count', + 'sort' + ] + + const path = '/api/v1/users/me/abuses' + + const defaultQuery = { sort: 'createdAt' } + const query = { ...defaultQuery, ...pick(options, toPick) } + + return this.getRequestBody>({ + ...options, + + path, + query, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } + + update (options: OverrideCommandOptions & { + abuseId: number + body: AbuseUpdate + }) { + const { abuseId, body } = options + const path = '/api/v1/abuses/' + abuseId + + return this.putBodyRequest({ + ...options, + + path, + fields: body, + defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 + }) + } + + delete (options: OverrideCommandOptions & { + abuseId: number + }) { + const { abuseId } = options + const path = '/api/v1/abuses/' + abuseId + + return this.deleteRequest({ ...options, path, defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 }) + } + + listMessages (options: OverrideCommandOptions & { + abuseId: number + }) { + const { abuseId } = options + const path = '/api/v1/abuses/' + abuseId + '/messages' + + return this.getRequestBody>({ ...options, path, defaultExpectedStatus: HttpStatusCode.OK_200 }) + } + + deleteMessage (options: OverrideCommandOptions & { + abuseId: number + messageId: number + }) { + const { abuseId, messageId } = options + const path = '/api/v1/abuses/' + abuseId + '/messages/' + messageId + + return this.deleteRequest({ ...options, path, defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 }) + } + + addMessage (options: OverrideCommandOptions & { + abuseId: number + message: string + }) { + const { abuseId, message } = options + const path = '/api/v1/abuses/' + abuseId + '/messages' + + return this.postBodyRequest({ + ...options, + + path, + fields: { message }, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } + +} diff --git a/shared/extra-utils/moderation/abuses.ts b/shared/extra-utils/moderation/abuses.ts deleted file mode 100644 index c0fda722f..000000000 --- a/shared/extra-utils/moderation/abuses.ts +++ /dev/null @@ -1,244 +0,0 @@ -import { AbuseFilter, AbusePredefinedReasonsString, AbuseState, AbuseUpdate, AbuseVideoIs } from '@shared/models' -import { makeDeleteRequest, makeGetRequest, makePostBodyRequest, makePutBodyRequest } from '../requests/requests' -import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' - -function reportAbuse (options: { - url: string - token: string - - reason: string - - accountId?: number - videoId?: number - commentId?: number - - predefinedReasons?: AbusePredefinedReasonsString[] - - startAt?: number - endAt?: number - - statusCodeExpected?: number -}) { - const path = '/api/v1/abuses' - - const video = options.videoId - ? { - id: options.videoId, - startAt: options.startAt, - endAt: options.endAt - } - : undefined - - const comment = options.commentId - ? { id: options.commentId } - : undefined - - const account = options.accountId - ? { id: options.accountId } - : undefined - - const body = { - account, - video, - comment, - - reason: options.reason, - predefinedReasons: options.predefinedReasons - } - - return makePostBodyRequest({ - url: options.url, - path, - token: options.token, - - fields: body, - statusCodeExpected: options.statusCodeExpected || HttpStatusCode.OK_200 - }) -} - -function getAdminAbusesList (options: { - url: string - token: string - - start?: number - count?: number - sort?: string - - id?: number - predefinedReason?: AbusePredefinedReasonsString - search?: string - filter?: AbuseFilter - state?: AbuseState - videoIs?: AbuseVideoIs - searchReporter?: string - searchReportee?: string - searchVideo?: string - searchVideoChannel?: string -}) { - const { - url, - token, - start, - count, - sort, - id, - predefinedReason, - search, - filter, - state, - videoIs, - searchReporter, - searchReportee, - searchVideo, - searchVideoChannel - } = options - const path = '/api/v1/abuses' - - const query = { - id, - predefinedReason, - search, - state, - filter, - videoIs, - start, - count, - sort: sort || 'createdAt', - searchReporter, - searchReportee, - searchVideo, - searchVideoChannel - } - - return makeGetRequest({ - url, - path, - token, - query, - statusCodeExpected: HttpStatusCode.OK_200 - }) -} - -function getUserAbusesList (options: { - url: string - token: string - - start?: number - count?: number - sort?: string - - id?: number - search?: string - state?: AbuseState -}) { - const { - url, - token, - start, - count, - sort, - id, - search, - state - } = options - const path = '/api/v1/users/me/abuses' - - const query = { - id, - search, - state, - start, - count, - sort: sort || 'createdAt' - } - - return makeGetRequest({ - url, - path, - token, - query, - statusCodeExpected: HttpStatusCode.OK_200 - }) -} - -function updateAbuse ( - url: string, - token: string, - abuseId: number, - body: AbuseUpdate, - statusCodeExpected = HttpStatusCode.NO_CONTENT_204 -) { - const path = '/api/v1/abuses/' + abuseId - - return makePutBodyRequest({ - url, - token, - path, - fields: body, - statusCodeExpected - }) -} - -function deleteAbuse (url: string, token: string, abuseId: number, statusCodeExpected = HttpStatusCode.NO_CONTENT_204) { - const path = '/api/v1/abuses/' + abuseId - - return makeDeleteRequest({ - url, - token, - path, - statusCodeExpected - }) -} - -function listAbuseMessages (url: string, token: string, abuseId: number, statusCodeExpected = HttpStatusCode.OK_200) { - const path = '/api/v1/abuses/' + abuseId + '/messages' - - return makeGetRequest({ - url, - token, - path, - statusCodeExpected - }) -} - -function deleteAbuseMessage ( - url: string, - token: string, - abuseId: number, - messageId: number, - statusCodeExpected = HttpStatusCode.NO_CONTENT_204 -) { - const path = '/api/v1/abuses/' + abuseId + '/messages/' + messageId - - return makeDeleteRequest({ - url, - token, - path, - statusCodeExpected - }) -} - -function addAbuseMessage (url: string, token: string, abuseId: number, message: string, statusCodeExpected = HttpStatusCode.OK_200) { - const path = '/api/v1/abuses/' + abuseId + '/messages' - - return makePostBodyRequest({ - url, - token, - path, - fields: { message }, - statusCodeExpected - }) -} - -// --------------------------------------------------------------------------- - -export { - reportAbuse, - getAdminAbusesList, - updateAbuse, - deleteAbuse, - getUserAbusesList, - listAbuseMessages, - deleteAbuseMessage, - addAbuseMessage -} diff --git a/shared/extra-utils/moderation/index.ts b/shared/extra-utils/moderation/index.ts new file mode 100644 index 000000000..b37643956 --- /dev/null +++ b/shared/extra-utils/moderation/index.ts @@ -0,0 +1 @@ +export * from './abuses-command' diff --git a/shared/extra-utils/server/servers.ts b/shared/extra-utils/server/servers.ts index 4343eab93..f05f0dbbe 100644 --- a/shared/extra-utils/server/servers.ts +++ b/shared/extra-utils/server/servers.ts @@ -12,6 +12,7 @@ import { CustomPagesCommand } from '../custom-pages' import { FeedCommand } from '../feeds' import { LogsCommand } from '../logs' import { buildServerDirectory, getFileSize, isGithubCI, root, wait } from '../miscs/miscs' +import { AbusesCommand } from '../moderation' import { makeGetRequest } from '../requests/requests' interface ServerInfo { @@ -71,6 +72,7 @@ interface ServerInfo { customPageCommand?: CustomPagesCommand feedCommand?: FeedCommand logsCommand?: LogsCommand + abusesCommand?: AbusesCommand } function parallelTests () { @@ -281,6 +283,7 @@ async function runServer (server: ServerInfo, configOverrideArg?: any, args = [] server.customPageCommand = new CustomPagesCommand(server) server.feedCommand = new FeedCommand(server) server.logsCommand = new LogsCommand(server) + server.abusesCommand = new AbusesCommand(server) res(server) }) diff --git a/shared/extra-utils/shared/abstract-command.ts b/shared/extra-utils/shared/abstract-command.ts index a57222216..3ee5cd865 100644 --- a/shared/extra-utils/shared/abstract-command.ts +++ b/shared/extra-utils/shared/abstract-command.ts @@ -1,5 +1,5 @@ import { HttpStatusCode } from '@shared/core-utils' -import { makeGetRequest, makePostBodyRequest, makePutBodyRequest, unwrapBody, unwrapText } from '../requests/requests' +import { makeDeleteRequest, makeGetRequest, makePostBodyRequest, makePutBodyRequest, unwrapBody, unwrapText } from '../requests/requests' import { ServerInfo } from '../server/servers' export interface OverrideCommandOptions { @@ -44,6 +44,10 @@ abstract class AbstractCommand { return unwrapText(this.getRequest(options)) } + protected deleteRequest (options: CommonCommandOptions) { + return makeDeleteRequest(this.buildCommonRequestOptions(options)) + } + protected putBodyRequest (options: CommonCommandOptions & { fields?: { [ fieldName: string ]: any } }) { diff --git a/tsconfig.json b/tsconfig.json index d305722c4..32e4a42e4 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -8,6 +8,7 @@ "emitDecoratorMetadata": true, "importHelpers": true, "removeComments": true, + "strictBindCallApply": true, "outDir": "./dist", "lib": [ "dom", -- cgit v1.2.3 From 480d6ea6791fe4100f1905af1e1e3a08173594ea Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Tue, 6 Jul 2021 14:07:54 +0200 Subject: Move plugin blocklist mock --- shared/extra-utils/index.ts | 2 -- shared/extra-utils/mock-servers/index.ts | 1 + .../mock-servers/mock-plugin-blocklist.ts | 37 ++++++++++++++++++++++ shared/extra-utils/plugins/mock-blocklist.ts | 37 ---------------------- 4 files changed, 38 insertions(+), 39 deletions(-) create mode 100644 shared/extra-utils/mock-servers/mock-plugin-blocklist.ts delete mode 100644 shared/extra-utils/plugins/mock-blocklist.ts diff --git a/shared/extra-utils/index.ts b/shared/extra-utils/index.ts index bde269052..7ca079c78 100644 --- a/shared/extra-utils/index.ts +++ b/shared/extra-utils/index.ts @@ -7,8 +7,6 @@ export * from './miscs' export * from './mock-servers' export * from './moderation' -export * from './plugins/mock-blocklist' - export * from './requests/check-api-params' export * from './requests/requests' diff --git a/shared/extra-utils/mock-servers/index.ts b/shared/extra-utils/mock-servers/index.ts index 485757843..0ec07f685 100644 --- a/shared/extra-utils/mock-servers/index.ts +++ b/shared/extra-utils/mock-servers/index.ts @@ -1,3 +1,4 @@ export * from './mock-email' export * from './mock-instances-index' export * from './mock-joinpeertube-versions' +export * from './mock-plugin-blocklist' diff --git a/shared/extra-utils/mock-servers/mock-plugin-blocklist.ts b/shared/extra-utils/mock-servers/mock-plugin-blocklist.ts new file mode 100644 index 000000000..d18f8224f --- /dev/null +++ b/shared/extra-utils/mock-servers/mock-plugin-blocklist.ts @@ -0,0 +1,37 @@ +import * as express from 'express' +import { Server } from 'http' +import { randomInt } from '@shared/core-utils' + +type BlocklistResponse = { + data: { + value: string + action?: 'add' | 'remove' + updatedAt?: string + }[] +} + +export class MockBlocklist { + private body: BlocklistResponse + private server: Server + + initialize () { + return new Promise(res => { + const app = express() + + app.get('/blocklist', (req: express.Request, res: express.Response) => { + return res.json(this.body) + }) + + const port = 42201 + randomInt(1, 100) + this.server = app.listen(port, () => res(port)) + }) + } + + replace (body: BlocklistResponse) { + this.body = body + } + + terminate () { + if (this.server) this.server.close() + } +} diff --git a/shared/extra-utils/plugins/mock-blocklist.ts b/shared/extra-utils/plugins/mock-blocklist.ts deleted file mode 100644 index d18f8224f..000000000 --- a/shared/extra-utils/plugins/mock-blocklist.ts +++ /dev/null @@ -1,37 +0,0 @@ -import * as express from 'express' -import { Server } from 'http' -import { randomInt } from '@shared/core-utils' - -type BlocklistResponse = { - data: { - value: string - action?: 'add' | 'remove' - updatedAt?: string - }[] -} - -export class MockBlocklist { - private body: BlocklistResponse - private server: Server - - initialize () { - return new Promise(res => { - const app = express() - - app.get('/blocklist', (req: express.Request, res: express.Response) => { - return res.json(this.body) - }) - - const port = 42201 + randomInt(1, 100) - this.server = app.listen(port, () => res(port)) - }) - } - - replace (body: BlocklistResponse) { - this.body = body - } - - terminate () { - if (this.server) this.server.close() - } -} -- cgit v1.2.3 From 23a3a8827cb8b862f5cc7ee2819f39918303beca Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Tue, 6 Jul 2021 14:30:20 +0200 Subject: Introduce overviews command --- server/tests/api/check-params/videos-overviews.ts | 9 ++- server/tests/api/videos/video-nsfw.ts | 35 ++++++----- server/tests/api/videos/videos-overview.ts | 71 +++++++++-------------- shared/extra-utils/index.ts | 1 + shared/extra-utils/overviews/index.ts | 1 + shared/extra-utils/overviews/overviews-command.ts | 25 ++++++++ shared/extra-utils/overviews/overviews.ts | 34 ----------- shared/extra-utils/server/servers.ts | 3 + shared/extra-utils/shared/abstract-command.ts | 5 +- 9 files changed, 86 insertions(+), 98 deletions(-) create mode 100644 shared/extra-utils/overviews/index.ts create mode 100644 shared/extra-utils/overviews/overviews-command.ts delete mode 100644 shared/extra-utils/overviews/overviews.ts diff --git a/server/tests/api/check-params/videos-overviews.ts b/server/tests/api/check-params/videos-overviews.ts index 69d7fc471..44a936c9f 100644 --- a/server/tests/api/check-params/videos-overviews.ts +++ b/server/tests/api/check-params/videos-overviews.ts @@ -1,8 +1,7 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ import 'mocha' -import { cleanupTests, flushAndRunServer, ServerInfo } from '../../../../shared/extra-utils' -import { getVideosOverview } from '@shared/extra-utils/overviews/overviews' +import { cleanupTests, flushAndRunServer, ServerInfo } from '@shared/extra-utils' describe('Test videos overview', function () { let server: ServerInfo @@ -18,12 +17,12 @@ describe('Test videos overview', function () { describe('When getting videos overview', function () { it('Should fail with a bad pagination', async function () { - await getVideosOverview(server.url, 0, 400) - await getVideosOverview(server.url, 100, 400) + await server.overviewsCommand.getVideos({ page: 0, expectedStatus: 400 }) + await server.overviewsCommand.getVideos({ page: 100, expectedStatus: 400 }) }) it('Should succeed with a good pagination', async function () { - await getVideosOverview(server.url, 1) + await server.overviewsCommand.getVideos({ page: 1 }) }) }) diff --git a/server/tests/api/videos/video-nsfw.ts b/server/tests/api/videos/video-nsfw.ts index b16b484b9..6c98c9f12 100644 --- a/server/tests/api/videos/video-nsfw.ts +++ b/server/tests/api/videos/video-nsfw.ts @@ -1,34 +1,33 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ -import * as chai from 'chai' import 'mocha' -import { cleanupTests, getVideosList, ServerInfo, setAccessTokensToServers, uploadVideo } from '../../../../shared/extra-utils/index' -import { userLogin } from '../../../../shared/extra-utils/users/login' -import { createUser } from '../../../../shared/extra-utils/users/users' -import { getMyVideos } from '../../../../shared/extra-utils/videos/videos' +import * as chai from 'chai' import { + cleanupTests, + createUser, flushAndRunServer, getAccountVideos, getConfig, getCustomConfig, getMyUserInformation, + getMyVideos, getVideoChannelVideos, + getVideosList, getVideosListWithToken, searchVideo, searchVideoWithToken, + ServerInfo, + setAccessTokensToServers, updateCustomConfig, - updateMyUser -} from '../../../../shared/extra-utils' -import { ServerConfig, VideosOverview } from '../../../../shared/models' -import { CustomConfig } from '../../../../shared/models/server/custom-config.model' -import { User } from '../../../../shared/models/users' -import { getVideosOverview, getVideosOverviewWithToken } from '@shared/extra-utils/overviews/overviews' + updateMyUser, + uploadVideo, + userLogin +} from '@shared/extra-utils' +import { CustomConfig, ServerConfig, User, VideosOverview } from '@shared/models' const expect = chai.expect -function createOverviewRes (res: any) { - const overview = res.body as VideosOverview - +function createOverviewRes (overview: VideosOverview) { const videos = overview.categories[0].videos return { body: { data: videos, total: videos.length } } } @@ -57,7 +56,9 @@ describe('Test video NSFW policy', function () { // Overviews do not support video filters if (!hasQuery) { - promises.push(getVideosOverviewWithToken(server.url, 1, token).then(res => createOverviewRes(res))) + const p = server.overviewsCommand.getVideos({ page: 1, token }) + .then(res => createOverviewRes(res)) + promises.push(p) } return Promise.all(promises) @@ -72,7 +73,9 @@ describe('Test video NSFW policy', function () { // Overviews do not support video filters if (!hasQuery) { - promises.push(getVideosOverview(server.url, 1).then(res => createOverviewRes(res))) + const p = server.overviewsCommand.getVideos({ page: 1 }) + .then(res => createOverviewRes(res)) + promises.push(p) } return Promise.all(promises) diff --git a/server/tests/api/videos/videos-overview.ts b/server/tests/api/videos/videos-overview.ts index c266a1dc5..c8e3df4bd 100644 --- a/server/tests/api/videos/videos-overview.ts +++ b/server/tests/api/videos/videos-overview.ts @@ -2,8 +2,9 @@ import 'mocha' import * as chai from 'chai' - +import { Response } from 'superagent' import { + addAccountToAccountBlocklist, cleanupTests, flushAndRunServer, generateUserAccessToken, @@ -11,20 +12,15 @@ import { setAccessTokensToServers, uploadVideo, wait -} from '../../../../shared/extra-utils' -import { getVideosOverview, getVideosOverviewWithToken } from '../../../../shared/extra-utils/overviews/overviews' -import { VideosOverview } from '../../../../shared/models/overviews' -import { addAccountToAccountBlocklist } from '@shared/extra-utils/users/blocklist' -import { Response } from 'superagent' +} from '@shared/extra-utils' +import { VideosOverview } from '@shared/models' const expect = chai.expect describe('Test a videos overview', function () { let server: ServerInfo = null - function testOverviewCount (res: Response, expected: number) { - const overview: VideosOverview = res.body - + function testOverviewCount (overview: VideosOverview, expected: number) { expect(overview.tags).to.have.lengthOf(expected) expect(overview.categories).to.have.lengthOf(expected) expect(overview.channels).to.have.lengthOf(expected) @@ -39,9 +35,9 @@ describe('Test a videos overview', function () { }) it('Should send empty overview', async function () { - const res = await getVideosOverview(server.url, 1) + const body = await server.overviewsCommand.getVideos({ page: 1 }) - testOverviewCount(res, 0) + testOverviewCount(body, 0) }) it('Should upload 5 videos in a specific category, tag and channel but not include them in overview', async function () { @@ -55,34 +51,35 @@ describe('Test a videos overview', function () { tags: [ 'coucou1', 'coucou2' ] }) - const res = await getVideosOverview(server.url, 1) + const body = await server.overviewsCommand.getVideos({ page: 1 }) - testOverviewCount(res, 0) + testOverviewCount(body, 0) }) it('Should upload another video and include all videos in the overview', async function () { this.timeout(30000) - for (let i = 1; i < 6; i++) { - await uploadVideo(server.url, server.accessToken, { - name: 'video ' + i, - category: 3, - tags: [ 'coucou1', 'coucou2' ] - }) + { + for (let i = 1; i < 6; i++) { + await uploadVideo(server.url, server.accessToken, { + name: 'video ' + i, + category: 3, + tags: [ 'coucou1', 'coucou2' ] + }) + } + + await wait(3000) } - await wait(3000) - { - const res = await getVideosOverview(server.url, 1) + const body = await server.overviewsCommand.getVideos({ page: 1 }) - testOverviewCount(res, 1) + testOverviewCount(body, 1) } { - const res = await getVideosOverview(server.url, 2) + const overview = await server.overviewsCommand.getVideos({ page: 2 }) - const overview: VideosOverview = res.body expect(overview.tags).to.have.lengthOf(1) expect(overview.categories).to.have.lengthOf(0) expect(overview.channels).to.have.lengthOf(0) @@ -90,20 +87,10 @@ describe('Test a videos overview', function () { }) it('Should have the correct overview', async function () { - const res1 = await getVideosOverview(server.url, 1) - const res2 = await getVideosOverview(server.url, 2) - - const overview1: VideosOverview = res1.body - const overview2: VideosOverview = res2.body - - const tmp = [ - overview1.tags, - overview1.categories, - overview1.channels, - overview2.tags - ] + const overview1 = await server.overviewsCommand.getVideos({ page: 1 }) + const overview2 = await server.overviewsCommand.getVideos({ page: 2 }) - for (const arr of tmp) { + for (const arr of [ overview1.tags, overview1.categories, overview1.channels, overview2.tags ]) { expect(arr).to.have.lengthOf(1) const obj = arr[0] @@ -132,15 +119,15 @@ describe('Test a videos overview', function () { await addAccountToAccountBlocklist(server.url, token, 'root@' + server.host) { - const res = await getVideosOverview(server.url, 1) + const body = await server.overviewsCommand.getVideos({ page: 1 }) - testOverviewCount(res, 1) + testOverviewCount(body, 1) } { - const res = await getVideosOverviewWithToken(server.url, 1, token) + const body = await server.overviewsCommand.getVideos({ page: 1, token }) - testOverviewCount(res, 0) + testOverviewCount(body, 0) } }) diff --git a/shared/extra-utils/index.ts b/shared/extra-utils/index.ts index 7ca079c78..38c8c4c1c 100644 --- a/shared/extra-utils/index.ts +++ b/shared/extra-utils/index.ts @@ -6,6 +6,7 @@ export * from './logs' export * from './miscs' export * from './mock-servers' export * from './moderation' +export * from './overviews' export * from './requests/check-api-params' export * from './requests/requests' diff --git a/shared/extra-utils/overviews/index.ts b/shared/extra-utils/overviews/index.ts new file mode 100644 index 000000000..e19551907 --- /dev/null +++ b/shared/extra-utils/overviews/index.ts @@ -0,0 +1 @@ +export * from './overviews-command' diff --git a/shared/extra-utils/overviews/overviews-command.ts b/shared/extra-utils/overviews/overviews-command.ts new file mode 100644 index 000000000..0ac3cbd33 --- /dev/null +++ b/shared/extra-utils/overviews/overviews-command.ts @@ -0,0 +1,25 @@ +import { HttpStatusCode } from '@shared/core-utils' +import { VideosOverview } from '@shared/models' +import { AbstractCommand, OverrideCommandOptions } from '../shared' + +export class OverviewsCommand extends AbstractCommand { + + getVideos (options: OverrideCommandOptions & { + page: number + token?: string + }) { + const { token, page } = options + const path = '/api/v1/overviews/videos' + + const query = { page } + + return this.getRequestBody({ + ...options, + + token: token || null, + path, + query, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } +} diff --git a/shared/extra-utils/overviews/overviews.ts b/shared/extra-utils/overviews/overviews.ts deleted file mode 100644 index 5e1a13e5e..000000000 --- a/shared/extra-utils/overviews/overviews.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { makeGetRequest } from '../requests/requests' -import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' - -function getVideosOverview (url: string, page: number, statusCodeExpected = HttpStatusCode.OK_200) { - const path = '/api/v1/overviews/videos' - - const query = { page } - - return makeGetRequest({ - url, - path, - query, - statusCodeExpected - }) -} - -function getVideosOverviewWithToken (url: string, page: number, token: string, statusCodeExpected = HttpStatusCode.OK_200) { - const path = '/api/v1/overviews/videos' - - const query = { page } - - return makeGetRequest({ - url, - path, - query, - token, - statusCodeExpected - }) -} - -export { - getVideosOverview, - getVideosOverviewWithToken -} diff --git a/shared/extra-utils/server/servers.ts b/shared/extra-utils/server/servers.ts index f05f0dbbe..70be96cf6 100644 --- a/shared/extra-utils/server/servers.ts +++ b/shared/extra-utils/server/servers.ts @@ -13,6 +13,7 @@ import { FeedCommand } from '../feeds' import { LogsCommand } from '../logs' import { buildServerDirectory, getFileSize, isGithubCI, root, wait } from '../miscs/miscs' import { AbusesCommand } from '../moderation' +import { OverviewsCommand } from '../overviews' import { makeGetRequest } from '../requests/requests' interface ServerInfo { @@ -73,6 +74,7 @@ interface ServerInfo { feedCommand?: FeedCommand logsCommand?: LogsCommand abusesCommand?: AbusesCommand + overviewsCommand?: OverviewsCommand } function parallelTests () { @@ -284,6 +286,7 @@ async function runServer (server: ServerInfo, configOverrideArg?: any, args = [] server.feedCommand = new FeedCommand(server) server.logsCommand = new LogsCommand(server) server.abusesCommand = new AbusesCommand(server) + server.overviewsCommand = new OverviewsCommand(server) res(server) }) diff --git a/shared/extra-utils/shared/abstract-command.ts b/shared/extra-utils/shared/abstract-command.ts index 3ee5cd865..3815fab0e 100644 --- a/shared/extra-utils/shared/abstract-command.ts +++ b/shared/extra-utils/shared/abstract-command.ts @@ -78,7 +78,10 @@ abstract class AbstractCommand { return { url: this.server.url, path, - token: token ?? this.server.accessToken, + + // Token can be null if we don't want to add it + token: token !== undefined ? token : this.server.accessToken, + statusCodeExpected: expectedStatus ?? this.expectedStatus ?? defaultExpectedStatus } } -- cgit v1.2.3 From af971e06c620bd46a5aa64c8833364e7022b5e3d Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Tue, 6 Jul 2021 15:22:51 +0200 Subject: Introduce search command --- server/tests/api/moderation/video-blacklist.ts | 31 ++- .../search/search-activitypub-video-channels.ts | 83 ++++---- .../search/search-activitypub-video-playlists.ts | 84 ++++---- .../tests/api/search/search-activitypub-videos.ts | 81 ++++---- server/tests/api/search/search-channels.ts | 29 +-- server/tests/api/search/search-index.ts | 129 +++++++------ server/tests/api/search/search-playlists.ts | 36 ++-- server/tests/api/search/search-videos.ts | 211 ++++++++++++--------- server/tests/api/videos/video-nsfw.ts | 14 +- server/tests/api/videos/videos-history.ts | 15 +- server/tests/plugins/filter-hooks.ts | 62 +++--- shared/extra-utils/index.ts | 4 +- shared/extra-utils/overviews/overviews-command.ts | 1 - shared/extra-utils/search/index.ts | 1 + shared/extra-utils/search/search-command.ts | 101 ++++++++++ shared/extra-utils/search/video-channels.ts | 36 ---- shared/extra-utils/search/video-playlists.ts | 36 ---- shared/extra-utils/search/videos.ts | 64 ------- shared/extra-utils/server/servers.ts | 3 + shared/extra-utils/videos/videos.ts | 8 +- 20 files changed, 519 insertions(+), 510 deletions(-) create mode 100644 shared/extra-utils/search/index.ts create mode 100644 shared/extra-utils/search/search-command.ts delete mode 100644 shared/extra-utils/search/video-channels.ts delete mode 100644 shared/extra-utils/search/video-playlists.ts delete mode 100644 shared/extra-utils/search/videos.ts diff --git a/server/tests/api/moderation/video-blacklist.ts b/server/tests/api/moderation/video-blacklist.ts index 52cac20d9..4a4930c98 100644 --- a/server/tests/api/moderation/video-blacklist.ts +++ b/server/tests/api/moderation/video-blacklist.ts @@ -7,6 +7,7 @@ import { addVideoToBlacklist, cleanupTests, createUser, + doubleFollow, flushAndRunMultipleServers, getBlacklistedVideosList, getMyUserInformation, @@ -15,20 +16,16 @@ import { killallServers, removeVideoFromBlacklist, reRunServer, - searchVideo, ServerInfo, setAccessTokensToServers, updateVideo, updateVideoBlacklist, uploadVideo, - userLogin -} from '../../../../shared/extra-utils/index' -import { doubleFollow } from '../../../../shared/extra-utils/server/follows' -import { waitJobs } from '../../../../shared/extra-utils/server/jobs' -import { getGoodVideoUrl, getMagnetURI, importVideo } from '../../../../shared/extra-utils/videos/video-imports' -import { User, UserRole } from '../../../../shared/models/users' -import { UserAdminFlag } from '../../../../shared/models/users/user-flag.model' -import { VideoBlacklist, VideoBlacklistType } from '../../../../shared/models/videos' + userLogin, + waitJobs +} from '@shared/extra-utils' +import { getGoodVideoUrl, getMagnetURI, importVideo } from '@shared/extra-utils/videos/video-imports' +import { User, UserAdminFlag, UserRole, VideoBlacklist, VideoBlacklistType } from '@shared/models' const expect = chai.expect @@ -80,11 +77,11 @@ describe('Test video blacklist', function () { } { - const res = await searchVideo(servers[0].url, 'name') + const body = await servers[0].searchCommand.searchVideos({ search: 'name' }) - expect(res.body.total).to.equal(0) - expect(res.body.data).to.be.an('array') - expect(res.body.data.length).to.equal(0) + expect(body.total).to.equal(0) + expect(body.data).to.be.an('array') + expect(body.data.length).to.equal(0) } }) @@ -98,11 +95,11 @@ describe('Test video blacklist', function () { } { - const res = await searchVideo(servers[1].url, 'video') + const body = await servers[1].searchCommand.searchVideos({ search: 'name' }) - expect(res.body.total).to.equal(2) - expect(res.body.data).to.be.an('array') - expect(res.body.data.length).to.equal(2) + expect(body.total).to.equal(2) + expect(body.data).to.be.an('array') + expect(body.data.length).to.equal(2) } }) }) diff --git a/server/tests/api/search/search-activitypub-video-channels.ts b/server/tests/api/search/search-activitypub-video-channels.ts index e83eb7171..cf5158b66 100644 --- a/server/tests/api/search/search-activitypub-video-channels.ts +++ b/server/tests/api/search/search-activitypub-video-channels.ts @@ -1,7 +1,7 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ -import * as chai from 'chai' import 'mocha' +import * as chai from 'chai' import { addVideoChannel, cleanupTests, @@ -10,6 +10,7 @@ import { flushAndRunMultipleServers, getVideoChannelsList, getVideoChannelVideos, + SearchCommand, ServerInfo, setAccessTokensToServers, updateMyUser, @@ -17,11 +18,10 @@ import { updateVideoChannel, uploadVideo, userLogin, - wait -} from '../../../../shared/extra-utils' -import { waitJobs } from '../../../../shared/extra-utils/server/jobs' -import { VideoChannel } from '../../../../shared/models/videos' -import { searchVideoChannel } from '../../../../shared/extra-utils/search/video-channels' + wait, + waitJobs +} from '@shared/extra-utils' +import { VideoChannel } from '@shared/models' const expect = chai.expect @@ -30,6 +30,7 @@ describe('Test ActivityPub video channels search', function () { let userServer2Token: string let videoServer2UUID: string let channelIdServer2: number + let command: SearchCommand before(async function () { this.timeout(120000) @@ -64,6 +65,8 @@ describe('Test ActivityPub video channels search', function () { } await waitJobs(servers) + + command = servers[0].searchCommand }) it('Should not find a remote video channel', async function () { @@ -71,21 +74,21 @@ describe('Test ActivityPub video channels search', function () { { const search = 'http://localhost:' + servers[1].port + '/video-channels/channel1_server3' - const res = await searchVideoChannel(servers[0].url, search, servers[0].accessToken) + const body = await command.searchChannels({ search, token: servers[0].accessToken }) - expect(res.body.total).to.equal(0) - expect(res.body.data).to.be.an('array') - expect(res.body.data).to.have.lengthOf(0) + expect(body.total).to.equal(0) + expect(body.data).to.be.an('array') + expect(body.data).to.have.lengthOf(0) } { // Without token const search = 'http://localhost:' + servers[1].port + '/video-channels/channel1_server2' - const res = await searchVideoChannel(servers[0].url, search) + const body = await command.searchChannels({ search }) - expect(res.body.total).to.equal(0) - expect(res.body.data).to.be.an('array') - expect(res.body.data).to.have.lengthOf(0) + expect(body.total).to.equal(0) + expect(body.data).to.be.an('array') + expect(body.data).to.have.lengthOf(0) } }) @@ -96,13 +99,13 @@ describe('Test ActivityPub video channels search', function () { ] for (const search of searches) { - const res = await searchVideoChannel(servers[0].url, search) + const body = await command.searchChannels({ search }) - expect(res.body.total).to.equal(1) - expect(res.body.data).to.be.an('array') - expect(res.body.data).to.have.lengthOf(1) - expect(res.body.data[0].name).to.equal('channel1_server1') - expect(res.body.data[0].displayName).to.equal('Channel 1 server 1') + expect(body.total).to.equal(1) + expect(body.data).to.be.an('array') + expect(body.data).to.have.lengthOf(1) + expect(body.data[0].name).to.equal('channel1_server1') + expect(body.data[0].displayName).to.equal('Channel 1 server 1') } }) @@ -110,13 +113,13 @@ describe('Test ActivityPub video channels search', function () { const search = 'http://localhost:' + servers[0].port + '/c/channel1_server1' for (const token of [ undefined, servers[0].accessToken ]) { - const res = await searchVideoChannel(servers[0].url, search, token) + const body = await command.searchChannels({ search, token }) - expect(res.body.total).to.equal(1) - expect(res.body.data).to.be.an('array') - expect(res.body.data).to.have.lengthOf(1) - expect(res.body.data[0].name).to.equal('channel1_server1') - expect(res.body.data[0].displayName).to.equal('Channel 1 server 1') + expect(body.total).to.equal(1) + expect(body.data).to.be.an('array') + expect(body.data).to.have.lengthOf(1) + expect(body.data[0].name).to.equal('channel1_server1') + expect(body.data[0].displayName).to.equal('Channel 1 server 1') } }) @@ -129,13 +132,13 @@ describe('Test ActivityPub video channels search', function () { ] for (const search of searches) { - const res = await searchVideoChannel(servers[0].url, search, servers[0].accessToken) + const body = await command.searchChannels({ search, token: servers[0].accessToken }) - expect(res.body.total).to.equal(1) - expect(res.body.data).to.be.an('array') - expect(res.body.data).to.have.lengthOf(1) - expect(res.body.data[0].name).to.equal('channel1_server2') - expect(res.body.data[0].displayName).to.equal('Channel 1 server 2') + expect(body.total).to.equal(1) + expect(body.data).to.be.an('array') + expect(body.data).to.have.lengthOf(1) + expect(body.data[0].name).to.equal('channel1_server2') + expect(body.data[0].displayName).to.equal('Channel 1 server 2') } }) @@ -176,11 +179,11 @@ describe('Test ActivityPub video channels search', function () { await wait(10000) const search = 'http://localhost:' + servers[1].port + '/video-channels/channel1_server2' - const res = await searchVideoChannel(servers[0].url, search, servers[0].accessToken) - expect(res.body.total).to.equal(1) - expect(res.body.data).to.have.lengthOf(1) + const body = await command.searchChannels({ search, token: servers[0].accessToken }) + expect(body.total).to.equal(1) + expect(body.data).to.have.lengthOf(1) - const videoChannel: VideoChannel = res.body.data[0] + const videoChannel: VideoChannel = body.data[0] expect(videoChannel.displayName).to.equal('channel updated') // We don't return the owner account for now @@ -199,7 +202,7 @@ describe('Test ActivityPub video channels search', function () { await wait(10000) const search = 'http://localhost:' + servers[1].port + '/video-channels/channel1_server2' - await searchVideoChannel(servers[0].url, search, servers[0].accessToken) + await command.searchChannels({ search, token: servers[0].accessToken }) await waitJobs(servers) @@ -221,9 +224,9 @@ describe('Test ActivityPub video channels search', function () { await wait(10000) const search = 'http://localhost:' + servers[1].port + '/video-channels/channel1_server2' - const res = await searchVideoChannel(servers[0].url, search, servers[0].accessToken) - expect(res.body.total).to.equal(0) - expect(res.body.data).to.have.lengthOf(0) + const body = await command.searchChannels({ search, token: servers[0].accessToken }) + expect(body.total).to.equal(0) + expect(body.data).to.have.lengthOf(0) }) after(async function () { diff --git a/server/tests/api/search/search-activitypub-video-playlists.ts b/server/tests/api/search/search-activitypub-video-playlists.ts index 4c08e9548..1df18173a 100644 --- a/server/tests/api/search/search-activitypub-video-playlists.ts +++ b/server/tests/api/search/search-activitypub-video-playlists.ts @@ -9,15 +9,15 @@ import { deleteVideoPlaylist, flushAndRunMultipleServers, getVideoPlaylistsList, - searchVideoPlaylists, + SearchCommand, ServerInfo, setAccessTokensToServers, setDefaultVideoChannel, uploadVideoAndGetId, - wait -} from '../../../../shared/extra-utils' -import { waitJobs } from '../../../../shared/extra-utils/server/jobs' -import { VideoPlaylist, VideoPlaylistPrivacy } from '../../../../shared/models/videos' + wait, + waitJobs +} from '@shared/extra-utils' +import { VideoPlaylistPrivacy } from '@shared/models' const expect = chai.expect @@ -27,6 +27,8 @@ describe('Test ActivityPub playlists search', function () { let playlistServer2UUID: string let video2Server2: string + let command: SearchCommand + before(async function () { this.timeout(120000) @@ -78,38 +80,40 @@ describe('Test ActivityPub playlists search', function () { } await waitJobs(servers) + + command = servers[0].searchCommand }) it('Should not find a remote playlist', async function () { { const search = 'http://localhost:' + servers[1].port + '/video-playlists/43' - const res = await searchVideoPlaylists(servers[0].url, search, servers[0].accessToken) + const body = await command.searchPlaylists({ search, token: servers[0].accessToken }) - expect(res.body.total).to.equal(0) - expect(res.body.data).to.be.an('array') - expect(res.body.data).to.have.lengthOf(0) + expect(body.total).to.equal(0) + expect(body.data).to.be.an('array') + expect(body.data).to.have.lengthOf(0) } { // Without token const search = 'http://localhost:' + servers[1].port + '/video-playlists/' + playlistServer2UUID - const res = await searchVideoPlaylists(servers[0].url, search) + const body = await command.searchPlaylists({ search }) - expect(res.body.total).to.equal(0) - expect(res.body.data).to.be.an('array') - expect(res.body.data).to.have.lengthOf(0) + expect(body.total).to.equal(0) + expect(body.data).to.be.an('array') + expect(body.data).to.have.lengthOf(0) } }) it('Should search a local playlist', async function () { const search = 'http://localhost:' + servers[0].port + '/video-playlists/' + playlistServer1UUID - const res = await searchVideoPlaylists(servers[0].url, search) + const body = await command.searchPlaylists({ search }) - expect(res.body.total).to.equal(1) - expect(res.body.data).to.be.an('array') - expect(res.body.data).to.have.lengthOf(1) - expect(res.body.data[0].displayName).to.equal('playlist 1 on server 1') - expect(res.body.data[0].videosLength).to.equal(2) + expect(body.total).to.equal(1) + expect(body.data).to.be.an('array') + expect(body.data).to.have.lengthOf(1) + expect(body.data[0].displayName).to.equal('playlist 1 on server 1') + expect(body.data[0].videosLength).to.equal(2) }) it('Should search a local playlist with an alternative URL', async function () { @@ -120,13 +124,13 @@ describe('Test ActivityPub playlists search', function () { for (const search of searches) { for (const token of [ undefined, servers[0].accessToken ]) { - const res = await searchVideoPlaylists(servers[0].url, search, token) + const body = await command.searchPlaylists({ search, token }) - expect(res.body.total).to.equal(1) - expect(res.body.data).to.be.an('array') - expect(res.body.data).to.have.lengthOf(1) - expect(res.body.data[0].displayName).to.equal('playlist 1 on server 1') - expect(res.body.data[0].videosLength).to.equal(2) + expect(body.total).to.equal(1) + expect(body.data).to.be.an('array') + expect(body.data).to.have.lengthOf(1) + expect(body.data[0].displayName).to.equal('playlist 1 on server 1') + expect(body.data[0].videosLength).to.equal(2) } } }) @@ -139,13 +143,13 @@ describe('Test ActivityPub playlists search', function () { ] for (const search of searches) { - const res = await searchVideoPlaylists(servers[0].url, search, servers[0].accessToken) + const body = await command.searchPlaylists({ search, token: servers[0].accessToken }) - expect(res.body.total).to.equal(1) - expect(res.body.data).to.be.an('array') - expect(res.body.data).to.have.lengthOf(1) - expect(res.body.data[0].displayName).to.equal('playlist 1 on server 2') - expect(res.body.data[0].videosLength).to.equal(1) + expect(body.total).to.equal(1) + expect(body.data).to.be.an('array') + expect(body.data).to.have.lengthOf(1) + expect(body.data[0].displayName).to.equal('playlist 1 on server 2') + expect(body.data[0].videosLength).to.equal(1) } }) @@ -172,16 +176,16 @@ describe('Test ActivityPub playlists search', function () { // Will run refresh async const search = 'http://localhost:' + servers[1].port + '/video-playlists/' + playlistServer2UUID - await searchVideoPlaylists(servers[0].url, search, servers[0].accessToken) + await command.searchPlaylists({ search, token: servers[0].accessToken }) // Wait refresh await wait(5000) - const res = await searchVideoPlaylists(servers[0].url, search, servers[0].accessToken) - expect(res.body.total).to.equal(1) - expect(res.body.data).to.have.lengthOf(1) + const body = await command.searchPlaylists({ search, token: servers[0].accessToken }) + expect(body.total).to.equal(1) + expect(body.data).to.have.lengthOf(1) - const playlist: VideoPlaylist = res.body.data[0] + const playlist = body.data[0] expect(playlist.videosLength).to.equal(2) }) @@ -196,14 +200,14 @@ describe('Test ActivityPub playlists search', function () { // Will run refresh async const search = 'http://localhost:' + servers[1].port + '/video-playlists/' + playlistServer2UUID - await searchVideoPlaylists(servers[0].url, search, servers[0].accessToken) + await command.searchPlaylists({ search, token: servers[0].accessToken }) // Wait refresh await wait(5000) - const res = await searchVideoPlaylists(servers[0].url, search, servers[0].accessToken) - expect(res.body.total).to.equal(0) - expect(res.body.data).to.have.lengthOf(0) + const body = await command.searchPlaylists({ search, token: servers[0].accessToken }) + expect(body.total).to.equal(0) + expect(body.data).to.have.lengthOf(0) }) after(async function () { diff --git a/server/tests/api/search/search-activitypub-videos.ts b/server/tests/api/search/search-activitypub-videos.ts index e9b4978da..1a5130ce9 100644 --- a/server/tests/api/search/search-activitypub-videos.ts +++ b/server/tests/api/search/search-activitypub-videos.ts @@ -1,15 +1,14 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ -import * as chai from 'chai' import 'mocha' +import * as chai from 'chai' import { addVideoChannel, cleanupTests, flushAndRunMultipleServers, getVideosList, removeVideo, - searchVideo, - searchVideoWithToken, + SearchCommand, ServerInfo, setAccessTokensToServers, updateVideo, @@ -17,7 +16,7 @@ import { wait } from '../../../../shared/extra-utils' import { waitJobs } from '../../../../shared/extra-utils/server/jobs' -import { Video, VideoPrivacy } from '../../../../shared/models/videos' +import { VideoPrivacy } from '../../../../shared/models/videos' const expect = chai.expect @@ -26,6 +25,8 @@ describe('Test ActivityPub videos search', function () { let videoServer1UUID: string let videoServer2UUID: string + let command: SearchCommand + before(async function () { this.timeout(120000) @@ -44,49 +45,51 @@ describe('Test ActivityPub videos search', function () { } await waitJobs(servers) + + command = servers[0].searchCommand }) it('Should not find a remote video', async function () { { const search = 'http://localhost:' + servers[1].port + '/videos/watch/43' - const res = await searchVideoWithToken(servers[0].url, search, servers[0].accessToken) + const body = await command.searchVideos({ search, token: servers[0].accessToken }) - expect(res.body.total).to.equal(0) - expect(res.body.data).to.be.an('array') - expect(res.body.data).to.have.lengthOf(0) + expect(body.total).to.equal(0) + expect(body.data).to.be.an('array') + expect(body.data).to.have.lengthOf(0) } { // Without token const search = 'http://localhost:' + servers[1].port + '/videos/watch/' + videoServer2UUID - const res = await searchVideo(servers[0].url, search) + const body = await command.searchVideos({ search }) - expect(res.body.total).to.equal(0) - expect(res.body.data).to.be.an('array') - expect(res.body.data).to.have.lengthOf(0) + expect(body.total).to.equal(0) + expect(body.data).to.be.an('array') + expect(body.data).to.have.lengthOf(0) } }) it('Should search a local video', async function () { const search = 'http://localhost:' + servers[0].port + '/videos/watch/' + videoServer1UUID - const res = await searchVideo(servers[0].url, search) + const body = await command.searchVideos({ search }) - expect(res.body.total).to.equal(1) - expect(res.body.data).to.be.an('array') - expect(res.body.data).to.have.lengthOf(1) - expect(res.body.data[0].name).to.equal('video 1 on server 1') + expect(body.total).to.equal(1) + expect(body.data).to.be.an('array') + expect(body.data).to.have.lengthOf(1) + expect(body.data[0].name).to.equal('video 1 on server 1') }) it('Should search a local video with an alternative URL', async function () { const search = 'http://localhost:' + servers[0].port + '/w/' + videoServer1UUID - const res1 = await searchVideo(servers[0].url, search) - const res2 = await searchVideoWithToken(servers[0].url, search, servers[0].accessToken) - - for (const res of [ res1, res2 ]) { - expect(res.body.total).to.equal(1) - expect(res.body.data).to.be.an('array') - expect(res.body.data).to.have.lengthOf(1) - expect(res.body.data[0].name).to.equal('video 1 on server 1') + const body1 = await command.searchVideos({ search }) + const body2 = await command.searchVideos({ search, token: servers[0].accessToken }) + + for (const body of [ body1, body2 ]) { + expect(body.total).to.equal(1) + expect(body.data).to.be.an('array') + expect(body.data).to.have.lengthOf(1) + expect(body.data[0].name).to.equal('video 1 on server 1') } }) @@ -97,12 +100,12 @@ describe('Test ActivityPub videos search', function () { ] for (const search of searches) { - const res = await searchVideoWithToken(servers[0].url, search, servers[0].accessToken) + const body = await command.searchVideos({ search, token: servers[0].accessToken }) - expect(res.body.total).to.equal(1) - expect(res.body.data).to.be.an('array') - expect(res.body.data).to.have.lengthOf(1) - expect(res.body.data[0].name).to.equal('video 1 on server 2') + expect(body.total).to.equal(1) + expect(body.data).to.be.an('array') + expect(body.data).to.have.lengthOf(1) + expect(body.data[0].name).to.equal('video 1 on server 2') } }) @@ -137,16 +140,16 @@ describe('Test ActivityPub videos search', function () { // Will run refresh async const search = 'http://localhost:' + servers[1].port + '/videos/watch/' + videoServer2UUID - await searchVideoWithToken(servers[0].url, search, servers[0].accessToken) + await command.searchVideos({ search, token: servers[0].accessToken }) // Wait refresh await wait(5000) - const res = await searchVideoWithToken(servers[0].url, search, servers[0].accessToken) - expect(res.body.total).to.equal(1) - expect(res.body.data).to.have.lengthOf(1) + const body = await command.searchVideos({ search, token: servers[0].accessToken }) + expect(body.total).to.equal(1) + expect(body.data).to.have.lengthOf(1) - const video: Video = res.body.data[0] + const video = body.data[0] expect(video.name).to.equal('updated') expect(video.channel.name).to.equal('super_channel') expect(video.privacy.id).to.equal(VideoPrivacy.UNLISTED) @@ -163,14 +166,14 @@ describe('Test ActivityPub videos search', function () { // Will run refresh async const search = 'http://localhost:' + servers[1].port + '/videos/watch/' + videoServer2UUID - await searchVideoWithToken(servers[0].url, search, servers[0].accessToken) + await command.searchVideos({ search, token: servers[0].accessToken }) // Wait refresh await wait(5000) - const res = await searchVideoWithToken(servers[0].url, search, servers[0].accessToken) - expect(res.body.total).to.equal(0) - expect(res.body.data).to.have.lengthOf(0) + const body = await command.searchVideos({ search, token: servers[0].accessToken }) + expect(body.total).to.equal(0) + expect(body.data).to.have.lengthOf(0) }) after(async function () { diff --git a/server/tests/api/search/search-channels.ts b/server/tests/api/search/search-channels.ts index daca2aebe..307bc063d 100644 --- a/server/tests/api/search/search-channels.ts +++ b/server/tests/api/search/search-channels.ts @@ -2,21 +2,22 @@ import 'mocha' import * as chai from 'chai' -import { searchVideoChannel, advancedVideoChannelSearch } from '@shared/extra-utils/search/video-channels' import { addVideoChannel, cleanupTests, createUser, flushAndRunServer, + SearchCommand, ServerInfo, setAccessTokensToServers -} from '../../../../shared/extra-utils' +} from '@shared/extra-utils' import { VideoChannel } from '@shared/models' const expect = chai.expect describe('Test channels search', function () { let server: ServerInfo = null + let command: SearchCommand before(async function () { this.timeout(30000) @@ -33,13 +34,15 @@ describe('Test channels search', function () { } await addVideoChannel(server.url, server.accessToken, channel) } + + command = server.searchCommand }) it('Should make a simple search and not have results', async function () { - const res = await searchVideoChannel(server.url, 'abc') + const body = await command.searchChannels({ search: 'abc' }) - expect(res.body.total).to.equal(0) - expect(res.body.data).to.have.lengthOf(0) + expect(body.total).to.equal(0) + expect(body.data).to.have.lengthOf(0) }) it('Should make a search and have results', async function () { @@ -49,11 +52,11 @@ describe('Test channels search', function () { start: 0, count: 1 } - const res = await advancedVideoChannelSearch(server.url, search) - expect(res.body.total).to.equal(1) - expect(res.body.data).to.have.lengthOf(1) + const body = await command.advancedChannelSearch({ search }) + expect(body.total).to.equal(1) + expect(body.data).to.have.lengthOf(1) - const channel: VideoChannel = res.body.data[0] + const channel: VideoChannel = body.data[0] expect(channel.name).to.equal('squall_channel') expect(channel.displayName).to.equal('Squall channel') } @@ -65,11 +68,9 @@ describe('Test channels search', function () { count: 1 } - const res = await advancedVideoChannelSearch(server.url, search) - - expect(res.body.total).to.equal(1) - - expect(res.body.data).to.have.lengthOf(0) + const body = await command.advancedChannelSearch({ search }) + expect(body.total).to.equal(1) + expect(body.data).to.have.lengthOf(0) } }) diff --git a/server/tests/api/search/search-index.ts b/server/tests/api/search/search-index.ts index 00f79232a..b2c0857a7 100644 --- a/server/tests/api/search/search-index.ts +++ b/server/tests/api/search/search-index.ts @@ -2,28 +2,26 @@ import 'mocha' import * as chai from 'chai' -import { advancedVideoChannelSearch, searchVideoChannel } from '@shared/extra-utils/search/video-channels' -import { Video, VideoChannel, VideoPlaylist, VideoPlaylistPrivacy, VideoPlaylistType, VideosSearchQuery } from '@shared/models' import { - advancedVideoPlaylistSearch, - advancedVideosSearch, cleanupTests, flushAndRunServer, immutableAssign, - searchVideo, - searchVideoPlaylists, + SearchCommand, ServerInfo, setAccessTokensToServers, updateCustomSubConfig, uploadVideo -} from '../../../../shared/extra-utils' +} from '@shared/extra-utils' +import { VideoPlaylistPrivacy, VideoPlaylistType, VideosSearchQuery } from '@shared/models' const expect = chai.expect describe('Test videos search', function () { - let server: ServerInfo = null const localVideoName = 'local video' + new Date().toISOString() + let server: ServerInfo = null + let command: SearchCommand + before(async function () { this.timeout(30000) @@ -32,6 +30,8 @@ describe('Test videos search', function () { await setAccessTokensToServers([ server ]) await uploadVideo(server.url, server.accessToken, { name: localVideoName }) + + command = server.searchCommand }) describe('Default search', async function () { @@ -49,18 +49,18 @@ describe('Test videos search', function () { } }) - const res = await searchVideo(server.url, 'local video') + const body = await command.searchVideos({ search: 'local video' }) - expect(res.body.total).to.equal(1) - expect(res.body.data[0].name).to.equal(localVideoName) + expect(body.total).to.equal(1) + expect(body.data[0].name).to.equal(localVideoName) }) it('Should make a local channels search by default', async function () { - const res = await searchVideoChannel(server.url, 'root') + const body = await command.searchChannels({ search: 'root' }) - expect(res.body.total).to.equal(1) - expect(res.body.data[0].name).to.equal('root_channel') - expect(res.body.data[0].host).to.equal('localhost:' + server.port) + expect(body.total).to.equal(1) + expect(body.data[0].name).to.equal('root_channel') + expect(body.data[0].host).to.equal('localhost:' + server.port) }) it('Should make an index videos search by default', async function () { @@ -74,13 +74,13 @@ describe('Test videos search', function () { } }) - const res = await searchVideo(server.url, 'local video') - expect(res.body.total).to.be.greaterThan(2) + const body = await command.searchVideos({ search: 'local video' }) + expect(body.total).to.be.greaterThan(2) }) it('Should make an index channels search by default', async function () { - const res = await searchVideoChannel(server.url, 'root') - expect(res.body.total).to.be.greaterThan(2) + const body = await command.searchChannels({ search: 'root' }) + expect(body.total).to.be.greaterThan(2) }) it('Should make an index videos search if local search is disabled', async function () { @@ -94,46 +94,46 @@ describe('Test videos search', function () { } }) - const res = await searchVideo(server.url, 'local video') - expect(res.body.total).to.be.greaterThan(2) + const body = await command.searchVideos({ search: 'local video' }) + expect(body.total).to.be.greaterThan(2) }) it('Should make an index channels search if local search is disabled', async function () { - const res = await searchVideoChannel(server.url, 'root') - expect(res.body.total).to.be.greaterThan(2) + const body = await command.searchChannels({ search: 'root' }) + expect(body.total).to.be.greaterThan(2) }) }) describe('Videos search', async function () { it('Should make a simple search and not have results', async function () { - const res = await searchVideo(server.url, 'djidane'.repeat(50)) + const body = await command.searchVideos({ search: 'djidane'.repeat(50) }) - expect(res.body.total).to.equal(0) - expect(res.body.data).to.have.lengthOf(0) + expect(body.total).to.equal(0) + expect(body.data).to.have.lengthOf(0) }) it('Should make a simple search and have results', async function () { - const res = await searchVideo(server.url, 'What is PeerTube') + const body = await command.searchVideos({ search: 'What is PeerTube' }) - expect(res.body.total).to.be.greaterThan(1) + expect(body.total).to.be.greaterThan(1) }) it('Should make a complex search', async function () { async function check (search: VideosSearchQuery, exists = true) { - const res = await advancedVideosSearch(server.url, search) + const body = await command.advancedVideoSearch({ search }) if (exists === false) { - expect(res.body.total).to.equal(0) - expect(res.body.data).to.have.lengthOf(0) + expect(body.total).to.equal(0) + expect(body.data).to.have.lengthOf(0) return } - expect(res.body.total).to.equal(1) - expect(res.body.data).to.have.lengthOf(1) + expect(body.total).to.equal(1) + expect(body.data).to.have.lengthOf(1) - const video: Video = res.body.data[0] + const video = body.data[0] expect(video.name).to.equal('What is PeerTube?') expect(video.category.label).to.equal('Science & Technology') @@ -206,10 +206,10 @@ describe('Test videos search', function () { count: 5 } - const res = await advancedVideosSearch(server.url, search) + const body = await command.advancedVideoSearch({ search }) - expect(res.body.total).to.be.greaterThan(5) - expect(res.body.data).to.have.lengthOf(5) + expect(body.total).to.be.greaterThan(5) + expect(body.data).to.have.lengthOf(5) }) it('Should use the nsfw instance policy as default', async function () { @@ -218,10 +218,10 @@ describe('Test videos search', function () { { await updateCustomSubConfig(server.url, server.accessToken, { instance: { defaultNSFWPolicy: 'display' } }) - const res = await searchVideo(server.url, 'NSFW search index', '-match') - const video = res.body.data[0] as Video + const body = await command.searchVideos({ search: 'NSFW search index', sort: '-match' }) + expect(body.data).to.have.length.greaterThan(0) - expect(res.body.data).to.have.length.greaterThan(0) + const video = body.data[0] expect(video.nsfw).to.be.true nsfwUUID = video.uuid @@ -230,13 +230,12 @@ describe('Test videos search', function () { { await updateCustomSubConfig(server.url, server.accessToken, { instance: { defaultNSFWPolicy: 'do_not_list' } }) - const res = await searchVideo(server.url, 'NSFW search index', '-match') + const body = await command.searchVideos({ search: 'NSFW search index', sort: '-match' }) try { - expect(res.body.data).to.have.lengthOf(0) - } catch (err) { - // - const video = res.body.data[0] as Video + expect(body.data).to.have.lengthOf(0) + } catch { + const video = body.data[0] expect(video.uuid).not.equal(nsfwUUID) } @@ -247,19 +246,19 @@ describe('Test videos search', function () { describe('Channels search', async function () { it('Should make a simple search and not have results', async function () { - const res = await searchVideoChannel(server.url, 'a'.repeat(500)) + const body = await command.searchChannels({ search: 'a'.repeat(500) }) - expect(res.body.total).to.equal(0) - expect(res.body.data).to.have.lengthOf(0) + expect(body.total).to.equal(0) + expect(body.data).to.have.lengthOf(0) }) it('Should make a search and have results', async function () { - const res = await advancedVideoChannelSearch(server.url, { search: 'Framasoft', sort: 'createdAt' }) + const body = await command.advancedChannelSearch({ search: { search: 'Framasoft', sort: 'createdAt' } }) - expect(res.body.total).to.be.greaterThan(0) - expect(res.body.data).to.have.length.greaterThan(0) + expect(body.total).to.be.greaterThan(0) + expect(body.data).to.have.length.greaterThan(0) - const videoChannel: VideoChannel = res.body.data[0] + const videoChannel = body.data[0] expect(videoChannel.url).to.equal('https://framatube.org/video-channels/bf54d359-cfad-4935-9d45-9d6be93f63e8') expect(videoChannel.host).to.equal('framatube.org') expect(videoChannel.avatar).to.exist @@ -272,29 +271,29 @@ describe('Test videos search', function () { }) it('Should have a correct pagination', async function () { - const res = await advancedVideoChannelSearch(server.url, { search: 'root', start: 0, count: 2 }) + const body = await command.advancedChannelSearch({ search: { search: 'root', start: 0, count: 2 } }) - expect(res.body.total).to.be.greaterThan(2) - expect(res.body.data).to.have.lengthOf(2) + expect(body.total).to.be.greaterThan(2) + expect(body.data).to.have.lengthOf(2) }) }) describe('Playlists search', async function () { it('Should make a simple search and not have results', async function () { - const res = await searchVideoPlaylists(server.url, 'a'.repeat(500)) + const body = await command.searchPlaylists({ search: 'a'.repeat(500) }) - expect(res.body.total).to.equal(0) - expect(res.body.data).to.have.lengthOf(0) + expect(body.total).to.equal(0) + expect(body.data).to.have.lengthOf(0) }) it('Should make a search and have results', async function () { - const res = await advancedVideoPlaylistSearch(server.url, { search: 'E2E playlist', sort: '-match' }) + const body = await command.advancedPlaylistSearch({ search: { search: 'E2E playlist', sort: '-match' } }) - expect(res.body.total).to.be.greaterThan(0) - expect(res.body.data).to.have.length.greaterThan(0) + expect(body.total).to.be.greaterThan(0) + expect(body.data).to.have.length.greaterThan(0) - const videoPlaylist: VideoPlaylist = res.body.data[0] + const videoPlaylist = body.data[0] expect(videoPlaylist.url).to.equal('https://peertube2.cpy.re/videos/watch/playlist/73804a40-da9a-40c2-b1eb-2c6d9eec8f0a') expect(videoPlaylist.thumbnailUrl).to.exist @@ -322,10 +321,10 @@ describe('Test videos search', function () { }) it('Should have a correct pagination', async function () { - const res = await advancedVideoChannelSearch(server.url, { search: 'root', start: 0, count: 2 }) + const body = await command.advancedChannelSearch({ search: { search: 'root', start: 0, count: 2 } }) - expect(res.body.total).to.be.greaterThan(2) - expect(res.body.data).to.have.lengthOf(2) + expect(body.total).to.be.greaterThan(2) + expect(body.data).to.have.lengthOf(2) }) }) diff --git a/server/tests/api/search/search-playlists.ts b/server/tests/api/search/search-playlists.ts index ab17d55e9..1862ecd31 100644 --- a/server/tests/api/search/search-playlists.ts +++ b/server/tests/api/search/search-playlists.ts @@ -2,14 +2,13 @@ import 'mocha' import * as chai from 'chai' -import { VideoPlaylist, VideoPlaylistPrivacy } from '@shared/models' +import { VideoPlaylistPrivacy } from '@shared/models' import { addVideoInPlaylist, - advancedVideoPlaylistSearch, cleanupTests, createVideoPlaylist, flushAndRunServer, - searchVideoPlaylists, + SearchCommand, ServerInfo, setAccessTokensToServers, setDefaultVideoChannel, @@ -20,6 +19,7 @@ const expect = chai.expect describe('Test playlists search', function () { let server: ServerInfo = null + let command: SearchCommand before(async function () { this.timeout(30000) @@ -71,13 +71,15 @@ describe('Test playlists search', function () { } await createVideoPlaylist({ url: server.url, token: server.accessToken, playlistAttrs: attributes }) } + + command = server.searchCommand }) it('Should make a simple search and not have results', async function () { - const res = await searchVideoPlaylists(server.url, 'abc') + const body = await command.searchPlaylists({ search: 'abc' }) - expect(res.body.total).to.equal(0) - expect(res.body.data).to.have.lengthOf(0) + expect(body.total).to.equal(0) + expect(body.data).to.have.lengthOf(0) }) it('Should make a search and have results', async function () { @@ -87,11 +89,11 @@ describe('Test playlists search', function () { start: 0, count: 1 } - const res = await advancedVideoPlaylistSearch(server.url, search) - expect(res.body.total).to.equal(1) - expect(res.body.data).to.have.lengthOf(1) + const body = await command.advancedPlaylistSearch({ search }) + expect(body.total).to.equal(1) + expect(body.data).to.have.lengthOf(1) - const playlist: VideoPlaylist = res.body.data[0] + const playlist = body.data[0] expect(playlist.displayName).to.equal('Dr. Kenzo Tenma hospital videos') expect(playlist.url).to.equal(server.url + '/video-playlists/' + playlist.uuid) } @@ -102,11 +104,11 @@ describe('Test playlists search', function () { start: 0, count: 1 } - const res = await advancedVideoPlaylistSearch(server.url, search) - expect(res.body.total).to.equal(1) - expect(res.body.data).to.have.lengthOf(1) + const body = await command.advancedPlaylistSearch({ search }) + expect(body.total).to.equal(1) + expect(body.data).to.have.lengthOf(1) - const playlist: VideoPlaylist = res.body.data[0] + const playlist = body.data[0] expect(playlist.displayName).to.equal('Johan & Anna Libert musics') } }) @@ -117,9 +119,9 @@ describe('Test playlists search', function () { start: 0, count: 1 } - const res = await advancedVideoPlaylistSearch(server.url, search) - expect(res.body.total).to.equal(0) - expect(res.body.data).to.have.lengthOf(0) + const body = await command.advancedPlaylistSearch({ search }) + expect(body.total).to.equal(0) + expect(body.data).to.have.lengthOf(0) }) after(async function () { diff --git a/server/tests/api/search/search-videos.ts b/server/tests/api/search/search-videos.ts index 5b8907961..f0482c7e0 100644 --- a/server/tests/api/search/search-videos.ts +++ b/server/tests/api/search/search-videos.ts @@ -4,12 +4,11 @@ import 'mocha' import * as chai from 'chai' import { VideoPrivacy } from '@shared/models' import { - advancedVideosSearch, cleanupTests, createLive, flushAndRunServer, immutableAssign, - searchVideo, + SearchCommand, sendRTMPStreamInVideo, ServerInfo, setAccessTokensToServers, @@ -29,6 +28,8 @@ describe('Test videos search', function () { let startDate: string let videoUUID: string + let command: SearchCommand + before(async function () { this.timeout(60000) @@ -144,21 +145,23 @@ describe('Test videos search', function () { await uploadVideo(server.url, server.accessToken, attributes1) await uploadVideo(server.url, server.accessToken, immutableAssign(attributes1, { category: 2 })) } + + command = server.searchCommand }) it('Should make a simple search and not have results', async function () { - const res = await searchVideo(server.url, 'abc') + const body = await command.searchVideos({ search: 'abc' }) - expect(res.body.total).to.equal(0) - expect(res.body.data).to.have.lengthOf(0) + expect(body.total).to.equal(0) + expect(body.data).to.have.lengthOf(0) }) it('Should make a simple search and have results', async function () { - const res = await searchVideo(server.url, '4444 5555 duplicate') + const body = await command.searchVideos({ search: '4444 5555 duplicate' }) - expect(res.body.total).to.equal(2) + expect(body.total).to.equal(2) - const videos = res.body.data + const videos = body.data expect(videos).to.have.lengthOf(2) // bestmatch @@ -167,15 +170,15 @@ describe('Test videos search', function () { }) it('Should make a search on tags too, and have results', async function () { - const query = { + const search = { search: 'aaaa', categoryOneOf: [ 1 ] } - const res = await advancedVideosSearch(server.url, query) + const body = await command.advancedVideoSearch({ search }) - expect(res.body.total).to.equal(2) + expect(body.total).to.equal(2) - const videos = res.body.data + const videos = body.data expect(videos).to.have.lengthOf(2) // bestmatch @@ -184,14 +187,14 @@ describe('Test videos search', function () { }) it('Should filter on tags without a search', async function () { - const query = { + const search = { tagsAllOf: [ 'bbbb' ] } - const res = await advancedVideosSearch(server.url, query) + const body = await command.advancedVideoSearch({ search }) - expect(res.body.total).to.equal(2) + expect(body.total).to.equal(2) - const videos = res.body.data + const videos = body.data expect(videos).to.have.lengthOf(2) expect(videos[0].name).to.equal('9999') @@ -199,14 +202,14 @@ describe('Test videos search', function () { }) it('Should filter on category without a search', async function () { - const query = { + const search = { categoryOneOf: [ 3 ] } - const res = await advancedVideosSearch(server.url, query) + const body = await command.advancedVideoSearch({ search: search }) - expect(res.body.total).to.equal(1) + expect(body.total).to.equal(1) - const videos = res.body.data + const videos = body.data expect(videos).to.have.lengthOf(1) expect(videos[0].name).to.equal('6666 7777 8888') @@ -218,11 +221,16 @@ describe('Test videos search', function () { categoryOneOf: [ 1 ], tagsOneOf: [ 'aAaa', 'ffff' ] } - const res1 = await advancedVideosSearch(server.url, query) - expect(res1.body.total).to.equal(2) - const res2 = await advancedVideosSearch(server.url, immutableAssign(query, { tagsOneOf: [ 'blabla' ] })) - expect(res2.body.total).to.equal(0) + { + const body = await command.advancedVideoSearch({ search: query }) + expect(body.total).to.equal(2) + } + + { + const body = await command.advancedVideoSearch({ search: { ...query, tagsOneOf: [ 'blabla' ] } }) + expect(body.total).to.equal(0) + } }) it('Should search by tags (all of)', async function () { @@ -231,14 +239,21 @@ describe('Test videos search', function () { categoryOneOf: [ 1 ], tagsAllOf: [ 'CCcc' ] } - const res1 = await advancedVideosSearch(server.url, query) - expect(res1.body.total).to.equal(2) - const res2 = await advancedVideosSearch(server.url, immutableAssign(query, { tagsAllOf: [ 'blAbla' ] })) - expect(res2.body.total).to.equal(0) + { + const body = await command.advancedVideoSearch({ search: query }) + expect(body.total).to.equal(2) + } - const res3 = await advancedVideosSearch(server.url, immutableAssign(query, { tagsAllOf: [ 'bbbb', 'CCCC' ] })) - expect(res3.body.total).to.equal(1) + { + const body = await command.advancedVideoSearch({ search: { ...query, tagsAllOf: [ 'blAbla' ] } }) + expect(body.total).to.equal(0) + } + + { + const body = await command.advancedVideoSearch({ search: { ...query, tagsAllOf: [ 'bbbb', 'CCCC' ] } }) + expect(body.total).to.equal(1) + } }) it('Should search by category', async function () { @@ -246,12 +261,17 @@ describe('Test videos search', function () { search: '6666', categoryOneOf: [ 3 ] } - const res1 = await advancedVideosSearch(server.url, query) - expect(res1.body.total).to.equal(1) - expect(res1.body.data[0].name).to.equal('6666 7777 8888') - const res2 = await advancedVideosSearch(server.url, immutableAssign(query, { categoryOneOf: [ 2 ] })) - expect(res2.body.total).to.equal(0) + { + const body = await command.advancedVideoSearch({ search: query }) + expect(body.total).to.equal(1) + expect(body.data[0].name).to.equal('6666 7777 8888') + } + + { + const body = await command.advancedVideoSearch({ search: { ...query, categoryOneOf: [ 2 ] } }) + expect(body.total).to.equal(0) + } }) it('Should search by licence', async function () { @@ -259,13 +279,18 @@ describe('Test videos search', function () { search: '4444 5555', licenceOneOf: [ 2 ] } - const res1 = await advancedVideosSearch(server.url, query) - expect(res1.body.total).to.equal(2) - expect(res1.body.data[0].name).to.equal('3333 4444 5555') - expect(res1.body.data[1].name).to.equal('3333 4444 5555 duplicate') - const res2 = await advancedVideosSearch(server.url, immutableAssign(query, { licenceOneOf: [ 3 ] })) - expect(res2.body.total).to.equal(0) + { + const body = await command.advancedVideoSearch({ search: query }) + expect(body.total).to.equal(2) + expect(body.data[0].name).to.equal('3333 4444 5555') + expect(body.data[1].name).to.equal('3333 4444 5555 duplicate') + } + + { + const body = await command.advancedVideoSearch({ search: { ...query, licenceOneOf: [ 3 ] } }) + expect(body.total).to.equal(0) + } }) it('Should search by languages', async function () { @@ -275,23 +300,23 @@ describe('Test videos search', function () { } { - const res = await advancedVideosSearch(server.url, query) - expect(res.body.total).to.equal(2) - expect(res.body.data[0].name).to.equal('1111 2222 3333 - 3') - expect(res.body.data[1].name).to.equal('1111 2222 3333 - 4') + const body = await command.advancedVideoSearch({ search: query }) + expect(body.total).to.equal(2) + expect(body.data[0].name).to.equal('1111 2222 3333 - 3') + expect(body.data[1].name).to.equal('1111 2222 3333 - 4') } { - const res = await advancedVideosSearch(server.url, immutableAssign(query, { languageOneOf: [ 'pl', 'en', '_unknown' ] })) - expect(res.body.total).to.equal(3) - expect(res.body.data[0].name).to.equal('1111 2222 3333 - 3') - expect(res.body.data[1].name).to.equal('1111 2222 3333 - 4') - expect(res.body.data[2].name).to.equal('1111 2222 3333 - 5') + const body = await command.advancedVideoSearch({ search: { ...query, languageOneOf: [ 'pl', 'en', '_unknown' ] } }) + expect(body.total).to.equal(3) + expect(body.data[0].name).to.equal('1111 2222 3333 - 3') + expect(body.data[1].name).to.equal('1111 2222 3333 - 4') + expect(body.data[2].name).to.equal('1111 2222 3333 - 5') } { - const res = await advancedVideosSearch(server.url, immutableAssign(query, { languageOneOf: [ 'eo' ] })) - expect(res.body.total).to.equal(0) + const body = await command.advancedVideoSearch({ search: { ...query, languageOneOf: [ 'eo' ] } }) + expect(body.total).to.equal(0) } }) @@ -301,10 +326,10 @@ describe('Test videos search', function () { startDate } - const res = await advancedVideosSearch(server.url, query) - expect(res.body.total).to.equal(4) + const body = await command.advancedVideoSearch({ search: query }) + expect(body.total).to.equal(4) - const videos = res.body.data + const videos = body.data expect(videos[0].name).to.equal('1111 2222 3333 - 5') expect(videos[1].name).to.equal('1111 2222 3333 - 6') expect(videos[2].name).to.equal('1111 2222 3333 - 7') @@ -320,10 +345,10 @@ describe('Test videos search', function () { licenceOneOf: [ 1, 4 ] } - const res = await advancedVideosSearch(server.url, query) - expect(res.body.total).to.equal(4) + const body = await command.advancedVideoSearch({ search: query }) + expect(body.total).to.equal(4) - const videos = res.body.data + const videos = body.data expect(videos[0].name).to.equal('1111 2222 3333') expect(videos[1].name).to.equal('1111 2222 3333 - 6') expect(videos[2].name).to.equal('1111 2222 3333 - 7') @@ -340,10 +365,10 @@ describe('Test videos search', function () { sort: '-name' } - const res = await advancedVideosSearch(server.url, query) - expect(res.body.total).to.equal(4) + const body = await command.advancedVideoSearch({ search: query }) + expect(body.total).to.equal(4) - const videos = res.body.data + const videos = body.data expect(videos[0].name).to.equal('1111 2222 3333 - 8') expect(videos[1].name).to.equal('1111 2222 3333 - 7') expect(videos[2].name).to.equal('1111 2222 3333 - 6') @@ -362,10 +387,10 @@ describe('Test videos search', function () { count: 1 } - const res = await advancedVideosSearch(server.url, query) - expect(res.body.total).to.equal(4) + const body = await command.advancedVideoSearch({ search: query }) + expect(body.total).to.equal(4) - const videos = res.body.data + const videos = body.data expect(videos[0].name).to.equal('1111 2222 3333 - 8') }) @@ -381,10 +406,10 @@ describe('Test videos search', function () { count: 1 } - const res = await advancedVideosSearch(server.url, query) - expect(res.body.total).to.equal(4) + const body = await command.advancedVideoSearch({ search: query }) + expect(body.total).to.equal(4) - const videos = res.body.data + const videos = body.data expect(videos[0].name).to.equal('1111 2222 3333') }) @@ -399,32 +424,32 @@ describe('Test videos search', function () { { const query = immutableAssign(baseQuery, { originallyPublishedStartDate: '2019-02-11T09:58:08.286Z' }) - const res = await advancedVideosSearch(server.url, query) + const body = await command.advancedVideoSearch({ search: query }) - expect(res.body.total).to.equal(1) - expect(res.body.data[0].name).to.equal('1111 2222 3333 - 7') + expect(body.total).to.equal(1) + expect(body.data[0].name).to.equal('1111 2222 3333 - 7') } { const query = immutableAssign(baseQuery, { originallyPublishedEndDate: '2019-03-11T09:58:08.286Z' }) - const res = await advancedVideosSearch(server.url, query) + const body = await command.advancedVideoSearch({ search: query }) - expect(res.body.total).to.equal(1) - expect(res.body.data[0].name).to.equal('1111 2222 3333 - 7') + expect(body.total).to.equal(1) + expect(body.data[0].name).to.equal('1111 2222 3333 - 7') } { const query = immutableAssign(baseQuery, { originallyPublishedEndDate: '2019-01-11T09:58:08.286Z' }) - const res = await advancedVideosSearch(server.url, query) + const body = await command.advancedVideoSearch({ search: query }) - expect(res.body.total).to.equal(0) + expect(body.total).to.equal(0) } { const query = immutableAssign(baseQuery, { originallyPublishedStartDate: '2019-03-11T09:58:08.286Z' }) - const res = await advancedVideosSearch(server.url, query) + const body = await command.advancedVideoSearch({ search: query }) - expect(res.body.total).to.equal(0) + expect(body.total).to.equal(0) } { @@ -432,9 +457,9 @@ describe('Test videos search', function () { originallyPublishedStartDate: '2019-01-11T09:58:08.286Z', originallyPublishedEndDate: '2019-01-10T09:58:08.286Z' }) - const res = await advancedVideosSearch(server.url, query) + const body = await command.advancedVideoSearch({ search: query }) - expect(res.body.total).to.equal(0) + expect(body.total).to.equal(0) } { @@ -442,19 +467,19 @@ describe('Test videos search', function () { originallyPublishedStartDate: '2019-01-11T09:58:08.286Z', originallyPublishedEndDate: '2019-04-11T09:58:08.286Z' }) - const res = await advancedVideosSearch(server.url, query) + const body = await command.advancedVideoSearch({ search: query }) - expect(res.body.total).to.equal(1) - expect(res.body.data[0].name).to.equal('1111 2222 3333 - 7') + expect(body.total).to.equal(1) + expect(body.data[0].name).to.equal('1111 2222 3333 - 7') } }) it('Should search by UUID', async function () { const search = videoUUID - const res = await advancedVideosSearch(server.url, { search }) + const body = await command.advancedVideoSearch({ search: { search } }) - expect(res.body.total).to.equal(1) - expect(res.body.data[0].name).to.equal('1111 2222 3333 - 3') + expect(body.total).to.equal(1) + expect(body.data[0].name).to.equal('1111 2222 3333 - 3') }) it('Should search by live', async function () { @@ -471,10 +496,10 @@ describe('Test videos search', function () { } { - const res = await advancedVideosSearch(server.url, { isLive: true }) + const body = await command.advancedVideoSearch({ search: { isLive: true } }) - expect(res.body.total).to.equal(0) - expect(res.body.data).to.have.lengthOf(0) + expect(body.total).to.equal(0) + expect(body.data).to.have.lengthOf(0) } { @@ -482,15 +507,15 @@ describe('Test videos search', function () { const resLive = await createLive(server.url, server.accessToken, liveOptions) const liveVideoId = resLive.body.video.uuid - const command = await sendRTMPStreamInVideo(server.url, server.accessToken, liveVideoId) + const ffmpegCommand = await sendRTMPStreamInVideo(server.url, server.accessToken, liveVideoId) await waitUntilLivePublished(server.url, server.accessToken, liveVideoId) - const res = await advancedVideosSearch(server.url, { isLive: true }) + const body = await command.advancedVideoSearch({ search: { isLive: true } }) - expect(res.body.total).to.equal(1) - expect(res.body.data[0].name).to.equal('live') + expect(body.total).to.equal(1) + expect(body.data[0].name).to.equal('live') - await stopFfmpeg(command) + await stopFfmpeg(ffmpegCommand) } }) diff --git a/server/tests/api/videos/video-nsfw.ts b/server/tests/api/videos/video-nsfw.ts index 6c98c9f12..24a4c6152 100644 --- a/server/tests/api/videos/video-nsfw.ts +++ b/server/tests/api/videos/video-nsfw.ts @@ -14,8 +14,6 @@ import { getVideoChannelVideos, getVideosList, getVideosListWithToken, - searchVideo, - searchVideoWithToken, ServerInfo, setAccessTokensToServers, updateCustomConfig, @@ -23,7 +21,7 @@ import { uploadVideo, userLogin } from '@shared/extra-utils' -import { CustomConfig, ServerConfig, User, VideosOverview } from '@shared/models' +import { BooleanBothQuery, CustomConfig, ServerConfig, User, VideosOverview } from '@shared/models' const expect = chai.expect @@ -37,7 +35,7 @@ describe('Test video NSFW policy', function () { let userAccessToken: string let customConfig: CustomConfig - function getVideosFunctions (token?: string, query = {}) { + function getVideosFunctions (token?: string, query: { nsfw?: BooleanBothQuery } = {}) { return getMyUserInformation(server.url, server.accessToken) .then(res => { const user: User = res.body @@ -49,7 +47,7 @@ describe('Test video NSFW policy', function () { if (token) { promises = [ getVideosListWithToken(server.url, token, query), - searchVideoWithToken(server.url, 'n', token, query), + server.searchCommand.advancedVideoSearch({ token, search: { search: 'n', ...query } }), getAccountVideos(server.url, token, accountName, 0, 5, undefined, query), getVideoChannelVideos(server.url, token, videoChannelName, 0, 5, undefined, query) ] @@ -66,7 +64,7 @@ describe('Test video NSFW policy', function () { promises = [ getVideosList(server.url), - searchVideo(server.url, 'n'), + server.searchCommand.searchVideos({ search: 'n' }), getAccountVideos(server.url, undefined, accountName, 0, 5), getVideoChannelVideos(server.url, undefined, videoChannelName, 0, 5) ] @@ -230,7 +228,7 @@ describe('Test video NSFW policy', function () { }) it('Should display NSFW videos when the nsfw param === true', async function () { - for (const res of await getVideosFunctions(server.accessToken, { nsfw: true })) { + for (const res of await getVideosFunctions(server.accessToken, { nsfw: 'true' })) { expect(res.body.total).to.equal(1) const videos = res.body.data @@ -240,7 +238,7 @@ describe('Test video NSFW policy', function () { }) it('Should hide NSFW videos when the nsfw param === true', async function () { - for (const res of await getVideosFunctions(server.accessToken, { nsfw: false })) { + for (const res of await getVideosFunctions(server.accessToken, { nsfw: 'false' })) { expect(res.body.total).to.equal(1) const videos = res.body.data diff --git a/server/tests/api/videos/videos-history.ts b/server/tests/api/videos/videos-history.ts index b25cff879..209b93014 100644 --- a/server/tests/api/videos/videos-history.ts +++ b/server/tests/api/videos/videos-history.ts @@ -1,7 +1,8 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ -import * as chai from 'chai' import 'mocha' +import * as chai from 'chai' +import { HttpStatusCode } from '@shared/core-utils' import { cleanupTests, createUser, @@ -10,17 +11,15 @@ import { getVideoWithToken, killallServers, reRunServer, - searchVideoWithToken, ServerInfo, setAccessTokensToServers, updateMyUser, uploadVideo, userLogin, wait -} from '../../../../shared/extra-utils' -import { Video, VideoDetails } from '../../../../shared/models/videos' -import { listMyVideosHistory, removeMyVideosHistory, userWatchVideo } from '../../../../shared/extra-utils/videos/video-history' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' +} from '@shared/extra-utils' +import { listMyVideosHistory, removeMyVideosHistory, userWatchVideo } from '@shared/extra-utils/videos/video-history' +import { Video, VideoDetails } from '@shared/models' const expect = chai.expect @@ -89,8 +88,8 @@ describe('Test videos history', function () { } { - const res = await searchVideoWithToken(server.url, 'video', server.accessToken) - videosOfVideos.push(res.body.data) + const body = await server.searchCommand.searchVideos({ token: server.accessToken, search: 'video' }) + videosOfVideos.push(body.data) } for (const videos of videosOfVideos) { diff --git a/server/tests/plugins/filter-hooks.ts b/server/tests/plugins/filter-hooks.ts index 644b41dea..e2ec5457b 100644 --- a/server/tests/plugins/filter-hooks.ts +++ b/server/tests/plugins/filter-hooks.ts @@ -2,17 +2,15 @@ import 'mocha' import * as chai from 'chai' -import { advancedVideoChannelSearch } from '@shared/extra-utils/search/video-channels' -import { ServerConfig } from '@shared/models' -import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '@shared/core-utils' import { addVideoCommentReply, addVideoCommentThread, - advancedVideoPlaylistSearch, - advancedVideosSearch, + cleanupTests, createLive, createVideoPlaylist, doubleFollow, + flushAndRunMultipleServers, getAccountVideos, getConfig, getMyVideos, @@ -28,17 +26,19 @@ import { installPlugin, makeRawRequest, registerUser, + ServerInfo, setAccessTokensToServers, setDefaultVideoChannel, updateCustomSubConfig, updateVideo, uploadVideo, uploadVideoAndGetId, - waitJobs -} from '../../../shared/extra-utils' -import { cleanupTests, flushAndRunMultipleServers, ServerInfo, waitUntilLog } from '../../../shared/extra-utils/server/servers' -import { getGoodVideoUrl, getMyVideoImports, importVideo } from '../../../shared/extra-utils/videos/video-imports' + waitJobs, + waitUntilLog +} from '@shared/extra-utils' +import { getGoodVideoUrl, getMyVideoImports, importVideo } from '@shared/extra-utils/videos/video-imports' import { + ServerConfig, VideoCommentThreadTree, VideoDetails, VideoImport, @@ -46,7 +46,7 @@ import { VideoPlaylist, VideoPlaylistPrivacy, VideoPrivacy -} from '../../../shared/models/videos' +} from '@shared/models' const expect = chai.expect @@ -486,8 +486,10 @@ describe('Test plugin filter hooks', function () { }) it('Should run filter:api.search.videos.local.list.{params,result}', async function () { - await advancedVideosSearch(servers[0].url, { - search: 'Sun Quan' + await servers[0].searchCommand.advancedVideoSearch({ + search: { + search: 'Sun Quan' + } }) await waitUntilLog(servers[0], 'Run hook filter:api.search.videos.local.list.params', 1) @@ -495,9 +497,11 @@ describe('Test plugin filter hooks', function () { }) it('Should run filter:api.search.videos.index.list.{params,result}', async function () { - await advancedVideosSearch(servers[0].url, { - search: 'Sun Quan', - searchTarget: 'search-index' + await servers[0].searchCommand.advancedVideoSearch({ + search: { + search: 'Sun Quan', + searchTarget: 'search-index' + } }) await waitUntilLog(servers[0], 'Run hook filter:api.search.videos.local.list.params', 1) @@ -507,8 +511,10 @@ describe('Test plugin filter hooks', function () { }) it('Should run filter:api.search.video-channels.local.list.{params,result}', async function () { - await advancedVideoChannelSearch(servers[0].url, { - search: 'Sun Ce' + await servers[0].searchCommand.advancedChannelSearch({ + search: { + search: 'Sun Ce' + } }) await waitUntilLog(servers[0], 'Run hook filter:api.search.video-channels.local.list.params', 1) @@ -516,9 +522,11 @@ describe('Test plugin filter hooks', function () { }) it('Should run filter:api.search.video-channels.index.list.{params,result}', async function () { - await advancedVideoChannelSearch(servers[0].url, { - search: 'Sun Ce', - searchTarget: 'search-index' + await servers[0].searchCommand.advancedChannelSearch({ + search: { + search: 'Sun Ce', + searchTarget: 'search-index' + } }) await waitUntilLog(servers[0], 'Run hook filter:api.search.video-channels.local.list.params', 1) @@ -528,8 +536,10 @@ describe('Test plugin filter hooks', function () { }) it('Should run filter:api.search.video-playlists.local.list.{params,result}', async function () { - await advancedVideoPlaylistSearch(servers[0].url, { - search: 'Sun Jian' + await servers[0].searchCommand.advancedPlaylistSearch({ + search: { + search: 'Sun Jian' + } }) await waitUntilLog(servers[0], 'Run hook filter:api.search.video-playlists.local.list.params', 1) @@ -537,9 +547,11 @@ describe('Test plugin filter hooks', function () { }) it('Should run filter:api.search.video-playlists.index.list.{params,result}', async function () { - await advancedVideoPlaylistSearch(servers[0].url, { - search: 'Sun Jian', - searchTarget: 'search-index' + await servers[0].searchCommand.advancedPlaylistSearch({ + search: { + search: 'Sun Jian', + searchTarget: 'search-index' + } }) await waitUntilLog(servers[0], 'Run hook filter:api.search.video-playlists.local.list.params', 1) diff --git a/shared/extra-utils/index.ts b/shared/extra-utils/index.ts index 38c8c4c1c..067e6fb65 100644 --- a/shared/extra-utils/index.ts +++ b/shared/extra-utils/index.ts @@ -11,9 +11,7 @@ export * from './overviews' export * from './requests/check-api-params' export * from './requests/requests' -export * from './search/video-channels' -export * from './search/video-playlists' -export * from './search/videos' +export * from './search' export * from './server/activitypub' export * from './server/clients' diff --git a/shared/extra-utils/overviews/overviews-command.ts b/shared/extra-utils/overviews/overviews-command.ts index 0ac3cbd33..6f56b0ce4 100644 --- a/shared/extra-utils/overviews/overviews-command.ts +++ b/shared/extra-utils/overviews/overviews-command.ts @@ -6,7 +6,6 @@ export class OverviewsCommand extends AbstractCommand { getVideos (options: OverrideCommandOptions & { page: number - token?: string }) { const { token, page } = options const path = '/api/v1/overviews/videos' diff --git a/shared/extra-utils/search/index.ts b/shared/extra-utils/search/index.ts new file mode 100644 index 000000000..48dbe8ae9 --- /dev/null +++ b/shared/extra-utils/search/index.ts @@ -0,0 +1 @@ +export * from './search-command' diff --git a/shared/extra-utils/search/search-command.ts b/shared/extra-utils/search/search-command.ts new file mode 100644 index 000000000..d4cfab32b --- /dev/null +++ b/shared/extra-utils/search/search-command.ts @@ -0,0 +1,101 @@ +import { + ResultList, + Video, + VideoChannel, + VideoChannelsSearchQuery, + VideoPlaylist, + VideoPlaylistsSearchQuery, + VideosSearchQuery +} from '@shared/models' +import { HttpStatusCode } from '../../core-utils/miscs/http-error-codes' +import { AbstractCommand, OverrideCommandOptions } from '../shared' + +export class SearchCommand extends AbstractCommand { + + searchChannels (options: OverrideCommandOptions & { + search: string + }) { + return this.advancedChannelSearch({ + ...options, + + search: { search: options.search } + }) + } + + advancedChannelSearch (options: OverrideCommandOptions & { + search: VideoChannelsSearchQuery + }) { + const { search, token } = options + const path = '/api/v1/search/video-channels' + + return this.getRequestBody>({ + ...options, + + token: token || null, + + path, + query: search, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } + + searchPlaylists (options: OverrideCommandOptions & { + search: string + }) { + return this.advancedPlaylistSearch({ + ...options, + + search: { search: options.search } + }) + } + + advancedPlaylistSearch (options: OverrideCommandOptions & { + search: VideoPlaylistsSearchQuery + }) { + const { search, token } = options + const path = '/api/v1/search/video-playlists' + + return this.getRequestBody>({ + ...options, + + token: token || null, + + path, + query: search, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } + + searchVideos (options: OverrideCommandOptions & { + search: string + sort?: string + }) { + const { search, sort } = options + + return this.advancedVideoSearch({ + ...options, + + search: { + search: search, + sort: sort ?? '-publishedAt' + } + }) + } + + advancedVideoSearch (options: OverrideCommandOptions & { + search: VideosSearchQuery + }) { + const { search, token } = options + const path = '/api/v1/search/videos' + + return this.getRequestBody>({ + ...options, + + token: token || null, + + path, + query: search, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } +} diff --git a/shared/extra-utils/search/video-channels.ts b/shared/extra-utils/search/video-channels.ts deleted file mode 100644 index 8e0f42578..000000000 --- a/shared/extra-utils/search/video-channels.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { VideoChannelsSearchQuery } from '@shared/models' -import { makeGetRequest } from '../requests/requests' -import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' - -function searchVideoChannel (url: string, search: string, token?: string, statusCodeExpected = HttpStatusCode.OK_200) { - const path = '/api/v1/search/video-channels' - - return makeGetRequest({ - url, - path, - query: { - sort: '-createdAt', - search - }, - token, - statusCodeExpected - }) -} - -function advancedVideoChannelSearch (url: string, search: VideoChannelsSearchQuery) { - const path = '/api/v1/search/video-channels' - - return makeGetRequest({ - url, - path, - query: search, - statusCodeExpected: HttpStatusCode.OK_200 - }) -} - -// --------------------------------------------------------------------------- - -export { - searchVideoChannel, - advancedVideoChannelSearch -} diff --git a/shared/extra-utils/search/video-playlists.ts b/shared/extra-utils/search/video-playlists.ts deleted file mode 100644 index c22831df7..000000000 --- a/shared/extra-utils/search/video-playlists.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { VideoPlaylistsSearchQuery } from '@shared/models' -import { HttpStatusCode } from '../../core-utils/miscs/http-error-codes' -import { makeGetRequest } from '../requests/requests' - -function searchVideoPlaylists (url: string, search: string, token?: string, statusCodeExpected = HttpStatusCode.OK_200) { - const path = '/api/v1/search/video-playlists' - - return makeGetRequest({ - url, - path, - query: { - sort: '-createdAt', - search - }, - token, - statusCodeExpected - }) -} - -function advancedVideoPlaylistSearch (url: string, search: VideoPlaylistsSearchQuery) { - const path = '/api/v1/search/video-playlists' - - return makeGetRequest({ - url, - path, - query: search, - statusCodeExpected: HttpStatusCode.OK_200 - }) -} - -// --------------------------------------------------------------------------- - -export { - searchVideoPlaylists, - advancedVideoPlaylistSearch -} diff --git a/shared/extra-utils/search/videos.ts b/shared/extra-utils/search/videos.ts deleted file mode 100644 index db6edbd58..000000000 --- a/shared/extra-utils/search/videos.ts +++ /dev/null @@ -1,64 +0,0 @@ -/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ - -import * as request from 'supertest' -import { VideosSearchQuery } from '../../models/search' -import { immutableAssign } from '../miscs/miscs' -import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' - -function searchVideo (url: string, search: string, sort = '-publishedAt') { - const path = '/api/v1/search/videos' - - const query = { sort, search: search } - const req = request(url) - .get(path) - .query(query) - .set('Accept', 'application/json') - - return req.expect(HttpStatusCode.OK_200) - .expect('Content-Type', /json/) -} - -function searchVideoWithToken (url: string, search: string, token: string, query: { nsfw?: boolean } = {}) { - const path = '/api/v1/search/videos' - const req = request(url) - .get(path) - .set('Authorization', 'Bearer ' + token) - .query(immutableAssign(query, { sort: '-publishedAt', search })) - .set('Accept', 'application/json') - - return req.expect(HttpStatusCode.OK_200) - .expect('Content-Type', /json/) -} - -function searchVideoWithSort (url: string, search: string, sort: string) { - const path = '/api/v1/search/videos' - - const query = { search, sort } - - return request(url) - .get(path) - .query(query) - .set('Accept', 'application/json') - .expect(HttpStatusCode.OK_200) - .expect('Content-Type', /json/) -} - -function advancedVideosSearch (url: string, options: VideosSearchQuery) { - const path = '/api/v1/search/videos' - - return request(url) - .get(path) - .query(options) - .set('Accept', 'application/json') - .expect(HttpStatusCode.OK_200) - .expect('Content-Type', /json/) -} - -// --------------------------------------------------------------------------- - -export { - searchVideo, - advancedVideosSearch, - searchVideoWithToken, - searchVideoWithSort -} diff --git a/shared/extra-utils/server/servers.ts b/shared/extra-utils/server/servers.ts index 70be96cf6..8ccf790fc 100644 --- a/shared/extra-utils/server/servers.ts +++ b/shared/extra-utils/server/servers.ts @@ -15,6 +15,7 @@ import { buildServerDirectory, getFileSize, isGithubCI, root, wait } from '../mi import { AbusesCommand } from '../moderation' import { OverviewsCommand } from '../overviews' import { makeGetRequest } from '../requests/requests' +import { SearchCommand } from '../search' interface ServerInfo { app: ChildProcess @@ -75,6 +76,7 @@ interface ServerInfo { logsCommand?: LogsCommand abusesCommand?: AbusesCommand overviewsCommand?: OverviewsCommand + searchCommand?: SearchCommand } function parallelTests () { @@ -287,6 +289,7 @@ async function runServer (server: ServerInfo, configOverrideArg?: any, args = [] server.logsCommand = new LogsCommand(server) server.abusesCommand = new AbusesCommand(server) server.overviewsCommand = new OverviewsCommand(server) + server.searchCommand = new SearchCommand(server) res(server) }) diff --git a/shared/extra-utils/videos/videos.ts b/shared/extra-utils/videos/videos.ts index 469ea4d63..a45c0402a 100644 --- a/shared/extra-utils/videos/videos.ts +++ b/shared/extra-utils/videos/videos.ts @@ -10,7 +10,7 @@ import validator from 'validator' import { getLowercaseExtension } from '@server/helpers/core-utils' import { buildUUID } from '@server/helpers/uuid' import { HttpStatusCode } from '@shared/core-utils' -import { VideosCommonQuery } from '@shared/models' +import { BooleanBothQuery, VideosCommonQuery } from '@shared/models' import { loadLanguages, VIDEO_CATEGORIES, VIDEO_LANGUAGES, VIDEO_LICENCES, VIDEO_PRIVACIES } from '../../../server/initializers/constants' import { VideoDetails, VideoPrivacy } from '../../models/videos' import { @@ -159,7 +159,7 @@ function getVideosList (url: string) { .expect('Content-Type', /json/) } -function getVideosListWithToken (url: string, token: string, query: { nsfw?: boolean } = {}) { +function getVideosListWithToken (url: string, token: string, query: { nsfw?: BooleanBothQuery } = {}) { const path = '/api/v1/videos' return request(url) @@ -219,7 +219,7 @@ function getAccountVideos ( count: number, sort?: string, query: { - nsfw?: boolean + nsfw?: BooleanBothQuery search?: string } = {} ) { @@ -245,7 +245,7 @@ function getVideoChannelVideos ( start: number, count: number, sort?: string, - query: { nsfw?: boolean } = {} + query: { nsfw?: BooleanBothQuery } = {} ) { const path = '/api/v1/video-channels/' + videoChannelName + '/videos' -- cgit v1.2.3 From 2d1ad5b96063d1e430ca99128a15e2e56cb614e0 Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Tue, 6 Jul 2021 15:33:39 +0200 Subject: Move AP request in requests file --- .../tests/api/notifications/moderation-notifications.ts | 2 +- server/tests/api/search/search-activitypub-videos.ts | 2 +- server/tests/api/videos/videos-overview.ts | 1 - shared/extra-utils/index.ts | 1 - shared/extra-utils/requests/requests.ts | 16 +++++++++++++--- shared/extra-utils/server/activitypub.ts | 15 --------------- 6 files changed, 15 insertions(+), 22 deletions(-) delete mode 100644 shared/extra-utils/server/activitypub.ts diff --git a/server/tests/api/notifications/moderation-notifications.ts b/server/tests/api/notifications/moderation-notifications.ts index f77719c68..c4f63200a 100644 --- a/server/tests/api/notifications/moderation-notifications.ts +++ b/server/tests/api/notifications/moderation-notifications.ts @@ -235,7 +235,7 @@ describe('Test moderation notifications', function () { const video = resVideo.body.video { - const body = await servers[0].abusesCommand.report({ token: userAccessToken, videoId: video.id, reason: 'super reason' }) + const body = await servers[0].abusesCommand.report({ token: userAccessToken, videoId: video.id, reason: 'super reason' }) abuseId = body.abuse.id } diff --git a/server/tests/api/search/search-activitypub-videos.ts b/server/tests/api/search/search-activitypub-videos.ts index 1a5130ce9..7c6455258 100644 --- a/server/tests/api/search/search-activitypub-videos.ts +++ b/server/tests/api/search/search-activitypub-videos.ts @@ -72,7 +72,7 @@ describe('Test ActivityPub videos search', function () { it('Should search a local video', async function () { const search = 'http://localhost:' + servers[0].port + '/videos/watch/' + videoServer1UUID - const body = await command.searchVideos({ search }) + const body = await command.searchVideos({ search }) expect(body.total).to.equal(1) expect(body.data).to.be.an('array') diff --git a/server/tests/api/videos/videos-overview.ts b/server/tests/api/videos/videos-overview.ts index c8e3df4bd..b3ab9e070 100644 --- a/server/tests/api/videos/videos-overview.ts +++ b/server/tests/api/videos/videos-overview.ts @@ -2,7 +2,6 @@ import 'mocha' import * as chai from 'chai' -import { Response } from 'superagent' import { addAccountToAccountBlocklist, cleanupTests, diff --git a/shared/extra-utils/index.ts b/shared/extra-utils/index.ts index 067e6fb65..9e0f6374a 100644 --- a/shared/extra-utils/index.ts +++ b/shared/extra-utils/index.ts @@ -13,7 +13,6 @@ export * from './requests/requests' export * from './search' -export * from './server/activitypub' export * from './server/clients' export * from './server/config' export * from './server/debug' diff --git a/shared/extra-utils/requests/requests.ts b/shared/extra-utils/requests/requests.ts index 8c26a3699..3fbaa31d6 100644 --- a/shared/extra-utils/requests/requests.ts +++ b/shared/extra-utils/requests/requests.ts @@ -1,11 +1,11 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/no-floating-promises */ -import * as request from 'supertest' -import { buildAbsoluteFixturePath, root } from '../miscs/miscs' import { isAbsolute, join } from 'path' -import { URL } from 'url' import { decode } from 'querystring' +import * as request from 'supertest' +import { URL } from 'url' import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' +import { buildAbsoluteFixturePath, root } from '../miscs/miscs' function get4KFileUrl () { return 'https://download.cpy.re/peertube/4k_file.txt' @@ -154,6 +154,15 @@ function makeHTMLRequest (url: string, path: string) { .expect(HttpStatusCode.OK_200) } +function makeActivityPubGetRequest (url: string, path: string, expectedStatus = HttpStatusCode.OK_200) { + return makeGetRequest({ + url, + path, + statusCodeExpected: expectedStatus, + accept: 'application/activity+json,text/html;q=0.9,\\*/\\*;q=0.8' + }) +} + function updateImageRequest (options: { url: string path: string @@ -202,6 +211,7 @@ export { makePutBodyRequest, makeDeleteRequest, makeRawRequest, + makeActivityPubGetRequest, unwrapBody, unwrapText, updateImageRequest diff --git a/shared/extra-utils/server/activitypub.ts b/shared/extra-utils/server/activitypub.ts deleted file mode 100644 index cf967ed7d..000000000 --- a/shared/extra-utils/server/activitypub.ts +++ /dev/null @@ -1,15 +0,0 @@ -import * as request from 'supertest' -import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' - -function makeActivityPubGetRequest (url: string, path: string, expectedStatus = HttpStatusCode.OK_200) { - return request(url) - .get(path) - .set('Accept', 'application/activity+json,text/html;q=0.9,\\*/\\*;q=0.8') - .expect(expectedStatus) -} - -// --------------------------------------------------------------------------- - -export { - makeActivityPubGetRequest -} -- cgit v1.2.3 From a9c58393d36d221197b48884a1960e6126ab31d7 Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Tue, 6 Jul 2021 15:53:25 +0200 Subject: Introduce contact form command --- server/tests/api/check-params/contact-form.ts | 69 ++++++----------------- server/tests/api/server/contact-form.ts | 23 ++++---- shared/extra-utils/server/contact-form-command.ts | 31 ++++++++++ shared/extra-utils/server/contact-form.ts | 31 ---------- shared/extra-utils/server/index.ts | 1 + shared/extra-utils/server/servers.ts | 3 + 6 files changed, 62 insertions(+), 96 deletions(-) create mode 100644 shared/extra-utils/server/contact-form-command.ts delete mode 100644 shared/extra-utils/server/contact-form.ts create mode 100644 shared/extra-utils/server/index.ts diff --git a/server/tests/api/check-params/contact-form.ts b/server/tests/api/check-params/contact-form.ts index 274562cbb..fb30766d9 100644 --- a/server/tests/api/check-params/contact-form.ts +++ b/server/tests/api/check-params/contact-form.ts @@ -1,10 +1,9 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ import 'mocha' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' -import { cleanupTests, flushAndRunServer, immutableAssign, killallServers, reRunServer, ServerInfo } from '../../../../shared/extra-utils' -import { MockSmtpServer } from '../../../../shared/extra-utils/mock-servers/mock-email' -import { sendContactForm } from '../../../../shared/extra-utils/server/contact-form' +import { HttpStatusCode } from '@shared/core-utils' +import { cleanupTests, flushAndRunServer, killallServers, MockSmtpServer, reRunServer, ServerInfo } from '@shared/extra-utils' +import { ContactFormCommand } from '@shared/extra-utils/server' describe('Test contact form API validators', function () { let server: ServerInfo @@ -16,6 +15,7 @@ describe('Test contact form API validators', function () { body: 'Hello, how are you?' } let emailPort: number + let command: ContactFormCommand // --------------------------------------------------------------- @@ -26,10 +26,11 @@ describe('Test contact form API validators', function () { // Email is disabled server = await flushAndRunServer(1) + command = server.contactFormCommand }) it('Should not accept a contact form if emails are disabled', async function () { - await sendContactForm(immutableAssign(defaultBody, { url: server.url, expectedStatus: HttpStatusCode.CONFLICT_409 })) + await command.send({ ...defaultBody, expectedStatus: HttpStatusCode.CONFLICT_409 }) }) it('Should not accept a contact form if it is disabled in the configuration', async function () { @@ -39,7 +40,7 @@ describe('Test contact form API validators', function () { // Contact form is disabled await reRunServer(server, { smtp: { hostname: 'localhost', port: emailPort }, contact_form: { enabled: false } }) - await sendContactForm(immutableAssign(defaultBody, { url: server.url, expectedStatus: HttpStatusCode.CONFLICT_409 })) + await command.send({ ...defaultBody, expectedStatus: HttpStatusCode.CONFLICT_409 }) }) it('Should not accept a contact form if from email is invalid', async function () { @@ -50,61 +51,25 @@ describe('Test contact form API validators', function () { // Email & contact form enabled await reRunServer(server, { smtp: { hostname: 'localhost', port: emailPort } }) - await sendContactForm(immutableAssign(defaultBody, { - url: server.url, - expectedStatus: HttpStatusCode.BAD_REQUEST_400, - fromEmail: 'badEmail' - })) - await sendContactForm(immutableAssign(defaultBody, { - url: server.url, - expectedStatus: HttpStatusCode.BAD_REQUEST_400, - fromEmail: 'badEmail@' - })) - await sendContactForm(immutableAssign(defaultBody, { - url: server.url, - expectedStatus: HttpStatusCode.BAD_REQUEST_400, - fromEmail: undefined - })) + await command.send({ ...defaultBody, fromEmail: 'badEmail', expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) + await command.send({ ...defaultBody, fromEmail: 'badEmail@', expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) + await command.send({ ...defaultBody, fromEmail: undefined, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) it('Should not accept a contact form if from name is invalid', async function () { - await sendContactForm(immutableAssign(defaultBody, { - url: server.url, - expectedStatus: HttpStatusCode.BAD_REQUEST_400, - fromName: 'name'.repeat(100) - })) - await sendContactForm(immutableAssign(defaultBody, { - url: server.url, - expectedStatus: HttpStatusCode.BAD_REQUEST_400, - fromName: '' - })) - await sendContactForm(immutableAssign(defaultBody, { - url: server.url, - expectedStatus: HttpStatusCode.BAD_REQUEST_400, - fromName: undefined - })) + await command.send({ ...defaultBody, fromName: 'name'.repeat(100), expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) + await command.send({ ...defaultBody, fromName: '', expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) + await command.send({ ...defaultBody, fromName: undefined, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) it('Should not accept a contact form if body is invalid', async function () { - await sendContactForm(immutableAssign(defaultBody, { - url: server.url, - expectedStatus: HttpStatusCode.BAD_REQUEST_400, - body: 'body'.repeat(5000) - })) - await sendContactForm(immutableAssign(defaultBody, { - url: server.url, - expectedStatus: HttpStatusCode.BAD_REQUEST_400, - body: 'a' - })) - await sendContactForm(immutableAssign(defaultBody, { - url: server.url, - expectedStatus: HttpStatusCode.BAD_REQUEST_400, - body: undefined - })) + await command.send({ ...defaultBody, body: 'body'.repeat(5000), expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) + await command.send({ ...defaultBody, body: 'a', expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) + await command.send({ ...defaultBody, body: undefined, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) it('Should accept a contact form with the correct parameters', async function () { - await sendContactForm(immutableAssign(defaultBody, { url: server.url })) + await command.send({ ...defaultBody }) }) after(async function () { diff --git a/server/tests/api/server/contact-form.ts b/server/tests/api/server/contact-form.ts index 71205723d..79c4c6748 100644 --- a/server/tests/api/server/contact-form.ts +++ b/server/tests/api/server/contact-form.ts @@ -2,17 +2,16 @@ import 'mocha' import * as chai from 'chai' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' -import { cleanupTests, flushAndRunServer, ServerInfo, setAccessTokensToServers, wait } from '../../../../shared/extra-utils' -import { MockSmtpServer } from '../../../../shared/extra-utils/mock-servers/mock-email' -import { sendContactForm } from '../../../../shared/extra-utils/server/contact-form' -import { waitJobs } from '../../../../shared/extra-utils/server/jobs' +import { HttpStatusCode } from '@shared/core-utils' +import { cleanupTests, flushAndRunServer, MockSmtpServer, ServerInfo, setAccessTokensToServers, wait, waitJobs } from '@shared/extra-utils' +import { ContactFormCommand } from '@shared/extra-utils/server' const expect = chai.expect describe('Test contact form', function () { let server: ServerInfo const emails: object[] = [] + let command: ContactFormCommand before(async function () { this.timeout(30000) @@ -27,13 +26,14 @@ describe('Test contact form', function () { } server = await flushAndRunServer(1, overrideConfig) await setAccessTokensToServers([ server ]) + + command = server.contactFormCommand }) it('Should send a contact form', async function () { this.timeout(10000) - await sendContactForm({ - url: server.url, + await command.send({ fromEmail: 'toto@example.com', body: 'my super message', subject: 'my subject', @@ -58,16 +58,14 @@ describe('Test contact form', function () { await wait(1000) - await sendContactForm({ - url: server.url, + await command.send({ fromEmail: 'toto@example.com', body: 'my super message', subject: 'my subject', fromName: 'Super toto' }) - await sendContactForm({ - url: server.url, + await command.send({ fromEmail: 'toto@example.com', body: 'my super message', fromName: 'Super toto', @@ -79,8 +77,7 @@ describe('Test contact form', function () { it('Should be able to send another contact form after a while', async function () { await wait(1000) - await sendContactForm({ - url: server.url, + await command.send({ fromEmail: 'toto@example.com', fromName: 'Super toto', subject: 'my subject', diff --git a/shared/extra-utils/server/contact-form-command.ts b/shared/extra-utils/server/contact-form-command.ts new file mode 100644 index 000000000..943e5ccbb --- /dev/null +++ b/shared/extra-utils/server/contact-form-command.ts @@ -0,0 +1,31 @@ +import { HttpStatusCode } from '../../core-utils/miscs/http-error-codes' +import { ContactForm } from '../../models/server' +import { AbstractCommand, OverrideCommandOptions } from '../shared' + +export class ContactFormCommand extends AbstractCommand { + + send (options: OverrideCommandOptions & { + fromEmail: string + fromName: string + subject: string + body: string + }) { + const path = '/api/v1/server/contact' + + const body: ContactForm = { + fromEmail: options.fromEmail, + fromName: options.fromName, + subject: options.subject, + body: options.body + } + + return this.postBodyRequest({ + ...options, + + path, + token: null, + fields: body, + defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 + }) + } +} diff --git a/shared/extra-utils/server/contact-form.ts b/shared/extra-utils/server/contact-form.ts deleted file mode 100644 index 6c9232cc6..000000000 --- a/shared/extra-utils/server/contact-form.ts +++ /dev/null @@ -1,31 +0,0 @@ -import * as request from 'supertest' -import { ContactForm } from '../../models/server' -import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' - -function sendContactForm (options: { - url: string - fromEmail: string - fromName: string - subject: string - body: string - expectedStatus?: number -}) { - const path = '/api/v1/server/contact' - - const body: ContactForm = { - fromEmail: options.fromEmail, - fromName: options.fromName, - subject: options.subject, - body: options.body - } - return request(options.url) - .post(path) - .send(body) - .expect(options.expectedStatus || HttpStatusCode.NO_CONTENT_204) -} - -// --------------------------------------------------------------------------- - -export { - sendContactForm -} diff --git a/shared/extra-utils/server/index.ts b/shared/extra-utils/server/index.ts new file mode 100644 index 000000000..4121c8828 --- /dev/null +++ b/shared/extra-utils/server/index.ts @@ -0,0 +1 @@ +export * from './contact-form-command' diff --git a/shared/extra-utils/server/servers.ts b/shared/extra-utils/server/servers.ts index 8ccf790fc..b58639ba6 100644 --- a/shared/extra-utils/server/servers.ts +++ b/shared/extra-utils/server/servers.ts @@ -16,6 +16,7 @@ import { AbusesCommand } from '../moderation' import { OverviewsCommand } from '../overviews' import { makeGetRequest } from '../requests/requests' import { SearchCommand } from '../search' +import { ContactFormCommand } from './contact-form-command' interface ServerInfo { app: ChildProcess @@ -77,6 +78,7 @@ interface ServerInfo { abusesCommand?: AbusesCommand overviewsCommand?: OverviewsCommand searchCommand?: SearchCommand + contactFormCommand?: ContactFormCommand } function parallelTests () { @@ -290,6 +292,7 @@ async function runServer (server: ServerInfo, configOverrideArg?: any, args = [] server.abusesCommand = new AbusesCommand(server) server.overviewsCommand = new OverviewsCommand(server) server.searchCommand = new SearchCommand(server) + server.contactFormCommand = new ContactFormCommand(server) res(server) }) -- cgit v1.2.3 From 883a9019085ff9013079d6b1539b86f2f519175a Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Tue, 6 Jul 2021 16:02:11 +0200 Subject: Introduce debug command --- server/controllers/api/server/debug.ts | 6 +++--- server/helpers/database-utils.ts | 10 ++++----- server/tests/api/videos/resumable-upload.ts | 5 ++--- shared/extra-utils/index.ts | 1 - shared/extra-utils/server/debug-command.ts | 32 ++++++++++++++++++++++++++++ shared/extra-utils/server/debug.ts | 33 ----------------------------- shared/extra-utils/server/index.ts | 1 + shared/extra-utils/server/jobs.ts | 9 ++++---- shared/extra-utils/server/servers.ts | 3 +++ shared/models/server/debug.model.ts | 1 + 10 files changed, 51 insertions(+), 50 deletions(-) create mode 100644 shared/extra-utils/server/debug-command.ts delete mode 100644 shared/extra-utils/server/debug.ts diff --git a/server/controllers/api/server/debug.ts b/server/controllers/api/server/debug.ts index a6e9147f3..31888e963 100644 --- a/server/controllers/api/server/debug.ts +++ b/server/controllers/api/server/debug.ts @@ -1,8 +1,8 @@ +import * as express from 'express' import { InboxManager } from '@server/lib/activitypub/inbox-manager' import { RemoveDanglingResumableUploadsScheduler } from '@server/lib/schedulers/remove-dangling-resumable-uploads-scheduler' +import { Debug, SendDebugCommand } from '@shared/models' import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' -import { SendDebugCommand } from '@shared/models' -import * as express from 'express' import { UserRight } from '../../../../shared/models/users' import { authenticate, ensureUserHasRight } from '../../../middlewares' @@ -32,7 +32,7 @@ function getDebug (req: express.Request, res: express.Response) { return res.json({ ip: req.ip, activityPubMessagesWaiting: InboxManager.Instance.getActivityPubMessagesWaiting() - }) + } as Debug) } async function runCommand (req: express.Request, res: express.Response) { diff --git a/server/helpers/database-utils.ts b/server/helpers/database-utils.ts index b5dc70c17..cbd7aa401 100644 --- a/server/helpers/database-utils.ts +++ b/server/helpers/database-utils.ts @@ -6,7 +6,7 @@ import { sequelizeTypescript } from '@server/initializers/database' import { logger } from './logger' function retryTransactionWrapper ( - functionToRetry: (arg1: A, arg2: B, arg3: C, arg4: D) => Promise | Bluebird, + functionToRetry: (arg1: A, arg2: B, arg3: C, arg4: D) => Promise, arg1: A, arg2: B, arg3: C, @@ -14,20 +14,20 @@ function retryTransactionWrapper ( ): Promise function retryTransactionWrapper ( - functionToRetry: (arg1: A, arg2: B, arg3: C) => Promise | Bluebird, + functionToRetry: (arg1: A, arg2: B, arg3: C) => Promise, arg1: A, arg2: B, arg3: C ): Promise function retryTransactionWrapper ( - functionToRetry: (arg1: A, arg2: B) => Promise | Bluebird, + functionToRetry: (arg1: A, arg2: B) => Promise, arg1: A, arg2: B ): Promise function retryTransactionWrapper ( - functionToRetry: (arg1: A) => Promise | Bluebird, + functionToRetry: (arg1: A) => Promise, arg1: A ): Promise @@ -36,7 +36,7 @@ function retryTransactionWrapper ( ): Promise function retryTransactionWrapper ( - functionToRetry: (...args: any[]) => Promise | Bluebird, + functionToRetry: (...args: any[]) => Promise, ...args: any[] ): Promise { return transactionRetryer(callback => { diff --git a/server/tests/api/videos/resumable-upload.ts b/server/tests/api/videos/resumable-upload.ts index 4fc3317df..6c01c7e78 100644 --- a/server/tests/api/videos/resumable-upload.ts +++ b/server/tests/api/videos/resumable-upload.ts @@ -12,7 +12,6 @@ import { flushAndRunServer, getMyUserInformation, prepareResumableUpload, - sendDebugCommand, sendResumableChunks, ServerInfo, setAccessTokensToServers, @@ -138,13 +137,13 @@ describe('Test resumable upload', function () { }) it('Should not delete recent uploads', async function () { - await sendDebugCommand(server.url, server.accessToken, { command: 'remove-dandling-resumable-uploads' }) + await server.debugCommand.sendCommand({ body: { command: 'remove-dandling-resumable-uploads' } }) expect(await countResumableUploads()).to.equal(2) }) it('Should delete old uploads', async function () { - await sendDebugCommand(server.url, server.accessToken, { command: 'remove-dandling-resumable-uploads' }) + await server.debugCommand.sendCommand({ body: { command: 'remove-dandling-resumable-uploads' } }) expect(await countResumableUploads()).to.equal(0) }) diff --git a/shared/extra-utils/index.ts b/shared/extra-utils/index.ts index 9e0f6374a..7b5835e47 100644 --- a/shared/extra-utils/index.ts +++ b/shared/extra-utils/index.ts @@ -15,7 +15,6 @@ export * from './search' export * from './server/clients' export * from './server/config' -export * from './server/debug' export * from './server/follows' export * from './server/jobs' export * from './server/plugins' diff --git a/shared/extra-utils/server/debug-command.ts b/shared/extra-utils/server/debug-command.ts new file mode 100644 index 000000000..eecbb1711 --- /dev/null +++ b/shared/extra-utils/server/debug-command.ts @@ -0,0 +1,32 @@ +import { Debug, SendDebugCommand } from '@shared/models' +import { HttpStatusCode } from '../../core-utils/miscs/http-error-codes' +import { AbstractCommand, OverrideCommandOptions } from '../shared' + +export class DebugCommand extends AbstractCommand { + + getDebug (options: OverrideCommandOptions = {}) { + const path = '/api/v1/server/debug' + + return this.getRequestBody({ + ...options, + + path, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } + + sendCommand (options: OverrideCommandOptions & { + body: SendDebugCommand + }) { + const { body } = options + const path = '/api/v1/server/debug/run-command' + + return this.postBodyRequest({ + ...options, + + path, + fields: body, + defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 + }) + } +} diff --git a/shared/extra-utils/server/debug.ts b/shared/extra-utils/server/debug.ts deleted file mode 100644 index f196812b7..000000000 --- a/shared/extra-utils/server/debug.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { makeGetRequest, makePostBodyRequest } from '../requests/requests' -import { HttpStatusCode } from '../../core-utils/miscs/http-error-codes' -import { SendDebugCommand } from '@shared/models' - -function getDebug (url: string, token: string) { - const path = '/api/v1/server/debug' - - return makeGetRequest({ - url, - path, - token, - statusCodeExpected: HttpStatusCode.OK_200 - }) -} - -function sendDebugCommand (url: string, token: string, body: SendDebugCommand) { - const path = '/api/v1/server/debug/run-command' - - return makePostBodyRequest({ - url, - path, - token, - fields: body, - statusCodeExpected: HttpStatusCode.NO_CONTENT_204 - }) -} - -// --------------------------------------------------------------------------- - -export { - getDebug, - sendDebugCommand -} diff --git a/shared/extra-utils/server/index.ts b/shared/extra-utils/server/index.ts index 4121c8828..f0071ba72 100644 --- a/shared/extra-utils/server/index.ts +++ b/shared/extra-utils/server/index.ts @@ -1 +1,2 @@ export * from './contact-form-command' +export * from './debug-command' diff --git a/shared/extra-utils/server/jobs.ts b/shared/extra-utils/server/jobs.ts index 763374e03..a3683913a 100644 --- a/shared/extra-utils/server/jobs.ts +++ b/shared/extra-utils/server/jobs.ts @@ -1,7 +1,7 @@ import * as request from 'supertest' import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' -import { getDebug, makeGetRequest } from '../../../shared/extra-utils' -import { Job, JobState, JobType, ServerDebug } from '../../models' +import { makeGetRequest } from '../../../shared/extra-utils' +import { Job, JobState, JobType } from '../../models' import { wait } from '../miscs/miscs' import { ServerInfo } from './servers' @@ -90,9 +90,8 @@ async function waitJobs (serversArg: ServerInfo[] | ServerInfo) { tasks.push(p) } - const p = getDebug(server.url, server.accessToken) - .then(res => res.body) - .then((obj: ServerDebug) => { + const p = server.debugCommand.getDebug() + .then(obj => { if (obj.activityPubMessagesWaiting !== 0) { pendingRequests = true } diff --git a/shared/extra-utils/server/servers.ts b/shared/extra-utils/server/servers.ts index b58639ba6..30e712ab8 100644 --- a/shared/extra-utils/server/servers.ts +++ b/shared/extra-utils/server/servers.ts @@ -17,6 +17,7 @@ import { OverviewsCommand } from '../overviews' import { makeGetRequest } from '../requests/requests' import { SearchCommand } from '../search' import { ContactFormCommand } from './contact-form-command' +import { DebugCommand } from './debug-command' interface ServerInfo { app: ChildProcess @@ -79,6 +80,7 @@ interface ServerInfo { overviewsCommand?: OverviewsCommand searchCommand?: SearchCommand contactFormCommand?: ContactFormCommand + debugCommand?: DebugCommand } function parallelTests () { @@ -293,6 +295,7 @@ async function runServer (server: ServerInfo, configOverrideArg?: any, args = [] server.overviewsCommand = new OverviewsCommand(server) server.searchCommand = new SearchCommand(server) server.contactFormCommand = new ContactFormCommand(server) + server.debugCommand = new DebugCommand(server) res(server) }) diff --git a/shared/models/server/debug.model.ts b/shared/models/server/debug.model.ts index 7ceff9137..2ecabdeca 100644 --- a/shared/models/server/debug.model.ts +++ b/shared/models/server/debug.model.ts @@ -1,5 +1,6 @@ export interface Debug { ip: string + activityPubMessagesWaiting: number } export interface SendDebugCommand { -- cgit v1.2.3 From c3d29f694bf8c910f917be655626d0f80871124f Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Wed, 7 Jul 2021 09:16:40 +0200 Subject: Introduce follows command --- server/tests/api/moderation/blocklist.ts | 10 +- .../api/notifications/moderation-notifications.ts | 16 +-- .../tests/api/redundancy/redundancy-constraints.ts | 5 +- server/tests/api/redundancy/redundancy.ts | 24 ++-- server/tests/api/server/auto-follows.ts | 48 +++---- server/tests/api/server/follow-constraints.ts | 15 +-- server/tests/api/server/follows-moderation.ts | 92 ++++++------- server/tests/api/server/follows.ts | 144 ++++++++++----------- server/tests/api/server/handle-down.ts | 50 ++++--- server/tests/api/server/jobs.ts | 4 +- server/tests/api/server/stats.ts | 22 ++-- server/tests/api/users/user-subscriptions.ts | 33 +++-- server/tests/api/users/users.ts | 8 +- server/tests/api/videos/video-description.ts | 2 +- server/tests/api/videos/video-playlists.ts | 41 +++--- shared/extra-utils/index.ts | 5 +- shared/extra-utils/server/follows-command.ts | 124 ++++++++++++++++++ shared/extra-utils/server/follows.ts | 131 +------------------ shared/extra-utils/server/index.ts | 2 + shared/extra-utils/server/servers.ts | 3 + 20 files changed, 368 insertions(+), 411 deletions(-) create mode 100644 shared/extra-utils/server/follows-command.ts diff --git a/server/tests/api/moderation/blocklist.ts b/server/tests/api/moderation/blocklist.ts index 793abbcb4..9ca6324c2 100644 --- a/server/tests/api/moderation/blocklist.ts +++ b/server/tests/api/moderation/blocklist.ts @@ -15,7 +15,6 @@ import { doubleFollow, findCommentId, flushAndRunMultipleServers, - follow, getAccountBlocklistByAccount, getAccountBlocklistByServer, getServerBlocklistByAccount, @@ -31,7 +30,6 @@ import { removeServerFromServerBlocklist, ServerInfo, setAccessTokensToServers, - unfollow, uploadVideo, userLogin, waitJobs @@ -742,9 +740,9 @@ describe('Test blocklist', function () { { const now = new Date() - await unfollow(servers[1].url, servers[1].accessToken, servers[0]) + await servers[1].followsCommand.unfollow({ target: servers[0] }) await waitJobs(servers) - await follow(servers[1].url, [ servers[0].host ], servers[1].accessToken) + await servers[1].followsCommand.follow({ targets: [ servers[0].host ] }) await waitJobs(servers) @@ -807,9 +805,9 @@ describe('Test blocklist', function () { { const now = new Date() - await unfollow(servers[1].url, servers[1].accessToken, servers[0]) + await servers[1].followsCommand.unfollow({ target: servers[0] }) await waitJobs(servers) - await follow(servers[1].url, [ servers[0].host ], servers[1].accessToken) + await servers[1].followsCommand.follow({ targets: [ servers[0].host ] }) await waitJobs(servers) diff --git a/server/tests/api/notifications/moderation-notifications.ts b/server/tests/api/notifications/moderation-notifications.ts index c4f63200a..9a93ce401 100644 --- a/server/tests/api/notifications/moderation-notifications.ts +++ b/server/tests/api/notifications/moderation-notifications.ts @@ -21,7 +21,6 @@ import { checkVideoIsPublished, cleanupTests, createUser, - follow, generateUserAccessToken, getAccount, getCustomConfig, @@ -35,7 +34,6 @@ import { removeUserSubscription, removeVideoFromBlacklist, ServerInfo, - unfollow, updateCustomConfig, updateCustomSubConfig, uploadVideo, @@ -386,7 +384,7 @@ describe('Test moderation notifications', function () { it('Should send a notification only to admin when there is a new instance follower', async function () { this.timeout(20000) - await follow(servers[2].url, [ servers[0].url ], servers[2].accessToken) + await servers[2].followsCommand.follow({ targets: [ servers[0].url ] }) await waitJobs(servers) @@ -399,7 +397,7 @@ describe('Test moderation notifications', function () { it('Should send a notification on auto follow back', async function () { this.timeout(40000) - await unfollow(servers[2].url, servers[2].accessToken, servers[0]) + await servers[2].followsCommand.unfollow({ target: servers[0] }) await waitJobs(servers) const config = { @@ -411,7 +409,7 @@ describe('Test moderation notifications', function () { } await updateCustomSubConfig(servers[0].url, servers[0].accessToken, config) - await follow(servers[2].url, [ servers[0].url ], servers[2].accessToken) + await servers[2].followsCommand.follow({ targets: [ servers[0].url ] }) await waitJobs(servers) @@ -424,13 +422,13 @@ describe('Test moderation notifications', function () { config.followings.instance.autoFollowBack.enabled = false await updateCustomSubConfig(servers[0].url, servers[0].accessToken, config) - await unfollow(servers[0].url, servers[0].accessToken, servers[2]) - await unfollow(servers[2].url, servers[2].accessToken, servers[0]) + await servers[0].followsCommand.unfollow({ target: servers[2] }) + await servers[2].followsCommand.unfollow({ target: servers[0] }) }) it('Should send a notification on auto instances index follow', async function () { this.timeout(30000) - await unfollow(servers[0].url, servers[0].accessToken, servers[1]) + await servers[0].followsCommand.unfollow({ target: servers[1] }) await updateCustomSubConfig(servers[0].url, servers[0].accessToken, config) @@ -443,7 +441,7 @@ describe('Test moderation notifications', function () { config.followings.instance.autoFollowIndex.enabled = false await updateCustomSubConfig(servers[0].url, servers[0].accessToken, config) - await unfollow(servers[0].url, servers[0].accessToken, servers[1]) + await servers[0].followsCommand.unfollow({ target: servers[1] }) }) }) diff --git a/server/tests/api/redundancy/redundancy-constraints.ts b/server/tests/api/redundancy/redundancy-constraints.ts index 1cb1603bc..602f4bc1b 100644 --- a/server/tests/api/redundancy/redundancy-constraints.ts +++ b/server/tests/api/redundancy/redundancy-constraints.ts @@ -7,7 +7,6 @@ import { VideoPrivacy } from '@shared/models' import { cleanupTests, flushAndRunServer, - follow, killallServers, reRunServer, ServerInfo, @@ -98,7 +97,7 @@ describe('Test redundancy constraints', function () { await waitJobs(servers) // Server 1 and server 2 follow each other - await follow(remoteServer.url, [ localServer.url ], remoteServer.accessToken) + await remoteServer.followsCommand.follow({ targets: [ localServer.url ] }) await waitJobs(servers) await updateRedundancy(remoteServer.url, remoteServer.accessToken, localServer.host, true) @@ -184,7 +183,7 @@ describe('Test redundancy constraints', function () { it('Should have redundancy on server 1 and on server 2 with followings filter now server 2 follows server 1', async function () { this.timeout(120000) - await follow(localServer.url, [ remoteServer.url ], localServer.accessToken) + await localServer.followsCommand.follow({ targets: [ remoteServer.url ] }) await waitJobs(servers) await uploadWrapper('video 4 server 2') diff --git a/server/tests/api/redundancy/redundancy.ts b/server/tests/api/redundancy/redundancy.ts index 0e0a73b9d..dfe8099ed 100644 --- a/server/tests/api/redundancy/redundancy.ts +++ b/server/tests/api/redundancy/redundancy.ts @@ -12,7 +12,6 @@ import { cleanupTests, doubleFollow, flushAndRunMultipleServers, - getFollowingListPaginationAndSort, getVideo, getVideoWithToken, immutableAssign, @@ -23,7 +22,6 @@ import { root, ServerInfo, setAccessTokensToServers, - unfollow, updateVideo, uploadVideo, viewVideo, @@ -38,7 +36,6 @@ import { updateRedundancy } from '../../../../shared/extra-utils/server/redundancy' import { getStats } from '../../../../shared/extra-utils/server/stats' -import { ActorFollow } from '../../../../shared/models/actors' import { VideoRedundancy, VideoRedundancyStrategy, VideoRedundancyStrategyWithManual } from '../../../../shared/models/redundancy' import { ServerStats } from '../../../../shared/models/server/server-stats.model' import { VideoDetails, VideoPrivacy } from '../../../../shared/models/videos' @@ -272,13 +269,19 @@ async function checkStatsWithoutRedundancy (strategy: VideoRedundancyStrategyWit expect(stat.totalVideos).to.equal(0) } +async function findServerFollows () { + const body = await servers[0].followsCommand.getFollowings({ start: 0, count: 5, sort: '-createdAt' }) + const follows = body.data + const server2 = follows.find(f => f.following.host === `localhost:${servers[1].port}`) + const server3 = follows.find(f => f.following.host === `localhost:${servers[2].port}`) + + return { server2, server3 } +} + async function enableRedundancyOnServer1 () { await updateRedundancy(servers[0].url, servers[0].accessToken, servers[1].host, true) - const res = await getFollowingListPaginationAndSort({ url: servers[0].url, start: 0, count: 5, sort: '-createdAt' }) - const follows: ActorFollow[] = res.body.data - const server2 = follows.find(f => f.following.host === `localhost:${servers[1].port}`) - const server3 = follows.find(f => f.following.host === `localhost:${servers[2].port}`) + const { server2, server3 } = await findServerFollows() expect(server3).to.not.be.undefined expect(server3.following.hostRedundancyAllowed).to.be.false @@ -290,10 +293,7 @@ async function enableRedundancyOnServer1 () { async function disableRedundancyOnServer1 () { await updateRedundancy(servers[0].url, servers[0].accessToken, servers[1].host, false) - const res = await getFollowingListPaginationAndSort({ url: servers[0].url, start: 0, count: 5, sort: '-createdAt' }) - const follows: ActorFollow[] = res.body.data - const server2 = follows.find(f => f.following.host === `localhost:${servers[1].port}`) - const server3 = follows.find(f => f.following.host === `localhost:${servers[2].port}`) + const { server2, server3 } = await findServerFollows() expect(server3).to.not.be.undefined expect(server3.following.hostRedundancyAllowed).to.be.false @@ -388,7 +388,7 @@ describe('Test videos redundancy', function () { it('Should unfollow on server 1 and remove duplicated videos', async function () { this.timeout(80000) - await unfollow(servers[0].url, servers[0].accessToken, servers[1]) + await servers[0].followsCommand.unfollow({ target: servers[1] }) await waitJobs(servers) await wait(5000) diff --git a/server/tests/api/server/auto-follows.ts b/server/tests/api/server/auto-follows.ts index 1519b263f..02389b1e9 100644 --- a/server/tests/api/server/auto-follows.ts +++ b/server/tests/api/server/auto-follows.ts @@ -3,64 +3,46 @@ import 'mocha' import * as chai from 'chai' import { - acceptFollower, cleanupTests, flushAndRunMultipleServers, MockInstancesIndex, ServerInfo, setAccessTokensToServers, - unfollow, updateCustomSubConfig, - wait -} from '../../../../shared/extra-utils/index' -import { follow, getFollowersListPaginationAndSort, getFollowingListPaginationAndSort } from '../../../../shared/extra-utils/server/follows' -import { waitJobs } from '../../../../shared/extra-utils/server/jobs' -import { ActorFollow } from '../../../../shared/models/actors' + wait, + waitJobs +} from '@shared/extra-utils' const expect = chai.expect async function checkFollow (follower: ServerInfo, following: ServerInfo, exists: boolean) { { - const res = await getFollowersListPaginationAndSort({ url: following.url, start: 0, count: 5, sort: '-createdAt' }) - const follows = res.body.data as ActorFollow[] + const body = await following.followsCommand.getFollowers({ start: 0, count: 5, sort: '-createdAt' }) + const follow = body.data.find(f => f.follower.host === follower.host && f.state === 'accepted') - const follow = follows.find(f => { - return f.follower.host === follower.host && f.state === 'accepted' - }) - - if (exists === true) { - expect(follow).to.exist - } else { - expect(follow).to.be.undefined - } + if (exists === true) expect(follow).to.exist + else expect(follow).to.be.undefined } { - const res = await getFollowingListPaginationAndSort({ url: follower.url, start: 0, count: 5, sort: '-createdAt' }) - const follows = res.body.data as ActorFollow[] - - const follow = follows.find(f => { - return f.following.host === following.host && f.state === 'accepted' - }) + const body = await follower.followsCommand.getFollowings({ start: 0, count: 5, sort: '-createdAt' }) + const follow = body.data.find(f => f.following.host === following.host && f.state === 'accepted') - if (exists === true) { - expect(follow).to.exist - } else { - expect(follow).to.be.undefined - } + if (exists === true) expect(follow).to.exist + else expect(follow).to.be.undefined } } async function server1Follows2 (servers: ServerInfo[]) { - await follow(servers[0].url, [ servers[1].host ], servers[0].accessToken) + await servers[0].followsCommand.follow({ targets: [ servers[1].host ] }) await waitJobs(servers) } async function resetFollows (servers: ServerInfo[]) { try { - await unfollow(servers[0].url, servers[0].accessToken, servers[1]) - await unfollow(servers[1].url, servers[1].accessToken, servers[0]) + await servers[0].followsCommand.unfollow({ target: servers[1] }) + await servers[1].followsCommand.unfollow({ target: servers[0] }) } catch { /* empty */ } @@ -137,7 +119,7 @@ describe('Test auto follows', function () { await checkFollow(servers[0], servers[1], false) await checkFollow(servers[1], servers[0], false) - await acceptFollower(servers[1].url, servers[1].accessToken, 'peertube@' + servers[0].host) + await servers[1].followsCommand.acceptFollower({ follower: 'peertube@' + servers[0].host }) await waitJobs(servers) await checkFollow(servers[0], servers[1], true) diff --git a/server/tests/api/server/follow-constraints.ts b/server/tests/api/server/follow-constraints.ts index 3f2f71f46..0f1c6264d 100644 --- a/server/tests/api/server/follow-constraints.ts +++ b/server/tests/api/server/follow-constraints.ts @@ -1,9 +1,12 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ -import * as chai from 'chai' import 'mocha' +import * as chai from 'chai' +import { HttpStatusCode } from '@shared/core-utils' +import { PeerTubeProblemDocument, ServerErrorCode } from '@shared/models' import { cleanupTests, + createUser, doubleFollow, flushAndRunMultipleServers, getAccountVideos, @@ -12,13 +15,9 @@ import { getVideoWithToken, ServerInfo, setAccessTokensToServers, - uploadVideo + uploadVideo, + userLogin } from '../../../../shared/extra-utils' -import { unfollow } from '../../../../shared/extra-utils/server/follows' -import { userLogin } from '../../../../shared/extra-utils/users/login' -import { createUser } from '../../../../shared/extra-utils/users/users' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' -import { PeerTubeProblemDocument, ServerErrorCode } from '@shared/models' const expect = chai.expect @@ -144,7 +143,7 @@ describe('Test follow constraints', function () { before(async function () { this.timeout(30000) - await unfollow(servers[0].url, servers[0].accessToken, servers[1]) + await servers[0].followsCommand.unfollow({ target: servers[1] }) }) describe('With an unlogged user', function () { diff --git a/server/tests/api/server/follows-moderation.ts b/server/tests/api/server/follows-moderation.ts index 73c212a32..4853b647d 100644 --- a/server/tests/api/server/follows-moderation.ts +++ b/server/tests/api/server/follows-moderation.ts @@ -1,43 +1,30 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ -import * as chai from 'chai' import 'mocha' +import * as chai from 'chai' import { - acceptFollower, cleanupTests, flushAndRunMultipleServers, + FollowsCommand, ServerInfo, setAccessTokensToServers, - updateCustomSubConfig -} from '../../../../shared/extra-utils/index' -import { - follow, - getFollowersListPaginationAndSort, - getFollowingListPaginationAndSort, - rejectFollower, - removeFollower -} from '../../../../shared/extra-utils/server/follows' -import { waitJobs } from '../../../../shared/extra-utils/server/jobs' -import { ActorFollow } from '../../../../shared/models/actors' + updateCustomSubConfig, + waitJobs +} from '@shared/extra-utils' const expect = chai.expect async function checkServer1And2HasFollowers (servers: ServerInfo[], state = 'accepted') { - { - const res = await getFollowingListPaginationAndSort({ url: servers[0].url, start: 0, count: 5, sort: 'createdAt' }) - expect(res.body.total).to.equal(1) + const fns = [ + servers[0].followsCommand.getFollowings.bind(servers[0].followsCommand), + servers[1].followsCommand.getFollowers.bind(servers[1].followsCommand) + ] - const follow = res.body.data[0] as ActorFollow - expect(follow.state).to.equal(state) - expect(follow.follower.url).to.equal('http://localhost:' + servers[0].port + '/accounts/peertube') - expect(follow.following.url).to.equal('http://localhost:' + servers[1].port + '/accounts/peertube') - } - - { - const res = await getFollowersListPaginationAndSort({ url: servers[1].url, start: 0, count: 5, sort: 'createdAt' }) - expect(res.body.total).to.equal(1) + for (const fn of fns) { + const body = await fn({ start: 0, count: 5, sort: 'createdAt' }) + expect(body.total).to.equal(1) - const follow = res.body.data[0] as ActorFollow + const follow = body.data[0] expect(follow.state).to.equal(state) expect(follow.follower.url).to.equal('http://localhost:' + servers[0].port + '/accounts/peertube') expect(follow.following.url).to.equal('http://localhost:' + servers[1].port + '/accounts/peertube') @@ -45,19 +32,20 @@ async function checkServer1And2HasFollowers (servers: ServerInfo[], state = 'acc } async function checkNoFollowers (servers: ServerInfo[]) { - { - const res = await getFollowingListPaginationAndSort({ url: servers[0].url, start: 0, count: 5, sort: 'createdAt' }) - expect(res.body.total).to.equal(0) - } - - { - const res = await getFollowersListPaginationAndSort({ url: servers[1].url, start: 0, count: 5, sort: 'createdAt' }) - expect(res.body.total).to.equal(0) + const fns = [ + servers[0].followsCommand.getFollowings.bind(servers[0].followsCommand), + servers[1].followsCommand.getFollowers.bind(servers[1].followsCommand) + ] + + for (const fn of fns) { + const body = await fn({ start: 0, count: 5, sort: 'createdAt' }) + expect(body.total).to.equal(0) } } describe('Test follows moderation', function () { let servers: ServerInfo[] = [] + let commands: FollowsCommand[] before(async function () { this.timeout(30000) @@ -66,12 +54,14 @@ describe('Test follows moderation', function () { // Get the access tokens await setAccessTokensToServers(servers) + + commands = servers.map(s => s.followsCommand) }) it('Should have server 1 following server 2', async function () { this.timeout(30000) - await follow(servers[0].url, [ servers[1].url ], servers[0].accessToken) + await commands[0].follow({ targets: [ servers[1].url ] }) await waitJobs(servers) }) @@ -83,7 +73,7 @@ describe('Test follows moderation', function () { it('Should remove follower on server 2', async function () { this.timeout(10000) - await removeFollower(servers[1].url, servers[1].accessToken, servers[0]) + await commands[1].removeFollower({ follower: servers[0] }) await waitJobs(servers) }) @@ -106,7 +96,7 @@ describe('Test follows moderation', function () { await updateCustomSubConfig(servers[1].url, servers[1].accessToken, subConfig) - await follow(servers[0].url, [ servers[1].url ], servers[0].accessToken) + await commands[0].follow({ targets: [ servers[1].url ] }) await waitJobs(servers) await checkNoFollowers(servers) @@ -126,7 +116,7 @@ describe('Test follows moderation', function () { await updateCustomSubConfig(servers[1].url, servers[1].accessToken, subConfig) - await follow(servers[0].url, [ servers[1].url ], servers[0].accessToken) + await commands[0].follow({ targets: [ servers[1].url ] }) await waitJobs(servers) await checkServer1And2HasFollowers(servers) @@ -135,7 +125,7 @@ describe('Test follows moderation', function () { it('Should manually approve followers', async function () { this.timeout(20000) - await removeFollower(servers[1].url, servers[1].accessToken, servers[0]) + await commands[1].removeFollower({ follower: servers[0] }) await waitJobs(servers) const subConfig = { @@ -150,7 +140,7 @@ describe('Test follows moderation', function () { await updateCustomSubConfig(servers[1].url, servers[1].accessToken, subConfig) await updateCustomSubConfig(servers[2].url, servers[2].accessToken, subConfig) - await follow(servers[0].url, [ servers[1].url ], servers[0].accessToken) + await commands[0].follow({ targets: [ servers[1].url ] }) await waitJobs(servers) await checkServer1And2HasFollowers(servers, 'pending') @@ -159,7 +149,7 @@ describe('Test follows moderation', function () { it('Should accept a follower', async function () { this.timeout(10000) - await acceptFollower(servers[1].url, servers[1].accessToken, 'peertube@localhost:' + servers[0].port) + await commands[1].acceptFollower({ follower: 'peertube@localhost:' + servers[0].port }) await waitJobs(servers) await checkServer1And2HasFollowers(servers) @@ -168,32 +158,32 @@ describe('Test follows moderation', function () { it('Should reject another follower', async function () { this.timeout(20000) - await follow(servers[0].url, [ servers[2].url ], servers[0].accessToken) + await commands[0].follow({ targets: [ servers[2].url ] }) await waitJobs(servers) { - const res = await getFollowingListPaginationAndSort({ url: servers[0].url, start: 0, count: 5, sort: 'createdAt' }) - expect(res.body.total).to.equal(2) + const body = await commands[0].getFollowings({ start: 0, count: 5, sort: 'createdAt' }) + expect(body.total).to.equal(2) } { - const res = await getFollowersListPaginationAndSort({ url: servers[1].url, start: 0, count: 5, sort: 'createdAt' }) - expect(res.body.total).to.equal(1) + const body = await commands[1].getFollowers({ start: 0, count: 5, sort: 'createdAt' }) + expect(body.total).to.equal(1) } { - const res = await getFollowersListPaginationAndSort({ url: servers[2].url, start: 0, count: 5, sort: 'createdAt' }) - expect(res.body.total).to.equal(1) + const body = await commands[2].getFollowers({ start: 0, count: 5, sort: 'createdAt' }) + expect(body.total).to.equal(1) } - await rejectFollower(servers[2].url, servers[2].accessToken, 'peertube@localhost:' + servers[0].port) + await commands[2].rejectFollower({ follower: 'peertube@localhost:' + servers[0].port }) await waitJobs(servers) await checkServer1And2HasFollowers(servers) { - const res = await getFollowersListPaginationAndSort({ url: servers[2].url, start: 0, count: 5, sort: 'createdAt' }) - expect(res.body.total).to.equal(0) + const body = await commands[2].getFollowers({ start: 0, count: 5, sort: 'createdAt' }) + expect(body.total).to.equal(0) } }) diff --git a/server/tests/api/server/follows.ts b/server/tests/api/server/follows.ts index 9e5aa00c7..c8fcca02c 100644 --- a/server/tests/api/server/follows.ts +++ b/server/tests/api/server/follows.ts @@ -13,9 +13,7 @@ import { deleteVideoComment, expectAccountFollows, flushAndRunMultipleServers, - follow, - getFollowersListPaginationAndSort, - getFollowingListPaginationAndSort, + FollowsCommand, getVideoCommentThreads, getVideosList, getVideoThreadComments, @@ -24,7 +22,6 @@ import { ServerInfo, setAccessTokensToServers, testCaptionFile, - unfollow, uploadVideo, userLogin, waitJobs @@ -35,11 +32,13 @@ const expect = chai.expect describe('Test follows', function () { let servers: ServerInfo[] = [] + let followsCommands: FollowsCommand[] before(async function () { this.timeout(30000) servers = await flushAndRunMultipleServers(3) + followsCommands = servers.map(s => s.followsCommand) // Get the access tokens await setAccessTokensToServers(servers) @@ -47,10 +46,10 @@ describe('Test follows', function () { it('Should not have followers', async function () { for (const server of servers) { - const res = await getFollowersListPaginationAndSort({ url: server.url, start: 0, count: 5, sort: 'createdAt' }) - const follows = res.body.data + const body = await server.followsCommand.getFollowers({ start: 0, count: 5, sort: 'createdAt' }) + expect(body.total).to.equal(0) - expect(res.body.total).to.equal(0) + const follows = body.data expect(follows).to.be.an('array') expect(follows.length).to.equal(0) } @@ -58,10 +57,10 @@ describe('Test follows', function () { it('Should not have following', async function () { for (const server of servers) { - const res = await getFollowingListPaginationAndSort({ url: server.url, start: 0, count: 5, sort: 'createdAt' }) - const follows = res.body.data + const body = await server.followsCommand.getFollowings({ start: 0, count: 5, sort: 'createdAt' }) + expect(body.total).to.equal(0) - expect(res.body.total).to.equal(0) + const follows = body.data expect(follows).to.be.an('array') expect(follows.length).to.equal(0) } @@ -70,21 +69,21 @@ describe('Test follows', function () { it('Should have server 1 following server 2 and 3', async function () { this.timeout(30000) - await follow(servers[0].url, [ servers[1].url, servers[2].url ], servers[0].accessToken) + await followsCommands[0].follow({ targets: [ servers[1].url, servers[2].url ] }) await waitJobs(servers) }) it('Should have 2 followings on server 1', async function () { - let res = await getFollowingListPaginationAndSort({ url: servers[0].url, start: 0, count: 1, sort: 'createdAt' }) - let follows = res.body.data + const body = await followsCommands[0].getFollowings({ start: 0, count: 1, sort: 'createdAt' }) + expect(body.total).to.equal(2) - expect(res.body.total).to.equal(2) + let follows = body.data expect(follows).to.be.an('array') expect(follows.length).to.equal(1) - res = await getFollowingListPaginationAndSort({ url: servers[0].url, start: 1, count: 1, sort: 'createdAt' }) - follows = follows.concat(res.body.data) + const body2 = await followsCommands[0].getFollowings({ start: 1, count: 1, sort: 'createdAt' }) + follows = follows.concat(body2.data) const server2Follow = follows.find(f => f.following.host === 'localhost:' + servers[1].port) const server3Follow = follows.find(f => f.following.host === 'localhost:' + servers[2].port) @@ -99,35 +98,33 @@ describe('Test follows', function () { const sort = 'createdAt' const start = 0 const count = 1 - const url = servers[0].url { const search = ':' + servers[1].port { - const res = await getFollowingListPaginationAndSort({ url, start, count, sort, search }) - const follows = res.body.data + const body = await followsCommands[0].getFollowings({ start, count, sort, search }) + expect(body.total).to.equal(1) - expect(res.body.total).to.equal(1) + const follows = body.data expect(follows.length).to.equal(1) expect(follows[0].following.host).to.equal('localhost:' + servers[1].port) } { - const res = await getFollowingListPaginationAndSort({ url, start, count, sort, search, state: 'accepted' }) - expect(res.body.total).to.equal(1) - expect(res.body.data).to.have.lengthOf(1) + const body = await followsCommands[0].getFollowings({ start, count, sort, search, state: 'accepted' }) + expect(body.total).to.equal(1) + expect(body.data).to.have.lengthOf(1) } { - const res = await getFollowingListPaginationAndSort({ url, start, count, sort, search, state: 'accepted', actorType: 'Person' }) - expect(res.body.total).to.equal(0) - expect(res.body.data).to.have.lengthOf(0) + const body = await followsCommands[0].getFollowings({ start, count, sort, search, state: 'accepted', actorType: 'Person' }) + expect(body.total).to.equal(0) + expect(body.data).to.have.lengthOf(0) } { - const res = await getFollowingListPaginationAndSort({ - url, + const body = await followsCommands[0].getFollowings({ start, count, sort, @@ -135,32 +132,31 @@ describe('Test follows', function () { state: 'accepted', actorType: 'Application' }) - expect(res.body.total).to.equal(1) - expect(res.body.data).to.have.lengthOf(1) + expect(body.total).to.equal(1) + expect(body.data).to.have.lengthOf(1) } { - const res = await getFollowingListPaginationAndSort({ url, start, count, sort, search, state: 'pending' }) - expect(res.body.total).to.equal(0) - expect(res.body.data).to.have.lengthOf(0) + const body = await followsCommands[0].getFollowings({ start, count, sort, search, state: 'pending' }) + expect(body.total).to.equal(0) + expect(body.data).to.have.lengthOf(0) } } { - const res = await getFollowingListPaginationAndSort({ url, start, count, sort, search: 'bla' }) - const follows = res.body.data + const body = await followsCommands[0].getFollowings({ start, count, sort, search: 'bla' }) + expect(body.total).to.equal(0) - expect(res.body.total).to.equal(0) - expect(follows.length).to.equal(0) + expect(body.data.length).to.equal(0) } }) it('Should have 0 followings on server 2 and 3', async function () { for (const server of [ servers[1], servers[2] ]) { - const res = await getFollowingListPaginationAndSort({ url: server.url, start: 0, count: 5, sort: 'createdAt' }) - const follows = res.body.data + const body = await server.followsCommand.getFollowings({ start: 0, count: 5, sort: 'createdAt' }) + expect(body.total).to.equal(0) - expect(res.body.total).to.equal(0) + const follows = body.data expect(follows).to.be.an('array') expect(follows.length).to.equal(0) } @@ -168,10 +164,10 @@ describe('Test follows', function () { it('Should have 1 followers on server 2 and 3', async function () { for (const server of [ servers[1], servers[2] ]) { - const res = await getFollowersListPaginationAndSort({ url: server.url, start: 0, count: 1, sort: 'createdAt' }) + const body = await server.followsCommand.getFollowers({ start: 0, count: 1, sort: 'createdAt' }) + expect(body.total).to.equal(1) - const follows = res.body.data - expect(res.body.total).to.equal(1) + const follows = body.data expect(follows).to.be.an('array') expect(follows.length).to.equal(1) expect(follows[0].follower.host).to.equal('localhost:' + servers[0].port) @@ -179,7 +175,6 @@ describe('Test follows', function () { }) it('Should search/filter followers on server 2', async function () { - const url = servers[2].url const start = 0 const count = 5 const sort = 'createdAt' @@ -188,29 +183,28 @@ describe('Test follows', function () { const search = servers[0].port + '' { - const res = await getFollowersListPaginationAndSort({ url, start, count, sort, search }) - const follows = res.body.data + const body = await followsCommands[2].getFollowers({ start, count, sort, search }) + expect(body.total).to.equal(1) - expect(res.body.total).to.equal(1) + const follows = body.data expect(follows.length).to.equal(1) expect(follows[0].following.host).to.equal('localhost:' + servers[2].port) } { - const res = await getFollowersListPaginationAndSort({ url, start, count, sort, search, state: 'accepted' }) - expect(res.body.total).to.equal(1) - expect(res.body.data).to.have.lengthOf(1) + const body = await followsCommands[2].getFollowers({ start, count, sort, search, state: 'accepted' }) + expect(body.total).to.equal(1) + expect(body.data).to.have.lengthOf(1) } { - const res = await getFollowersListPaginationAndSort({ url, start, count, sort, search, state: 'accepted', actorType: 'Person' }) - expect(res.body.total).to.equal(0) - expect(res.body.data).to.have.lengthOf(0) + const body = await followsCommands[2].getFollowers({ start, count, sort, search, state: 'accepted', actorType: 'Person' }) + expect(body.total).to.equal(0) + expect(body.data).to.have.lengthOf(0) } { - const res = await getFollowersListPaginationAndSort({ - url, + const body = await followsCommands[2].getFollowers({ start, count, sort, @@ -218,31 +212,31 @@ describe('Test follows', function () { state: 'accepted', actorType: 'Application' }) - expect(res.body.total).to.equal(1) - expect(res.body.data).to.have.lengthOf(1) + expect(body.total).to.equal(1) + expect(body.data).to.have.lengthOf(1) } { - const res = await getFollowersListPaginationAndSort({ url, start, count, sort, search, state: 'pending' }) - expect(res.body.total).to.equal(0) - expect(res.body.data).to.have.lengthOf(0) + const body = await followsCommands[2].getFollowers({ start, count, sort, search, state: 'pending' }) + expect(body.total).to.equal(0) + expect(body.data).to.have.lengthOf(0) } } { - const res = await getFollowersListPaginationAndSort({ url, start, count, sort, search: 'bla' }) - const follows = res.body.data + const body = await followsCommands[2].getFollowers({ start, count, sort, search: 'bla' }) + expect(body.total).to.equal(0) - expect(res.body.total).to.equal(0) + const follows = body.data expect(follows.length).to.equal(0) } }) it('Should have 0 followers on server 1', async function () { - const res = await getFollowersListPaginationAndSort({ url: servers[0].url, start: 0, count: 5, sort: 'createdAt' }) - const follows = res.body.data + const body = await followsCommands[0].getFollowers({ start: 0, count: 5, sort: 'createdAt' }) + expect(body.total).to.equal(0) - expect(res.body.total).to.equal(0) + const follows = body.data expect(follows).to.be.an('array') expect(follows.length).to.equal(0) }) @@ -263,16 +257,16 @@ describe('Test follows', function () { it('Should unfollow server 3 on server 1', async function () { this.timeout(5000) - await unfollow(servers[0].url, servers[0].accessToken, servers[2]) + await followsCommands[0].unfollow({ target: servers[2] }) await waitJobs(servers) }) it('Should not follow server 3 on server 1 anymore', async function () { - const res = await getFollowingListPaginationAndSort({ url: servers[0].url, start: 0, count: 2, sort: 'createdAt' }) - const follows = res.body.data + const body = await followsCommands[0].getFollowings({ start: 0, count: 2, sort: 'createdAt' }) + expect(body.total).to.equal(1) - expect(res.body.total).to.equal(1) + const follows = body.data expect(follows).to.be.an('array') expect(follows.length).to.equal(1) @@ -280,10 +274,10 @@ describe('Test follows', function () { }) it('Should not have server 1 as follower on server 3 anymore', async function () { - const res = await getFollowersListPaginationAndSort({ url: servers[2].url, start: 0, count: 1, sort: 'createdAt' }) + const body = await followsCommands[2].getFollowers({ start: 0, count: 1, sort: 'createdAt' }) + expect(body.total).to.equal(0) - const follows = res.body.data - expect(res.body.total).to.equal(0) + const follows = body.data expect(follows).to.be.an('array') expect(follows.length).to.equal(0) }) @@ -404,7 +398,7 @@ describe('Test follows', function () { await waitJobs(servers) // Server 1 follows server 3 - await follow(servers[0].url, [ servers[2].url ], servers[0].accessToken) + await followsCommands[0].follow({ targets: [ servers[2].url ] }) await waitJobs(servers) }) @@ -563,7 +557,7 @@ describe('Test follows', function () { it('Should unfollow server 3 on server 1 and does not list server 3 videos', async function () { this.timeout(5000) - await unfollow(servers[0].url, servers[0].accessToken, servers[2]) + await followsCommands[0].unfollow({ target: servers[2] }) await waitJobs(servers) diff --git a/server/tests/api/server/handle-down.ts b/server/tests/api/server/handle-down.ts index d57d72f5e..eff4451e5 100644 --- a/server/tests/api/server/handle-down.ts +++ b/server/tests/api/server/handle-down.ts @@ -1,39 +1,33 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ -import * as chai from 'chai' import 'mocha' -import { JobState, Video } from '../../../../shared/models' -import { VideoPrivacy } from '../../../../shared/models/videos' -import { VideoCommentThreadTree } from '../../../../shared/models/videos/comment/video-comment.model' - +import * as chai from 'chai' +import { HttpStatusCode } from '@shared/core-utils' import { + addVideoCommentReply, + addVideoCommentThread, cleanupTests, closeAllSequelize, completeVideoCheck, flushAndRunMultipleServers, + getJobsListPaginationAndSort, getVideo, + getVideoCommentThreads, getVideosList, + getVideoThreadComments, immutableAssign, killallServers, reRunServer, ServerInfo, setAccessTokensToServers, setActorFollowScores, - unfollow, updateVideo, uploadVideo, uploadVideoAndGetId, - wait -} from '../../../../shared/extra-utils' -import { follow, getFollowersListPaginationAndSort } from '../../../../shared/extra-utils/server/follows' -import { getJobsListPaginationAndSort, waitJobs } from '../../../../shared/extra-utils/server/jobs' -import { - addVideoCommentReply, - addVideoCommentThread, - getVideoCommentThreads, - getVideoThreadComments -} from '../../../../shared/extra-utils/videos/video-comments' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' + wait, + waitJobs +} from '@shared/extra-utils' +import { JobState, Video, VideoCommentThreadTree, VideoPrivacy } from '@shared/models' const expect = chai.expect @@ -118,8 +112,8 @@ describe('Test handle downs', function () { this.timeout(240000) // Server 2 and 3 follow server 1 - await follow(servers[1].url, [ servers[0].url ], servers[1].accessToken) - await follow(servers[2].url, [ servers[0].url ], servers[2].accessToken) + await servers[1].followsCommand.follow({ targets: [ servers[0].url ] }) + await servers[2].followsCommand.follow({ targets: [ servers[0].url ] }) await waitJobs(servers) @@ -177,10 +171,10 @@ describe('Test handle downs', function () { await wait(11000) // Only server 3 is still a follower of server 1 - const res = await getFollowersListPaginationAndSort({ url: servers[0].url, start: 0, count: 2, sort: 'createdAt' }) - expect(res.body.data).to.be.an('array') - expect(res.body.data).to.have.lengthOf(1) - expect(res.body.data[0].follower.host).to.equal('localhost:' + servers[2].port) + const body = await servers[0].followsCommand.getFollowers({ start: 0, count: 2, sort: 'createdAt' }) + expect(body.data).to.be.an('array') + expect(body.data).to.have.lengthOf(1) + expect(body.data[0].follower.host).to.equal('localhost:' + servers[2].port) }) it('Should not have pending/processing jobs anymore', async function () { @@ -205,16 +199,16 @@ describe('Test handle downs', function () { await reRunServer(servers[1]) await reRunServer(servers[2]) - await unfollow(servers[1].url, servers[1].accessToken, servers[0]) + await servers[1].followsCommand.unfollow({ target: servers[0] }) await waitJobs(servers) - await follow(servers[1].url, [ servers[0].url ], servers[1].accessToken) + await servers[1].followsCommand.follow({ targets: [ servers[0].url ] }) await waitJobs(servers) - const res = await getFollowersListPaginationAndSort({ url: servers[0].url, start: 0, count: 2, sort: 'createdAt' }) - expect(res.body.data).to.be.an('array') - expect(res.body.data).to.have.lengthOf(2) + const body = await servers[0].followsCommand.getFollowers({ start: 0, count: 2, sort: 'createdAt' }) + expect(body.data).to.be.an('array') + expect(body.data).to.have.lengthOf(2) }) it('Should send an update to server 3, and automatically fetch the video', async function () { diff --git a/server/tests/api/server/jobs.ts b/server/tests/api/server/jobs.ts index d0e222997..6576dd7af 100644 --- a/server/tests/api/server/jobs.ts +++ b/server/tests/api/server/jobs.ts @@ -1,13 +1,13 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ -import * as chai from 'chai' import 'mocha' +import * as chai from 'chai' import { cleanupTests, ServerInfo, setAccessTokensToServers } from '../../../../shared/extra-utils/index' +import { dateIsValid } from '../../../../shared/extra-utils/miscs/miscs' import { doubleFollow } from '../../../../shared/extra-utils/server/follows' import { getJobsList, getJobsListPaginationAndSort, waitJobs } from '../../../../shared/extra-utils/server/jobs' import { flushAndRunMultipleServers } from '../../../../shared/extra-utils/server/servers' import { uploadVideo } from '../../../../shared/extra-utils/videos/videos' -import { dateIsValid } from '../../../../shared/extra-utils/miscs/miscs' import { Job } from '../../../../shared/models/server' const expect = chai.expect diff --git a/server/tests/api/server/stats.ts b/server/tests/api/server/stats.ts index 304181a6d..f609ea725 100644 --- a/server/tests/api/server/stats.ts +++ b/server/tests/api/server/stats.ts @@ -4,27 +4,23 @@ import 'mocha' import * as chai from 'chai' import { addVideoChannel, + addVideoCommentThread, cleanupTests, createUser, createVideoPlaylist, doubleFollow, flushAndRunMultipleServers, - follow, ServerInfo, - unfollow, + setAccessTokensToServers, updateCustomSubConfig, uploadVideo, userLogin, viewVideo, - wait -} from '../../../../shared/extra-utils' -import { setAccessTokensToServers } from '../../../../shared/extra-utils/index' -import { waitJobs } from '../../../../shared/extra-utils/server/jobs' -import { getStats } from '../../../../shared/extra-utils/server/stats' -import { addVideoCommentThread } from '../../../../shared/extra-utils/videos/video-comments' -import { ServerStats } from '../../../../shared/models/server/server-stats.model' -import { VideoPlaylistPrivacy } from '../../../../shared/models/videos/playlist/video-playlist-privacy.model' -import { ActivityType } from '@shared/models' + wait, + waitJobs +} from '@shared/extra-utils' +import { getStats } from '@shared/extra-utils/server/stats' +import { ActivityType, ServerStats, VideoPlaylistPrivacy } from '@shared/models' const expect = chai.expect @@ -57,7 +53,7 @@ describe('Test stats (excluding redundancy)', function () { // Wait the video views repeatable job await wait(8000) - await follow(servers[2].url, [ servers[0].url ], servers[2].accessToken) + await servers[2].followsCommand.follow({ targets: [ servers[0].url ] }) await waitJobs(servers) }) @@ -111,7 +107,7 @@ describe('Test stats (excluding redundancy)', function () { it('Should have the correct total videos stats after an unfollow', async function () { this.timeout(15000) - await unfollow(servers[2].url, servers[2].accessToken, servers[0]) + await servers[2].followsCommand.unfollow({ target: servers[0] }) await waitJobs(servers) const res = await getStats(servers[2].url) diff --git a/server/tests/api/users/user-subscriptions.ts b/server/tests/api/users/user-subscriptions.ts index 60676a37b..7e365d797 100644 --- a/server/tests/api/users/user-subscriptions.ts +++ b/server/tests/api/users/user-subscriptions.ts @@ -1,30 +1,27 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ -import * as chai from 'chai' import 'mocha' +import * as chai from 'chai' import { + addUserSubscription, + areSubscriptionsExist, cleanupTests, createUser, doubleFollow, flushAndRunMultipleServers, - follow, - getVideosList, - unfollow, - updateVideo, - userLogin -} from '../../../../shared/extra-utils' -import { ServerInfo, uploadVideo } from '../../../../shared/extra-utils/index' -import { setAccessTokensToServers } from '../../../../shared/extra-utils/users/login' -import { Video, VideoChannel } from '../../../../shared/models/videos' -import { waitJobs } from '../../../../shared/extra-utils/server/jobs' -import { - addUserSubscription, - areSubscriptionsExist, getUserSubscription, + getVideosList, listUserSubscriptions, listUserSubscriptionVideos, - removeUserSubscription -} from '../../../../shared/extra-utils/users/user-subscriptions' + removeUserSubscription, + ServerInfo, + setAccessTokensToServers, + updateVideo, + uploadVideo, + userLogin, + waitJobs +} from '@shared/extra-utils' +import { Video, VideoChannel } from '@shared/models' const expect = chai.expect @@ -250,7 +247,7 @@ describe('Test users subscriptions', function () { it('Should have server 1 follow server 3 and display server 3 videos', async function () { this.timeout(60000) - await follow(servers[0].url, [ servers[2].url ], servers[0].accessToken) + await servers[0].followsCommand.follow({ targets: [ servers[2].url ] }) await waitJobs(servers) @@ -268,7 +265,7 @@ describe('Test users subscriptions', function () { it('Should remove follow server 1 -> server 3 and hide server 3 videos', async function () { this.timeout(60000) - await unfollow(servers[0].url, servers[0].accessToken, servers[2]) + await servers[0].followsCommand.unfollow({ target: servers[2] }) await waitJobs(servers) diff --git a/server/tests/api/users/users.ts b/server/tests/api/users/users.ts index 6bfc7cfe5..92927ea97 100644 --- a/server/tests/api/users/users.ts +++ b/server/tests/api/users/users.ts @@ -11,7 +11,6 @@ import { createUser, deleteMe, flushAndRunServer, - follow, getAccountRatings, getBlacklistedVideosList, getCustomConfig, @@ -138,7 +137,12 @@ describe('Test users', function () { it('Should not be able to follow', async function () { accessToken = 'my_super_token' - await follow(server.url, [ 'http://example.com' ], accessToken, HttpStatusCode.UNAUTHORIZED_401) + + await server.followsCommand.follow({ + targets: [ 'http://example.com' ], + token: accessToken, + expectedStatus: HttpStatusCode.UNAUTHORIZED_401 + }) }) it('Should not be able to unfollow') diff --git a/server/tests/api/videos/video-description.ts b/server/tests/api/videos/video-description.ts index b8e98e45f..e1c9afe79 100644 --- a/server/tests/api/videos/video-description.ts +++ b/server/tests/api/videos/video-description.ts @@ -1,7 +1,7 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ -import * as chai from 'chai' import 'mocha' +import * as chai from 'chai' import { cleanupTests, flushAndRunMultipleServers, diff --git a/server/tests/api/videos/video-playlists.ts b/server/tests/api/videos/video-playlists.ts index da8de054b..28f68dcfe 100644 --- a/server/tests/api/videos/video-playlists.ts +++ b/server/tests/api/videos/video-playlists.ts @@ -2,8 +2,12 @@ import 'mocha' import * as chai from 'chai' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '@shared/core-utils' import { + addAccountToAccountBlocklist, + addAccountToServerBlocklist, + addServerToAccountBlocklist, + addServerToServerBlocklist, addVideoChannel, addVideoInPlaylist, addVideoToBlacklist, @@ -27,6 +31,10 @@ import { getVideoPlaylistPrivacies, getVideoPlaylistsList, getVideoPlaylistWithToken, + removeAccountFromAccountBlocklist, + removeAccountFromServerBlocklist, + removeServerFromAccountBlocklist, + removeServerFromServerBlocklist, removeUser, removeVideoFromBlacklist, removeVideoFromPlaylist, @@ -35,7 +43,6 @@ import { setAccessTokensToServers, setDefaultVideoChannel, testImage, - unfollow, updateVideo, updateVideoPlaylist, updateVideoPlaylistElement, @@ -44,24 +51,18 @@ import { userLogin, wait, waitJobs -} from '../../../../shared/extra-utils' +} from '@shared/extra-utils' import { - addAccountToAccountBlocklist, - addAccountToServerBlocklist, - addServerToAccountBlocklist, - addServerToServerBlocklist, - removeAccountFromAccountBlocklist, - removeAccountFromServerBlocklist, - removeServerFromAccountBlocklist, - removeServerFromServerBlocklist -} from '../../../../shared/extra-utils/users/blocklist' -import { User } from '../../../../shared/models/users' -import { VideoPlaylistCreateResult, VideoPrivacy } from '../../../../shared/models/videos' -import { VideoExistInPlaylist } from '../../../../shared/models/videos/playlist/video-exist-in-playlist.model' -import { VideoPlaylistElement, VideoPlaylistElementType } from '../../../../shared/models/videos/playlist/video-playlist-element.model' -import { VideoPlaylistPrivacy } from '../../../../shared/models/videos/playlist/video-playlist-privacy.model' -import { VideoPlaylistType } from '../../../../shared/models/videos/playlist/video-playlist-type.model' -import { VideoPlaylist } from '../../../../shared/models/videos/playlist/video-playlist.model' + User, + VideoExistInPlaylist, + VideoPlaylist, + VideoPlaylistCreateResult, + VideoPlaylistElement, + VideoPlaylistElementType, + VideoPlaylistPrivacy, + VideoPlaylistType, + VideoPrivacy +} from '@shared/models' const expect = chai.expect @@ -1171,7 +1172,7 @@ describe('Test video playlists', function () { expect(finder(res.body.data)).to.not.be.undefined } - await unfollow(servers[2].url, servers[2].accessToken, servers[0]) + await servers[2].followsCommand.unfollow({ target: servers[0] }) { const res = await getVideoPlaylistsList(servers[2].url, 0, 5) diff --git a/shared/extra-utils/index.ts b/shared/extra-utils/index.ts index 7b5835e47..48431ed83 100644 --- a/shared/extra-utils/index.ts +++ b/shared/extra-utils/index.ts @@ -7,15 +7,14 @@ export * from './miscs' export * from './mock-servers' export * from './moderation' export * from './overviews' +export * from './search' +export * from './server' export * from './requests/check-api-params' export * from './requests/requests' -export * from './search' - export * from './server/clients' export * from './server/config' -export * from './server/follows' export * from './server/jobs' export * from './server/plugins' export * from './server/servers' diff --git a/shared/extra-utils/server/follows-command.ts b/shared/extra-utils/server/follows-command.ts new file mode 100644 index 000000000..aba7bce82 --- /dev/null +++ b/shared/extra-utils/server/follows-command.ts @@ -0,0 +1,124 @@ +import { pick } from 'lodash' +import { ActivityPubActorType, ActorFollow, FollowState, ResultList } from '@shared/models' +import { HttpStatusCode } from '../../core-utils/miscs/http-error-codes' +import { AbstractCommand, OverrideCommandOptions } from '../shared' +import { ServerInfo } from './servers' + +export class FollowsCommand extends AbstractCommand { + + getFollowers (options: OverrideCommandOptions & { + start: number + count: number + sort: string + search?: string + actorType?: ActivityPubActorType + state?: FollowState + }) { + const path = '/api/v1/server/followers' + + const toPick = [ 'start', 'count', 'sort', 'search', 'state', 'actorType' ] + const query = pick(options, toPick) + + return this.getRequestBody>({ + ...options, + + token: null, + + path, + query, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } + + getFollowings (options: OverrideCommandOptions & { + start: number + count: number + sort: string + search?: string + actorType?: ActivityPubActorType + state?: FollowState + }) { + const path = '/api/v1/server/following' + + const toPick = [ 'start', 'count', 'sort', 'search', 'state', 'actorType' ] + const query = pick(options, toPick) + + return this.getRequestBody>({ + ...options, + + token: null, + + path, + query, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } + + follow (options: OverrideCommandOptions & { + targets: string[] + }) { + const path = '/api/v1/server/following' + + const hosts = options.targets.map(f => f.replace(/^http:\/\//, '')) + + return this.postBodyRequest({ + ...options, + + path, + fields: { hosts }, + defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 + }) + } + + async unfollow (options: OverrideCommandOptions & { + target: ServerInfo + }) { + const path = '/api/v1/server/following/' + options.target.host + + return this.deleteRequest({ + ...options, + + path, + defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 + }) + } + + acceptFollower (options: OverrideCommandOptions & { + follower: string + }) { + const path = '/api/v1/server/followers/' + options.follower + '/accept' + + return this.postBodyRequest({ + ...options, + + path, + defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 + }) + } + + rejectFollower (options: OverrideCommandOptions & { + follower: string + }) { + const path = '/api/v1/server/followers/' + options.follower + '/reject' + + return this.postBodyRequest({ + ...options, + + path, + defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 + }) + } + + removeFollower (options: OverrideCommandOptions & { + follower: ServerInfo + }) { + const path = '/api/v1/server/followers/peertube@' + options.follower.host + + return this.deleteRequest({ + ...options, + + path, + defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 + }) + } +} diff --git a/shared/extra-utils/server/follows.ts b/shared/extra-utils/server/follows.ts index 6aae4a31d..c23cebd81 100644 --- a/shared/extra-utils/server/follows.ts +++ b/shared/extra-utils/server/follows.ts @@ -1,126 +1,10 @@ -import * as request from 'supertest' -import { ServerInfo } from './servers' import { waitJobs } from './jobs' -import { makePostBodyRequest } from '../requests/requests' -import { ActivityPubActorType, FollowState } from '@shared/models' -import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' - -function getFollowersListPaginationAndSort (options: { - url: string - start: number - count: number - sort: string - search?: string - actorType?: ActivityPubActorType - state?: FollowState -}) { - const { url, start, count, sort, search, state, actorType } = options - const path = '/api/v1/server/followers' - - const query = { - start, - count, - sort, - search, - state, - actorType - } - - return request(url) - .get(path) - .query(query) - .set('Accept', 'application/json') - .expect(HttpStatusCode.OK_200) - .expect('Content-Type', /json/) -} - -function acceptFollower (url: string, token: string, follower: string, statusCodeExpected = HttpStatusCode.NO_CONTENT_204) { - const path = '/api/v1/server/followers/' + follower + '/accept' - - return makePostBodyRequest({ - url, - token, - path, - statusCodeExpected - }) -} - -function rejectFollower (url: string, token: string, follower: string, statusCodeExpected = HttpStatusCode.NO_CONTENT_204) { - const path = '/api/v1/server/followers/' + follower + '/reject' - - return makePostBodyRequest({ - url, - token, - path, - statusCodeExpected - }) -} - -function getFollowingListPaginationAndSort (options: { - url: string - start: number - count: number - sort: string - search?: string - actorType?: ActivityPubActorType - state?: FollowState -}) { - const { url, start, count, sort, search, state, actorType } = options - const path = '/api/v1/server/following' - - const query = { - start, - count, - sort, - search, - state, - actorType - } - - return request(url) - .get(path) - .query(query) - .set('Accept', 'application/json') - .expect(HttpStatusCode.OK_200) - .expect('Content-Type', /json/) -} - -function follow (follower: string, following: string[], accessToken: string, expectedStatus = HttpStatusCode.NO_CONTENT_204) { - const path = '/api/v1/server/following' - - const followingHosts = following.map(f => f.replace(/^http:\/\//, '')) - return request(follower) - .post(path) - .set('Accept', 'application/json') - .set('Authorization', 'Bearer ' + accessToken) - .send({ hosts: followingHosts }) - .expect(expectedStatus) -} - -async function unfollow (url: string, accessToken: string, target: ServerInfo, expectedStatus = HttpStatusCode.NO_CONTENT_204) { - const path = '/api/v1/server/following/' + target.host - - return request(url) - .delete(path) - .set('Accept', 'application/json') - .set('Authorization', 'Bearer ' + accessToken) - .expect(expectedStatus) -} - -function removeFollower (url: string, accessToken: string, follower: ServerInfo, expectedStatus = HttpStatusCode.NO_CONTENT_204) { - const path = '/api/v1/server/followers/peertube@' + follower.host - - return request(url) - .delete(path) - .set('Accept', 'application/json') - .set('Authorization', 'Bearer ' + accessToken) - .expect(expectedStatus) -} +import { ServerInfo } from './servers' async function doubleFollow (server1: ServerInfo, server2: ServerInfo) { await Promise.all([ - follow(server1.url, [ server2.url ], server1.accessToken), - follow(server2.url, [ server1.url ], server2.accessToken) + server1.followsCommand.follow({ targets: [ server2.url ] }), + server2.followsCommand.follow({ targets: [ server1.url ] }) ]) // Wait request propagation @@ -132,12 +16,5 @@ async function doubleFollow (server1: ServerInfo, server2: ServerInfo) { // --------------------------------------------------------------------------- export { - getFollowersListPaginationAndSort, - getFollowingListPaginationAndSort, - unfollow, - removeFollower, - follow, - doubleFollow, - acceptFollower, - rejectFollower + doubleFollow } diff --git a/shared/extra-utils/server/index.ts b/shared/extra-utils/server/index.ts index f0071ba72..258084623 100644 --- a/shared/extra-utils/server/index.ts +++ b/shared/extra-utils/server/index.ts @@ -1,2 +1,4 @@ export * from './contact-form-command' export * from './debug-command' +export * from './follows-command' +export * from './follows' diff --git a/shared/extra-utils/server/servers.ts b/shared/extra-utils/server/servers.ts index 30e712ab8..7ac80cea0 100644 --- a/shared/extra-utils/server/servers.ts +++ b/shared/extra-utils/server/servers.ts @@ -18,6 +18,7 @@ import { makeGetRequest } from '../requests/requests' import { SearchCommand } from '../search' import { ContactFormCommand } from './contact-form-command' import { DebugCommand } from './debug-command' +import { FollowsCommand } from './follows-command' interface ServerInfo { app: ChildProcess @@ -81,6 +82,7 @@ interface ServerInfo { searchCommand?: SearchCommand contactFormCommand?: ContactFormCommand debugCommand?: DebugCommand + followsCommand?: FollowsCommand } function parallelTests () { @@ -296,6 +298,7 @@ async function runServer (server: ServerInfo, configOverrideArg?: any, args = [] server.searchCommand = new SearchCommand(server) server.contactFormCommand = new ContactFormCommand(server) server.debugCommand = new DebugCommand(server) + server.followsCommand = new FollowsCommand(server) res(server) }) -- cgit v1.2.3 From 9c6327f803aaf4200672f1fc40b2f43786daca47 Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Wed, 7 Jul 2021 09:34:56 +0200 Subject: Introduce jobs command --- server/tests/api/server/handle-down.ts | 7 +-- server/tests/api/server/jobs.ts | 50 +++++++++++---------- server/tests/api/videos/video-transcoder.ts | 8 +--- shared/extra-utils/index.ts | 1 - shared/extra-utils/server/index.ts | 2 + shared/extra-utils/server/jobs-command.ts | 35 +++++++++++++++ shared/extra-utils/server/jobs.ts | 67 +++-------------------------- shared/extra-utils/server/servers.ts | 3 ++ 8 files changed, 75 insertions(+), 98 deletions(-) create mode 100644 shared/extra-utils/server/jobs-command.ts diff --git a/server/tests/api/server/handle-down.ts b/server/tests/api/server/handle-down.ts index eff4451e5..c6202fdaa 100644 --- a/server/tests/api/server/handle-down.ts +++ b/server/tests/api/server/handle-down.ts @@ -10,7 +10,6 @@ import { closeAllSequelize, completeVideoCheck, flushAndRunMultipleServers, - getJobsListPaginationAndSort, getVideo, getVideoCommentThreads, getVideosList, @@ -181,15 +180,13 @@ describe('Test handle downs', function () { const states: JobState[] = [ 'waiting', 'active' ] for (const state of states) { - const res = await getJobsListPaginationAndSort({ - url: servers[0].url, - accessToken: servers[0].accessToken, + const body = await servers[0].jobsCommand.getJobsList({ state: state, start: 0, count: 50, sort: '-createdAt' }) - expect(res.body.data).to.have.length(0) + expect(body.data).to.have.length(0) } }) diff --git a/server/tests/api/server/jobs.ts b/server/tests/api/server/jobs.ts index 6576dd7af..c0b9facff 100644 --- a/server/tests/api/server/jobs.ts +++ b/server/tests/api/server/jobs.ts @@ -2,13 +2,16 @@ import 'mocha' import * as chai from 'chai' -import { cleanupTests, ServerInfo, setAccessTokensToServers } from '../../../../shared/extra-utils/index' -import { dateIsValid } from '../../../../shared/extra-utils/miscs/miscs' -import { doubleFollow } from '../../../../shared/extra-utils/server/follows' -import { getJobsList, getJobsListPaginationAndSort, waitJobs } from '../../../../shared/extra-utils/server/jobs' -import { flushAndRunMultipleServers } from '../../../../shared/extra-utils/server/servers' -import { uploadVideo } from '../../../../shared/extra-utils/videos/videos' -import { Job } from '../../../../shared/models/server' +import { + cleanupTests, + dateIsValid, + doubleFollow, + flushAndRunMultipleServers, + ServerInfo, + setAccessTokensToServers, + uploadVideo, + waitJobs +} from '@shared/extra-utils' const expect = chai.expect @@ -36,27 +39,25 @@ describe('Test jobs', function () { }) it('Should list jobs', async function () { - const res = await getJobsList(servers[1].url, servers[1].accessToken, 'completed') - expect(res.body.total).to.be.above(2) - expect(res.body.data).to.have.length.above(2) + const body = await servers[1].jobsCommand.getJobsList({ state: 'completed' }) + expect(body.total).to.be.above(2) + expect(body.data).to.have.length.above(2) }) it('Should list jobs with sort, pagination and job type', async function () { { - const res = await getJobsListPaginationAndSort({ - url: servers[1].url, - accessToken: servers[1].accessToken, + const body = await servers[1].jobsCommand.getJobsList({ state: 'completed', start: 1, count: 2, sort: 'createdAt' }) - expect(res.body.total).to.be.above(2) - expect(res.body.data).to.have.lengthOf(2) + expect(body.total).to.be.above(2) + expect(body.data).to.have.lengthOf(2) - let job: Job = res.body.data[0] + let job = body.data[0] // Skip repeat jobs - if (job.type === 'videos-views') job = res.body.data[1] + if (job.type === 'videos-views') job = body.data[1] expect(job.state).to.equal('completed') expect(job.type.startsWith('activitypub-')).to.be.true @@ -66,29 +67,26 @@ describe('Test jobs', function () { } { - const res = await getJobsListPaginationAndSort({ - url: servers[1].url, - accessToken: servers[1].accessToken, + const body = await servers[1].jobsCommand.getJobsList({ state: 'completed', start: 0, count: 100, sort: 'createdAt', jobType: 'activitypub-http-broadcast' }) - expect(res.body.total).to.be.above(2) + expect(body.total).to.be.above(2) - for (const j of res.body.data as Job[]) { + for (const j of body.data) { expect(j.type).to.equal('activitypub-http-broadcast') } } }) it('Should list all jobs', async function () { - const res = await getJobsList(servers[1].url, servers[1].accessToken) + const body = await servers[1].jobsCommand.getJobsList() + expect(body.total).to.be.above(2) - const jobs = res.body.data as Job[] - - expect(res.body.total).to.be.above(2) + const jobs = body.data expect(jobs).to.have.length.above(2) // We know there are a least 1 delayed job (video views) and 1 completed job (broadcast) diff --git a/server/tests/api/videos/video-transcoder.ts b/server/tests/api/videos/video-transcoder.ts index ea5ffd239..c95053a29 100644 --- a/server/tests/api/videos/video-transcoder.ts +++ b/server/tests/api/videos/video-transcoder.ts @@ -16,7 +16,6 @@ import { flushAndRunMultipleServers, generateHighBitrateVideo, generateVideoWithFramerate, - getJobsListPaginationAndSort, getMyVideos, getServerFileSize, getVideo, @@ -709,17 +708,14 @@ describe('Test video transcoding', function () { describe('Transcoding job queue', function () { it('Should have the appropriate priorities for transcoding jobs', async function () { - const res = await getJobsListPaginationAndSort({ - url: servers[1].url, - accessToken: servers[1].accessToken, + const body = await servers[1].jobsCommand.getJobsList({ start: 0, count: 100, sort: '-createdAt', jobType: 'video-transcoding' }) - const jobs = res.body.data as Job[] - + const jobs = body.data const transcodingJobs = jobs.filter(j => j.data.videoUUID === video4k) expect(transcodingJobs).to.have.lengthOf(14) diff --git a/shared/extra-utils/index.ts b/shared/extra-utils/index.ts index 48431ed83..652779eea 100644 --- a/shared/extra-utils/index.ts +++ b/shared/extra-utils/index.ts @@ -15,7 +15,6 @@ export * from './requests/requests' export * from './server/clients' export * from './server/config' -export * from './server/jobs' export * from './server/plugins' export * from './server/servers' diff --git a/shared/extra-utils/server/index.ts b/shared/extra-utils/server/index.ts index 258084623..b5b6b2116 100644 --- a/shared/extra-utils/server/index.ts +++ b/shared/extra-utils/server/index.ts @@ -2,3 +2,5 @@ export * from './contact-form-command' export * from './debug-command' export * from './follows-command' export * from './follows' +export * from './jobs' +export * from './jobs-command' diff --git a/shared/extra-utils/server/jobs-command.ts b/shared/extra-utils/server/jobs-command.ts new file mode 100644 index 000000000..758b4a4af --- /dev/null +++ b/shared/extra-utils/server/jobs-command.ts @@ -0,0 +1,35 @@ +import { pick } from 'lodash' +import { HttpStatusCode } from '../../core-utils/miscs/http-error-codes' +import { Job, JobState, JobType, ResultList } from '../../models' +import { AbstractCommand, OverrideCommandOptions } from '../shared' + +export class JobsCommand extends AbstractCommand { + + getJobsList (options: OverrideCommandOptions & { + state?: JobState + jobType?: JobType + start?: number + count?: number + sort?: string + } = {}) { + const path = this.buildJobsUrl(options.state) + + const query = pick(options, [ 'start', 'count', 'sort', 'jobType' ]) + + return this.getRequestBody>({ + ...options, + + path, + query, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } + + private buildJobsUrl (state?: JobState) { + let path = '/api/v1/jobs' + + if (state) path += '/' + state + + return path + } +} diff --git a/shared/extra-utils/server/jobs.ts b/shared/extra-utils/server/jobs.ts index a3683913a..b4b3d52e7 100644 --- a/shared/extra-utils/server/jobs.ts +++ b/shared/extra-utils/server/jobs.ts @@ -1,57 +1,8 @@ -import * as request from 'supertest' -import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' -import { makeGetRequest } from '../../../shared/extra-utils' -import { Job, JobState, JobType } from '../../models' + +import { JobState } from '../../models' import { wait } from '../miscs/miscs' import { ServerInfo } from './servers' -function buildJobsUrl (state?: JobState) { - let path = '/api/v1/jobs' - - if (state) path += '/' + state - - return path -} - -function getJobsList (url: string, accessToken: string, state?: JobState) { - const path = buildJobsUrl(state) - - return request(url) - .get(path) - .set('Accept', 'application/json') - .set('Authorization', 'Bearer ' + accessToken) - .expect(HttpStatusCode.OK_200) - .expect('Content-Type', /json/) -} - -function getJobsListPaginationAndSort (options: { - url: string - accessToken: string - start: number - count: number - sort: string - state?: JobState - jobType?: JobType -}) { - const { url, accessToken, state, start, count, sort, jobType } = options - const path = buildJobsUrl(state) - - const query = { - start, - count, - sort, - jobType - } - - return makeGetRequest({ - url, - path, - token: accessToken, - statusCodeExpected: HttpStatusCode.OK_200, - query - }) -} - async function waitJobs (serversArg: ServerInfo[] | ServerInfo) { const pendingJobWait = process.env.NODE_PENDING_JOB_WAIT ? parseInt(process.env.NODE_PENDING_JOB_WAIT, 10) @@ -72,15 +23,13 @@ async function waitJobs (serversArg: ServerInfo[] | ServerInfo) { // Check if each server has pending request for (const server of servers) { for (const state of states) { - const p = getJobsListPaginationAndSort({ - url: server.url, - accessToken: server.accessToken, - state: state, + const p = server.jobsCommand.getJobsList({ + state, start: 0, count: 10, sort: '-createdAt' - }).then(res => res.body.data) - .then((jobs: Job[]) => jobs.filter(j => !repeatableJobs.includes(j.type))) + }).then(body => body.data) + .then(jobs => jobs.filter(j => !repeatableJobs.includes(j.type))) .then(jobs => { if (jobs.length !== 0) { pendingRequests = true @@ -122,7 +71,5 @@ async function waitJobs (serversArg: ServerInfo[] | ServerInfo) { // --------------------------------------------------------------------------- export { - getJobsList, - waitJobs, - getJobsListPaginationAndSort + waitJobs } diff --git a/shared/extra-utils/server/servers.ts b/shared/extra-utils/server/servers.ts index 7ac80cea0..5511ce0b0 100644 --- a/shared/extra-utils/server/servers.ts +++ b/shared/extra-utils/server/servers.ts @@ -19,6 +19,7 @@ import { SearchCommand } from '../search' import { ContactFormCommand } from './contact-form-command' import { DebugCommand } from './debug-command' import { FollowsCommand } from './follows-command' +import { JobsCommand } from './jobs-command' interface ServerInfo { app: ChildProcess @@ -83,6 +84,7 @@ interface ServerInfo { contactFormCommand?: ContactFormCommand debugCommand?: DebugCommand followsCommand?: FollowsCommand + jobsCommand?: JobsCommand } function parallelTests () { @@ -299,6 +301,7 @@ async function runServer (server: ServerInfo, configOverrideArg?: any, args = [] server.contactFormCommand = new ContactFormCommand(server) server.debugCommand = new DebugCommand(server) server.followsCommand = new FollowsCommand(server) + server.jobsCommand = new JobsCommand(server) res(server) }) -- cgit v1.2.3 From ae2abfd3aed3e75d39a316b49b914d187faa7475 Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Wed, 7 Jul 2021 10:33:49 +0200 Subject: Introduce plugins command --- server/tests/api/check-params/plugins.ts | 5 +- .../tests/api/notifications/admin-notifications.ts | 31 +-- server/tests/api/server/plugins.ts | 188 ++++--------- server/tests/api/users/users.ts | 3 +- server/tests/cli/plugins.ts | 4 +- server/tests/external-plugins/auth-ldap.ts | 28 +- server/tests/external-plugins/auto-block-videos.ts | 19 +- server/tests/external-plugins/auto-mute.ts | 40 +-- server/tests/plugins/action-hooks.ts | 9 +- server/tests/plugins/external-auth.ts | 47 ++-- server/tests/plugins/filter-hooks.ts | 16 +- server/tests/plugins/html-injection.ts | 33 +-- server/tests/plugins/id-and-pass-auth.ts | 36 ++- server/tests/plugins/plugin-helpers.ts | 24 +- server/tests/plugins/plugin-router.ts | 27 +- server/tests/plugins/plugin-storage.ts | 29 +- server/tests/plugins/plugin-transcoding.ts | 26 +- server/tests/plugins/plugin-unloading.ts | 32 +-- server/tests/plugins/translations.ts | 46 ++-- server/tests/plugins/video-constants.ts | 28 +- shared/extra-utils/index.ts | 1 - shared/extra-utils/server/index.ts | 2 + shared/extra-utils/server/plugins-command.ts | 245 +++++++++++++++++ shared/extra-utils/server/plugins.ts | 297 +-------------------- shared/extra-utils/server/servers.ts | 3 + shared/extra-utils/shared/abstract-command.ts | 26 +- 26 files changed, 480 insertions(+), 765 deletions(-) create mode 100644 shared/extra-utils/server/plugins-command.ts diff --git a/server/tests/api/check-params/plugins.ts b/server/tests/api/check-params/plugins.ts index a833fe6ff..d372221d0 100644 --- a/server/tests/api/check-params/plugins.ts +++ b/server/tests/api/check-params/plugins.ts @@ -10,7 +10,6 @@ import { createUser, flushAndRunServer, immutableAssign, - installPlugin, makeGetRequest, makePostBodyRequest, makePutBodyRequest, @@ -50,13 +49,13 @@ describe('Test server plugins API validators', function () { userAccessToken = await userLogin(server, user) { - const res = await installPlugin({ url: server.url, accessToken: server.accessToken, npmName: npmPlugin }) + const res = await server.pluginsCommand.install({ npmName: npmPlugin }) const plugin = res.body as PeerTubePlugin npmVersion = plugin.version } { - const res = await installPlugin({ url: server.url, accessToken: server.accessToken, npmName: themePlugin }) + const res = await server.pluginsCommand.install({ npmName: themePlugin }) const plugin = res.body as PeerTubePlugin themeVersion = plugin.version } diff --git a/server/tests/api/notifications/admin-notifications.ts b/server/tests/api/notifications/admin-notifications.ts index 91681c9d6..da9767b74 100644 --- a/server/tests/api/notifications/admin-notifications.ts +++ b/server/tests/api/notifications/admin-notifications.ts @@ -2,18 +2,20 @@ import 'mocha' import { expect } from 'chai' -import { MockJoinPeerTubeVersions } from '@shared/extra-utils' -import { PluginType } from '@shared/models' -import { cleanupTests, installPlugin, setPluginLatestVersion, setPluginVersion, wait } from '../../../../shared/extra-utils' -import { ServerInfo } from '../../../../shared/extra-utils/index' -import { MockSmtpServer } from '../../../../shared/extra-utils/mock-servers/mock-email' import { CheckerBaseParams, checkNewPeerTubeVersion, checkNewPluginVersion, - prepareNotificationsTest -} from '../../../../shared/extra-utils/users/user-notifications' -import { UserNotification, UserNotificationType } from '../../../../shared/models/users' + cleanupTests, + MockJoinPeerTubeVersions, + MockSmtpServer, + prepareNotificationsTest, + ServerInfo, + setPluginLatestVersion, + setPluginVersion, + wait +} from '@shared/extra-utils' +import { PluginType, UserNotification, UserNotificationType } from '@shared/models' describe('Test admin notifications', function () { let server: ServerInfo @@ -58,17 +60,8 @@ describe('Test admin notifications', function () { token: server.accessToken } - await installPlugin({ - url: server.url, - accessToken: server.accessToken, - npmName: 'peertube-plugin-hello-world' - }) - - await installPlugin({ - url: server.url, - accessToken: server.accessToken, - npmName: 'peertube-theme-background-red' - }) + await server.pluginsCommand.install({ npmName: 'peertube-plugin-hello-world' }) + await server.pluginsCommand.install({ npmName: 'peertube-theme-background-red' }) }) describe('Latest PeerTube version notification', function () { diff --git a/server/tests/api/server/plugins.ts b/server/tests/api/server/plugins.ts index 6b61c7c33..1536997d5 100644 --- a/server/tests/api/server/plugins.ts +++ b/server/tests/api/server/plugins.ts @@ -9,34 +9,25 @@ import { flushAndRunServer, getConfig, getMyUserInformation, - getPlugin, - getPluginPackageJSON, - getPluginTestPath, - getPublicSettings, - installPlugin, killallServers, - listAvailablePlugins, - listPlugins, + PluginsCommand, reRunServer, ServerInfo, setAccessTokensToServers, setPluginVersion, testHelloWorldRegisteredSettings, - uninstallPlugin, updateCustomSubConfig, updateMyUser, - updatePlugin, - updatePluginPackageJSON, - updatePluginSettings, wait, waitUntilLog } from '@shared/extra-utils' -import { PeerTubePlugin, PeerTubePluginIndex, PluginPackageJson, PluginType, PublicServerSetting, ServerConfig, User } from '@shared/models' +import { PluginType, ServerConfig, User } from '@shared/models' const expect = chai.expect describe('Test plugins', function () { let server: ServerInfo = null + let command: PluginsCommand before(async function () { this.timeout(30000) @@ -54,60 +45,51 @@ describe('Test plugins', function () { this.timeout(30000) { - const res = await listAvailablePlugins({ - url: server.url, - accessToken: server.accessToken, + const body = await command.listAvailable({ count: 1, start: 0, pluginType: PluginType.THEME, search: 'background-red' }) - expect(res.body.total).to.be.at.least(1) - expect(res.body.data).to.have.lengthOf(1) + expect(body.total).to.be.at.least(1) + expect(body.data).to.have.lengthOf(1) } { - const res1 = await listAvailablePlugins({ - url: server.url, - accessToken: server.accessToken, + const body1 = await command.listAvailable({ count: 2, start: 0, sort: 'npmName' }) - const data1: PeerTubePluginIndex[] = res1.body.data + expect(body1.total).to.be.at.least(2) - expect(res1.body.total).to.be.at.least(2) + const data1 = body1.data expect(data1).to.have.lengthOf(2) - const res2 = await listAvailablePlugins({ - url: server.url, - accessToken: server.accessToken, + const body2 = await command.listAvailable({ count: 2, start: 0, sort: '-npmName' }) - const data2: PeerTubePluginIndex[] = res2.body.data + expect(body2.total).to.be.at.least(2) - expect(res2.body.total).to.be.at.least(2) + const data2 = body2.data expect(data2).to.have.lengthOf(2) expect(data1[0].npmName).to.not.equal(data2[0].npmName) } { - const res = await listAvailablePlugins({ - url: server.url, - accessToken: server.accessToken, + const body = await command.listAvailable({ count: 10, start: 0, pluginType: PluginType.THEME, search: 'background-red', currentPeerTubeEngine: '1.0.0' }) - const data: PeerTubePluginIndex[] = res.body.data - const p = data.find(p => p.npmName === 'peertube-theme-background-red') + const p = body.data.find(p => p.npmName === 'peertube-theme-background-red') expect(p).to.be.undefined } }) @@ -115,17 +97,8 @@ describe('Test plugins', function () { it('Should install a plugin and a theme', async function () { this.timeout(30000) - await installPlugin({ - url: server.url, - accessToken: server.accessToken, - npmName: 'peertube-plugin-hello-world' - }) - - await installPlugin({ - url: server.url, - accessToken: server.accessToken, - npmName: 'peertube-theme-background-red' - }) + await command.install({ npmName: 'peertube-plugin-hello-world' }) + await command.install({ npmName: 'peertube-theme-background-red' }) }) it('Should have the plugin loaded in the configuration', async function () { @@ -161,45 +134,38 @@ describe('Test plugins', function () { it('Should list plugins and themes', async function () { { - const res = await listPlugins({ - url: server.url, - accessToken: server.accessToken, + const body = await command.list({ count: 1, start: 0, pluginType: PluginType.THEME }) - const data: PeerTubePlugin[] = res.body.data + expect(body.total).to.be.at.least(1) - expect(res.body.total).to.be.at.least(1) + const data = body.data expect(data).to.have.lengthOf(1) expect(data[0].name).to.equal('background-red') } { - const res = await listPlugins({ - url: server.url, - accessToken: server.accessToken, + const body = await command.list({ count: 2, start: 0, sort: 'name' }) - const data: PeerTubePlugin[] = res.body.data + const data = body expect(data[0].name).to.equal('background-red') expect(data[1].name).to.equal('hello-world') } { - const res = await listPlugins({ - url: server.url, - accessToken: server.accessToken, + const body = await command.list({ count: 2, start: 1, sort: 'name' }) - const data: PeerTubePlugin[] = res.body.data - expect(data[0].name).to.equal('hello-world') + expect(body.data[0].name).to.equal('hello-world') } }) @@ -208,9 +174,8 @@ describe('Test plugins', function () { }) it('Should get public settings', async function () { - const res = await getPublicSettings({ url: server.url, npmName: 'peertube-plugin-hello-world' }) - - const publicSettings = (res.body as PublicServerSetting).publicSettings + const body = await command.getPublicSettings({ npmName: 'peertube-plugin-hello-world' }) + const publicSettings = body.publicSettings expect(Object.keys(publicSettings)).to.have.lengthOf(1) expect(Object.keys(publicSettings)).to.deep.equal([ 'user-name' ]) @@ -222,9 +187,7 @@ describe('Test plugins', function () { 'admin-name': 'Cid' } - await updatePluginSettings({ - url: server.url, - accessToken: server.accessToken, + await command.updateSettings({ npmName: 'peertube-plugin-hello-world', settings }) @@ -238,13 +201,7 @@ describe('Test plugins', function () { it('Should get a plugin and a theme', async function () { { - const res = await getPlugin({ - url: server.url, - accessToken: server.accessToken, - npmName: 'peertube-plugin-hello-world' - }) - - const plugin: PeerTubePlugin = res.body + const plugin = await command.get({ npmName: 'peertube-plugin-hello-world' }) expect(plugin.type).to.equal(PluginType.PLUGIN) expect(plugin.name).to.equal('hello-world') @@ -262,13 +219,7 @@ describe('Test plugins', function () { } { - const res = await getPlugin({ - url: server.url, - accessToken: server.accessToken, - npmName: 'peertube-theme-background-red' - }) - - const plugin: PeerTubePlugin = res.body + const plugin = await command.get({ npmName: 'peertube-theme-background-red' }) expect(plugin.type).to.equal(PluginType.THEME) expect(plugin.name).to.equal('background-red') @@ -295,92 +246,59 @@ describe('Test plugins', function () { await setPluginVersion(server.internalServerNumber, 'hello-world', '0.0.1') // Fake update package.json - const packageJSON: PluginPackageJson = await getPluginPackageJSON(server, 'peertube-plugin-hello-world') + const packageJSON = await command.getPackageJSON('peertube-plugin-hello-world') const oldVersion = packageJSON.version packageJSON.version = '0.0.1' - await updatePluginPackageJSON(server, 'peertube-plugin-hello-world', packageJSON) + await command.updatePackageJSON('peertube-plugin-hello-world', packageJSON) // Restart the server to take into account this change killallServers([ server ]) await reRunServer(server) { - const res = await listPlugins({ - url: server.url, - accessToken: server.accessToken, - pluginType: PluginType.PLUGIN - }) - - const plugin: PeerTubePlugin = res.body.data[0] + const body = await command.list({ pluginType: PluginType.PLUGIN }) + const plugin = body.data[0] expect(plugin.version).to.equal('0.0.1') expect(plugin.latestVersion).to.exist expect(plugin.latestVersion).to.not.equal('0.0.1') } { - await updatePlugin({ - url: server.url, - accessToken: server.accessToken, - npmName: 'peertube-plugin-hello-world' - }) - - const res = await listPlugins({ - url: server.url, - accessToken: server.accessToken, - pluginType: PluginType.PLUGIN - }) + await command.update({ npmName: 'peertube-plugin-hello-world' }) - const plugin: PeerTubePlugin = res.body.data[0] + const body = await command.list({ pluginType: PluginType.PLUGIN }) + const plugin = body.data[0] expect(plugin.version).to.equal(oldVersion) - const updatedPackageJSON: PluginPackageJson = await getPluginPackageJSON(server, 'peertube-plugin-hello-world') + const updatedPackageJSON = await command.getPackageJSON('peertube-plugin-hello-world') expect(updatedPackageJSON.version).to.equal(oldVersion) } }) it('Should uninstall the plugin', async function () { - await uninstallPlugin({ - url: server.url, - accessToken: server.accessToken, - npmName: 'peertube-plugin-hello-world' - }) - - const res = await listPlugins({ - url: server.url, - accessToken: server.accessToken, - pluginType: PluginType.PLUGIN - }) + await command.uninstall({ npmName: 'peertube-plugin-hello-world' }) - expect(res.body.total).to.equal(0) - expect(res.body.data).to.have.lengthOf(0) + const body = await command.list({ pluginType: PluginType.PLUGIN }) + expect(body.total).to.equal(0) + expect(body.data).to.have.lengthOf(0) }) it('Should list uninstalled plugins', async function () { - const res = await listPlugins({ - url: server.url, - accessToken: server.accessToken, - pluginType: PluginType.PLUGIN, - uninstalled: true - }) + const body = await command.list({ pluginType: PluginType.PLUGIN, uninstalled: true }) + expect(body.total).to.equal(1) + expect(body.data).to.have.lengthOf(1) - expect(res.body.total).to.equal(1) - expect(res.body.data).to.have.lengthOf(1) - - const plugin: PeerTubePlugin = res.body.data[0] + const plugin = body.data[0] expect(plugin.name).to.equal('hello-world') expect(plugin.enabled).to.be.false expect(plugin.uninstalled).to.be.true }) it('Should uninstall the theme', async function () { - await uninstallPlugin({ - url: server.url, - accessToken: server.accessToken, - npmName: 'peertube-theme-background-red' - }) + await command.uninstall({ npmName: 'peertube-theme-background-red' }) }) it('Should have updated the configuration', async function () { @@ -406,21 +324,13 @@ describe('Test plugins', function () { this.timeout(60000) async function check () { - const res = await listPlugins({ - url: server.url, - accessToken: server.accessToken, - pluginType: PluginType.PLUGIN - }) - - const plugins: PeerTubePlugin[] = res.body.data - + const body = await command.list({ pluginType: PluginType.PLUGIN }) + const plugins = body.data expect(plugins.find(p => p.name === 'test-broken')).to.not.exist } - await installPlugin({ - url: server.url, - accessToken: server.accessToken, - path: getPluginTestPath('-broken'), + await command.install({ + path: PluginsCommand.getPluginTestPath('-broken'), expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) diff --git a/server/tests/api/users/users.ts b/server/tests/api/users/users.ts index 92927ea97..ba4183e08 100644 --- a/server/tests/api/users/users.ts +++ b/server/tests/api/users/users.ts @@ -23,7 +23,6 @@ import { getUsersListPaginationAndSort, getVideoChannel, getVideosList, - installPlugin, killallServers, login, logout, @@ -75,7 +74,7 @@ describe('Test users', function () { await setAccessTokensToServers([ server ]) - await installPlugin({ url: server.url, accessToken: server.accessToken, npmName: 'peertube-theme-background-red' }) + await server.pluginsCommand.install({ npmName: 'peertube-theme-background-red' }) }) describe('OAuth client', function () { diff --git a/server/tests/cli/plugins.ts b/server/tests/cli/plugins.ts index efdc20748..7b8746a5d 100644 --- a/server/tests/cli/plugins.ts +++ b/server/tests/cli/plugins.ts @@ -6,8 +6,8 @@ import { cleanupTests, flushAndRunServer, getConfig, - getPluginTestPath, killallServers, + PluginsCommand, reRunServer, ServerInfo, setAccessTokensToServers @@ -27,7 +27,7 @@ describe('Test plugin scripts', function () { it('Should install a plugin from stateless CLI', async function () { this.timeout(60000) - const packagePath = getPluginTestPath() + const packagePath = PluginsCommand.getPluginTestPath() await server.cliCommand.execWithEnv(`npm run plugin:install -- --plugin-path ${packagePath}`) }) diff --git a/server/tests/external-plugins/auth-ldap.ts b/server/tests/external-plugins/auth-ldap.ts index e4eae7e8c..0d4edbee0 100644 --- a/server/tests/external-plugins/auth-ldap.ts +++ b/server/tests/external-plugins/auth-ldap.ts @@ -3,17 +3,7 @@ import 'mocha' import { expect } from 'chai' import { User } from '@shared/models/users/user.model' -import { - blockUser, - getMyUserInformation, - installPlugin, - setAccessTokensToServers, - unblockUser, - uninstallPlugin, - updatePluginSettings, - uploadVideo, - userLogin -} from '../../../shared/extra-utils' +import { blockUser, getMyUserInformation, setAccessTokensToServers, unblockUser, uploadVideo, userLogin } from '../../../shared/extra-utils' import { cleanupTests, flushAndRunServer, ServerInfo } from '../../../shared/extra-utils/server/servers' describe('Official plugin auth-ldap', function () { @@ -27,11 +17,7 @@ describe('Official plugin auth-ldap', function () { server = await flushAndRunServer(1) await setAccessTokensToServers([ server ]) - await installPlugin({ - url: server.url, - accessToken: server.accessToken, - npmName: 'peertube-plugin-auth-ldap' - }) + await server.pluginsCommand.install({ npmName: 'peertube-plugin-auth-ldap' }) }) it('Should not login with without LDAP settings', async function () { @@ -39,9 +25,7 @@ describe('Official plugin auth-ldap', function () { }) it('Should not login with bad LDAP settings', async function () { - await updatePluginSettings({ - url: server.url, - accessToken: server.accessToken, + await server.pluginsCommand.updateSettings({ npmName: 'peertube-plugin-auth-ldap', settings: { 'bind-credentials': 'GoodNewsEveryone', @@ -59,9 +43,7 @@ describe('Official plugin auth-ldap', function () { }) it('Should not login with good LDAP settings but wrong username/password', async function () { - await updatePluginSettings({ - url: server.url, - accessToken: server.accessToken, + await server.pluginsCommand.updateSettings({ npmName: 'peertube-plugin-auth-ldap', settings: { 'bind-credentials': 'GoodNewsEveryone', @@ -114,7 +96,7 @@ describe('Official plugin auth-ldap', function () { }) it('Should not login if the plugin is uninstalled', async function () { - await uninstallPlugin({ url: server.url, accessToken: server.accessToken, npmName: 'peertube-plugin-auth-ldap' }) + await server.pluginsCommand.uninstall({ npmName: 'peertube-plugin-auth-ldap' }) await userLogin(server, { username: 'fry@planetexpress.com', password: 'fry' }, 400) }) diff --git a/server/tests/external-plugins/auto-block-videos.ts b/server/tests/external-plugins/auto-block-videos.ts index 18ea17d78..6baf37566 100644 --- a/server/tests/external-plugins/auto-block-videos.ts +++ b/server/tests/external-plugins/auto-block-videos.ts @@ -7,11 +7,9 @@ import { doubleFollow, getBlacklistedVideosList, getVideosList, - installPlugin, MockBlocklist, removeVideoFromBlacklist, setAccessTokensToServers, - updatePluginSettings, uploadVideoAndGetId, wait } from '../../../shared/extra-utils' @@ -28,11 +26,8 @@ async function check (server: ServerInfo, videoUUID: string, exists = true) { const video = res.body.data.find(v => v.uuid === videoUUID) - if (exists) { - expect(video).to.not.be.undefined - } else { - expect(video).to.be.undefined - } + if (exists) expect(video).to.not.be.undefined + else expect(video).to.be.undefined } describe('Official plugin auto-block videos', function () { @@ -49,11 +44,7 @@ describe('Official plugin auto-block videos', function () { await setAccessTokensToServers(servers) for (const server of servers) { - await installPlugin({ - url: server.url, - accessToken: server.accessToken, - npmName: 'peertube-plugin-auto-block-videos' - }) + await server.pluginsCommand.install({ npmName: 'peertube-plugin-auto-block-videos' }) } blocklistServer = new MockBlocklist() @@ -78,9 +69,7 @@ describe('Official plugin auto-block videos', function () { }) it('Should update plugin settings', async function () { - await updatePluginSettings({ - url: servers[0].url, - accessToken: servers[0].accessToken, + await servers[0].pluginsCommand.updateSettings({ npmName: 'peertube-plugin-auto-block-videos', settings: { 'blocklist-urls': `http://localhost:${port}/blocklist`, diff --git a/server/tests/external-plugins/auto-mute.ts b/server/tests/external-plugins/auto-mute.ts index 09355d932..8fcf94452 100644 --- a/server/tests/external-plugins/auto-mute.ts +++ b/server/tests/external-plugins/auto-mute.ts @@ -2,30 +2,24 @@ import 'mocha' import { expect } from 'chai' +import { HttpStatusCode } from '@shared/core-utils' import { addAccountToServerBlocklist, addServerToAccountBlocklist, - removeAccountFromServerBlocklist -} from '@shared/extra-utils/users/blocklist' -import { + cleanupTests, doubleFollow, + flushAndRunMultipleServers, getVideosList, - installPlugin, + killallServers, makeGetRequest, MockBlocklist, + removeAccountFromServerBlocklist, + reRunServer, + ServerInfo, setAccessTokensToServers, - updatePluginSettings, uploadVideoAndGetId, wait -} from '../../../shared/extra-utils' -import { - cleanupTests, - flushAndRunMultipleServers, - killallServers, - reRunServer, - ServerInfo -} from '../../../shared/extra-utils/server/servers' -import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' +} from '@shared/extra-utils' describe('Official plugin auto-mute', function () { const autoMuteListPath = '/plugins/auto-mute/router/api/v1/mute-list' @@ -40,11 +34,7 @@ describe('Official plugin auto-mute', function () { await setAccessTokensToServers(servers) for (const server of servers) { - await installPlugin({ - url: server.url, - accessToken: server.accessToken, - npmName: 'peertube-plugin-auto-mute' - }) + await server.pluginsCommand.install({ npmName: 'peertube-plugin-auto-mute' }) } blocklistServer = new MockBlocklist() @@ -57,9 +47,7 @@ describe('Official plugin auto-mute', function () { }) it('Should update plugin settings', async function () { - await updatePluginSettings({ - url: servers[0].url, - accessToken: servers[0].accessToken, + await servers[0].pluginsCommand.updateSettings({ npmName: 'peertube-plugin-auto-mute', settings: { 'blocklist-urls': `http://localhost:${port}/blocklist`, @@ -185,9 +173,7 @@ describe('Official plugin auto-mute', function () { }) it('Should enable auto mute list', async function () { - await updatePluginSettings({ - url: servers[0].url, - accessToken: servers[0].accessToken, + await servers[0].pluginsCommand.updateSettings({ npmName: 'peertube-plugin-auto-mute', settings: { 'blocklist-urls': '', @@ -206,9 +192,7 @@ describe('Official plugin auto-mute', function () { it('Should mute an account on server 1, and server 2 auto mutes it', async function () { this.timeout(20000) - await updatePluginSettings({ - url: servers[1].url, - accessToken: servers[1].accessToken, + await servers[1].pluginsCommand.updateSettings({ npmName: 'peertube-plugin-auto-mute', settings: { 'blocklist-urls': 'http://localhost:' + servers[0].port + autoMuteListPath, diff --git a/server/tests/plugins/action-hooks.ts b/server/tests/plugins/action-hooks.ts index 0f57ef7fe..0de5b523b 100644 --- a/server/tests/plugins/action-hooks.ts +++ b/server/tests/plugins/action-hooks.ts @@ -11,8 +11,7 @@ import { createUser, createVideoPlaylist, deleteVideoComment, - getPluginTestPath, - installPlugin, + PluginsCommand, registerUser, removeUser, setAccessTokensToServers, @@ -49,11 +48,7 @@ describe('Test plugin action hooks', function () { await setAccessTokensToServers(servers) await setDefaultVideoChannel(servers) - await installPlugin({ - url: servers[0].url, - accessToken: servers[0].accessToken, - path: getPluginTestPath() - }) + await servers[0].pluginsCommand.install({ path: PluginsCommand.getPluginTestPath() }) killallServers([ servers[0] ]) diff --git a/server/tests/plugins/external-auth.ts b/server/tests/plugins/external-auth.ts index 5addb45c7..424302786 100644 --- a/server/tests/plugins/external-auth.ts +++ b/server/tests/plugins/external-auth.ts @@ -2,27 +2,26 @@ import 'mocha' import { expect } from 'chai' -import { ServerConfig, User, UserRole } from '@shared/models' +import { HttpStatusCode } from '@shared/core-utils' import { + cleanupTests, + createUser, decodeQueryString, + flushAndRunServer, getConfig, - getExternalAuth, getMyUserInformation, - getPluginTestPath, - installPlugin, loginUsingExternalToken, logout, + PluginsCommand, refreshToken, + ServerInfo, setAccessTokensToServers, - uninstallPlugin, updateMyUser, - wait, userLogin, - updatePluginSettings, - createUser -} from '../../../shared/extra-utils' -import { cleanupTests, flushAndRunServer, ServerInfo, waitUntilLog } from '../../../shared/extra-utils/server/servers' -import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' + wait, + waitUntilLog +} from '@shared/extra-utils' +import { ServerConfig, User, UserRole } from '@shared/models' async function loginExternal (options: { server: ServerInfo @@ -33,13 +32,12 @@ async function loginExternal (options: { statusCodeExpected?: HttpStatusCode statusCodeExpectedStep2?: HttpStatusCode }) { - const res = await getExternalAuth({ - url: options.server.url, + const res = await options.server.pluginsCommand.getExternalAuth({ npmName: options.npmName, npmVersion: '0.0.1', authName: options.authName, query: options.query, - statusCodeExpected: options.statusCodeExpected || HttpStatusCode.FOUND_302 + expectedStatus: options.statusCodeExpected || HttpStatusCode.FOUND_302 }) if (res.status !== HttpStatusCode.FOUND_302) return @@ -75,11 +73,7 @@ describe('Test external auth plugins', function () { await setAccessTokensToServers([ server ]) for (const suffix of [ 'one', 'two', 'three' ]) { - await installPlugin({ - url: server.url, - accessToken: server.accessToken, - path: getPluginTestPath('-external-auth-' + suffix) - }) + await server.pluginsCommand.install({ path: PluginsCommand.getPluginTestPath('-external-auth-' + suffix) }) } }) @@ -98,15 +92,14 @@ describe('Test external auth plugins', function () { }) it('Should redirect for a Cyan login', async function () { - const res = await getExternalAuth({ - url: server.url, + const res = await server.pluginsCommand.getExternalAuth({ npmName: 'test-external-auth-one', npmVersion: '0.0.1', authName: 'external-auth-1', query: { username: 'cyan' }, - statusCodeExpected: HttpStatusCode.FOUND_302 + expectedStatus: HttpStatusCode.FOUND_302 }) const location = res.header.location @@ -275,9 +268,7 @@ describe('Test external auth plugins', function () { }) it('Should unregister external-auth-2 and do not login existing Kefka', async function () { - await updatePluginSettings({ - url: server.url, - accessToken: server.accessToken, + await server.pluginsCommand.updateSettings({ npmName: 'peertube-plugin-test-external-auth-one', settings: { disableKefka: true } }) @@ -309,11 +300,7 @@ describe('Test external auth plugins', function () { }) it('Should uninstall the plugin one and do not login Cyan', async function () { - await uninstallPlugin({ - url: server.url, - accessToken: server.accessToken, - npmName: 'peertube-plugin-test-external-auth-one' - }) + await server.pluginsCommand.uninstall({ npmName: 'peertube-plugin-test-external-auth-one' }) await loginExternal({ server, diff --git a/server/tests/plugins/filter-hooks.ts b/server/tests/plugins/filter-hooks.ts index e2ec5457b..c51e96ab7 100644 --- a/server/tests/plugins/filter-hooks.ts +++ b/server/tests/plugins/filter-hooks.ts @@ -14,7 +14,6 @@ import { getAccountVideos, getConfig, getMyVideos, - getPluginTestPath, getVideo, getVideoChannelVideos, getVideoCommentThreads, @@ -23,8 +22,8 @@ import { getVideosListPagination, getVideoThreadComments, getVideoWithToken, - installPlugin, makeRawRequest, + PluginsCommand, registerUser, ServerInfo, setAccessTokensToServers, @@ -63,17 +62,8 @@ describe('Test plugin filter hooks', function () { await setDefaultVideoChannel(servers) await doubleFollow(servers[0], servers[1]) - await installPlugin({ - url: servers[0].url, - accessToken: servers[0].accessToken, - path: getPluginTestPath() - }) - - await installPlugin({ - url: servers[0].url, - accessToken: servers[0].accessToken, - path: getPluginTestPath('-filter-translations') - }) + await servers[0].pluginsCommand.install({ path: PluginsCommand.getPluginTestPath() }) + await servers[0].pluginsCommand.install({ path: PluginsCommand.getPluginTestPath('-filter-translations') }) for (let i = 0; i < 10; i++) { await uploadVideo(servers[0].url, servers[0].accessToken, { name: 'default video ' + i }) diff --git a/server/tests/plugins/html-injection.ts b/server/tests/plugins/html-injection.ts index 4fa8caa3a..80d67ae0e 100644 --- a/server/tests/plugins/html-injection.ts +++ b/server/tests/plugins/html-injection.ts @@ -5,30 +5,31 @@ import * as chai from 'chai' import { cleanupTests, flushAndRunServer, - getPluginsCSS, - installPlugin, makeHTMLRequest, + PluginsCommand, ServerInfo, - setAccessTokensToServers, - uninstallPlugin + setAccessTokensToServers } from '../../../shared/extra-utils' const expect = chai.expect describe('Test plugins HTML injection', function () { let server: ServerInfo = null + let command: PluginsCommand before(async function () { this.timeout(30000) server = await flushAndRunServer(1) await setAccessTokensToServers([ server ]) + + command = server.pluginsCommand }) it('Should not inject global css file in HTML', async function () { { - const res = await getPluginsCSS(server.url) - expect(res.text).to.be.empty + const text = await command.getCSS() + expect(text).to.be.empty } for (const path of [ '/', '/videos/embed/1', '/video-playlists/embed/1' ]) { @@ -40,17 +41,13 @@ describe('Test plugins HTML injection', function () { it('Should install a plugin and a theme', async function () { this.timeout(30000) - await installPlugin({ - url: server.url, - accessToken: server.accessToken, - npmName: 'peertube-plugin-hello-world' - }) + await command.install({ npmName: 'peertube-plugin-hello-world' }) }) it('Should have the correct global css', async function () { { - const res = await getPluginsCSS(server.url) - expect(res.text).to.contain('background-color: red') + const text = await command.getCSS() + expect(text).to.contain('background-color: red') } for (const path of [ '/', '/videos/embed/1', '/video-playlists/embed/1' ]) { @@ -60,15 +57,11 @@ describe('Test plugins HTML injection', function () { }) it('Should have an empty global css on uninstall', async function () { - await uninstallPlugin({ - url: server.url, - accessToken: server.accessToken, - npmName: 'peertube-plugin-hello-world' - }) + await command.uninstall({ npmName: 'peertube-plugin-hello-world' }) { - const res = await getPluginsCSS(server.url) - expect(res.text).to.be.empty + const text = await command.getCSS() + expect(text).to.be.empty } for (const path of [ '/', '/videos/embed/1', '/video-playlists/embed/1' ]) { diff --git a/server/tests/plugins/id-and-pass-auth.ts b/server/tests/plugins/id-and-pass-auth.ts index cbba638c2..545968040 100644 --- a/server/tests/plugins/id-and-pass-auth.ts +++ b/server/tests/plugins/id-and-pass-auth.ts @@ -1,21 +1,25 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ import 'mocha' -import { cleanupTests, flushAndRunServer, ServerInfo, waitUntilLog } from '../../../shared/extra-utils/server/servers' +import { expect } from 'chai' import { + cleanupTests, + flushAndRunServer, + getConfig, getMyUserInformation, - getPluginTestPath, - installPlugin, + getUsersList, + login, logout, + PluginsCommand, + refreshToken, + ServerInfo, setAccessTokensToServers, - uninstallPlugin, updateMyUser, userLogin, wait, - login, refreshToken, getConfig, updatePluginSettings, getUsersList -} from '../../../shared/extra-utils' -import { User, UserRole, ServerConfig } from '@shared/models' -import { expect } from 'chai' + waitUntilLog +} from '@shared/extra-utils' +import { ServerConfig, User, UserRole } from '@shared/models' describe('Test id and pass auth plugins', function () { let server: ServerInfo @@ -33,11 +37,7 @@ describe('Test id and pass auth plugins', function () { await setAccessTokensToServers([ server ]) for (const suffix of [ 'one', 'two', 'three' ]) { - await installPlugin({ - url: server.url, - accessToken: server.accessToken, - path: getPluginTestPath('-id-pass-auth-' + suffix) - }) + await server.pluginsCommand.install({ path: PluginsCommand.getPluginTestPath('-id-pass-auth-' + suffix) }) } }) @@ -180,9 +180,7 @@ describe('Test id and pass auth plugins', function () { }) it('Should unregister spyro-auth and do not login existing Spyro', async function () { - await updatePluginSettings({ - url: server.url, - accessToken: server.accessToken, + await server.pluginsCommand.updateSettings({ npmName: 'peertube-plugin-test-id-pass-auth-one', settings: { disableSpyro: true } }) @@ -204,11 +202,7 @@ describe('Test id and pass auth plugins', function () { }) it('Should uninstall the plugin one and do not login existing Crash', async function () { - await uninstallPlugin({ - url: server.url, - accessToken: server.accessToken, - npmName: 'peertube-plugin-test-id-pass-auth-one' - }) + await server.pluginsCommand.uninstall({ npmName: 'peertube-plugin-test-id-pass-auth-one' }) await userLogin(server, { username: 'crash', password: 'crash password' }, 400) }) diff --git a/server/tests/plugins/plugin-helpers.ts b/server/tests/plugins/plugin-helpers.ts index 0296d6eb7..0e0f61638 100644 --- a/server/tests/plugins/plugin-helpers.ts +++ b/server/tests/plugins/plugin-helpers.ts @@ -1,23 +1,25 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ import 'mocha' +import { expect } from 'chai' +import { HttpStatusCode } from '@shared/core-utils' import { checkVideoFilesWereRemoved, + cleanupTests, doubleFollow, - getPluginTestPath, + flushAndRunMultipleServers, getVideo, - installPlugin, + getVideosList, + makeGetRequest, makePostBodyRequest, + PluginsCommand, + ServerInfo, setAccessTokensToServers, uploadVideoAndGetId, viewVideo, - getVideosList, waitJobs, - makeGetRequest -} from '../../../shared/extra-utils' -import { cleanupTests, flushAndRunMultipleServers, ServerInfo, waitUntilLog } from '../../../shared/extra-utils/server/servers' -import { expect } from 'chai' -import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' + waitUntilLog +} from '@shared/extra-utils' function postCommand (server: ServerInfo, command: string, bodyArg?: object) { const body = { command } @@ -42,11 +44,7 @@ describe('Test plugin helpers', function () { await doubleFollow(servers[0], servers[1]) - await installPlugin({ - url: servers[0].url, - accessToken: servers[0].accessToken, - path: getPluginTestPath('-four') - }) + await servers[0].pluginsCommand.install({ path: PluginsCommand.getPluginTestPath('-four') }) }) describe('Logger', function () { diff --git a/server/tests/plugins/plugin-router.ts b/server/tests/plugins/plugin-router.ts index 24e6a1e83..81e18dabd 100644 --- a/server/tests/plugins/plugin-router.ts +++ b/server/tests/plugins/plugin-router.ts @@ -1,16 +1,17 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ import 'mocha' -import { cleanupTests, flushAndRunServer, ServerInfo } from '../../../shared/extra-utils/server/servers' +import { expect } from 'chai' +import { HttpStatusCode } from '@shared/core-utils' import { - getPluginTestPath, - installPlugin, + cleanupTests, + flushAndRunServer, makeGetRequest, makePostBodyRequest, - setAccessTokensToServers, uninstallPlugin -} from '../../../shared/extra-utils' -import { expect } from 'chai' -import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' + PluginsCommand, + ServerInfo, + setAccessTokensToServers +} from '@shared/extra-utils' describe('Test plugin helpers', function () { let server: ServerInfo @@ -25,11 +26,7 @@ describe('Test plugin helpers', function () { server = await flushAndRunServer(1) await setAccessTokensToServers([ server ]) - await installPlugin({ - url: server.url, - accessToken: server.accessToken, - path: getPluginTestPath('-five') - }) + await server.pluginsCommand.install({ path: PluginsCommand.getPluginTestPath('-five') }) }) it('Should answer "pong"', async function () { @@ -85,11 +82,7 @@ describe('Test plugin helpers', function () { }) it('Should remove the plugin and remove the routes', async function () { - await uninstallPlugin({ - url: server.url, - accessToken: server.accessToken, - npmName: 'peertube-plugin-test-five' - }) + await server.pluginsCommand.uninstall({ npmName: 'peertube-plugin-test-five' }) for (const path of basePaths) { await makeGetRequest({ diff --git a/server/tests/plugins/plugin-storage.ts b/server/tests/plugins/plugin-storage.ts index 3c46b2585..4c65463f2 100644 --- a/server/tests/plugins/plugin-storage.ts +++ b/server/tests/plugins/plugin-storage.ts @@ -7,13 +7,14 @@ import { join } from 'path' import { HttpStatusCode } from '@shared/core-utils' import { buildServerDirectory, - getPluginTestPath, - installPlugin, + cleanupTests, + flushAndRunServer, makeGetRequest, + PluginsCommand, + ServerInfo, setAccessTokensToServers, - uninstallPlugin -} from '../../../shared/extra-utils' -import { cleanupTests, flushAndRunServer, ServerInfo, waitUntilLog } from '../../../shared/extra-utils/server/servers' + waitUntilLog +} from '@shared/extra-utils' describe('Test plugin storage', function () { let server: ServerInfo @@ -24,11 +25,7 @@ describe('Test plugin storage', function () { server = await flushAndRunServer(1) await setAccessTokensToServers([ server ]) - await installPlugin({ - url: server.url, - accessToken: server.accessToken, - path: getPluginTestPath('-six') - }) + await server.pluginsCommand.install({ path: PluginsCommand.getPluginTestPath('-six') }) }) describe('DB storage', function () { @@ -76,22 +73,14 @@ describe('Test plugin storage', function () { }) it('Should still have the file after an uninstallation', async function () { - await uninstallPlugin({ - url: server.url, - accessToken: server.accessToken, - npmName: 'peertube-plugin-test-six' - }) + await server.pluginsCommand.uninstall({ npmName: 'peertube-plugin-test-six' }) const content = await getFileContent() expect(content).to.equal('Prince Ali') }) it('Should still have the file after the reinstallation', async function () { - await installPlugin({ - url: server.url, - accessToken: server.accessToken, - path: getPluginTestPath('-six') - }) + await server.pluginsCommand.install({ path: PluginsCommand.getPluginTestPath('-six') }) const content = await getFileContent() expect(content).to.equal('Prince Ali') diff --git a/server/tests/plugins/plugin-transcoding.ts b/server/tests/plugins/plugin-transcoding.ts index eefb2294d..f1ff91077 100644 --- a/server/tests/plugins/plugin-transcoding.ts +++ b/server/tests/plugins/plugin-transcoding.ts @@ -4,25 +4,25 @@ import 'mocha' import { expect } from 'chai' import { join } from 'path' import { getAudioStream, getVideoFileFPS, getVideoStreamFromFile } from '@server/helpers/ffprobe-utils' -import { ServerConfig, VideoDetails, VideoPrivacy } from '@shared/models' import { buildServerDirectory, + cleanupTests, createLive, + flushAndRunServer, getConfig, - getPluginTestPath, getVideo, - installPlugin, + PluginsCommand, sendRTMPStreamInVideo, + ServerInfo, setAccessTokensToServers, setDefaultVideoChannel, testFfmpegStreamError, - uninstallPlugin, updateCustomSubConfig, uploadVideoAndGetId, waitJobs, waitUntilLivePublished -} from '../../../shared/extra-utils' -import { cleanupTests, flushAndRunServer, ServerInfo } from '../../../shared/extra-utils/server/servers' +} from '@shared/extra-utils' +import { ServerConfig, VideoDetails, VideoPrivacy } from '@shared/models' async function createLiveWrapper (server: ServerInfo) { const liveAttributes = { @@ -109,11 +109,7 @@ describe('Test transcoding plugins', function () { } before(async function () { - await installPlugin({ - url: server.url, - accessToken: server.accessToken, - path: getPluginTestPath('-transcoding-one') - }) + await server.pluginsCommand.install({ path: PluginsCommand.getPluginTestPath('-transcoding-one') }) }) it('Should have the appropriate available profiles', async function () { @@ -225,7 +221,7 @@ describe('Test transcoding plugins', function () { it('Should default to the default profile if the specified profile does not exist', async function () { this.timeout(240000) - await uninstallPlugin({ url: server.url, accessToken: server.accessToken, npmName: 'peertube-plugin-test-transcoding-one' }) + await server.pluginsCommand.uninstall({ npmName: 'peertube-plugin-test-transcoding-one' }) const res = await getConfig(server.url) const config = res.body as ServerConfig @@ -244,11 +240,7 @@ describe('Test transcoding plugins', function () { describe('When using a plugin adding new encoders', function () { before(async function () { - await installPlugin({ - url: server.url, - accessToken: server.accessToken, - path: getPluginTestPath('-transcoding-two') - }) + await server.pluginsCommand.install({ path: PluginsCommand.getPluginTestPath('-transcoding-two') }) await updateConf(server, 'test-vod-profile', 'test-live-profile') }) diff --git a/server/tests/plugins/plugin-unloading.ts b/server/tests/plugins/plugin-unloading.ts index 74ca82e2f..f430f82b8 100644 --- a/server/tests/plugins/plugin-unloading.ts +++ b/server/tests/plugins/plugin-unloading.ts @@ -1,18 +1,9 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ import 'mocha' -import { - cleanupTests, - flushAndRunServer, - getPluginTestPath, - makeGetRequest, - installPlugin, - uninstallPlugin, - ServerInfo, - setAccessTokensToServers -} from '../../../shared/extra-utils' -import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' import { expect } from 'chai' +import { HttpStatusCode } from '@shared/core-utils' +import { cleanupTests, flushAndRunServer, makeGetRequest, PluginsCommand, ServerInfo, setAccessTokensToServers } from '@shared/extra-utils' describe('Test plugins module unloading', function () { let server: ServerInfo = null @@ -25,11 +16,7 @@ describe('Test plugins module unloading', function () { server = await flushAndRunServer(1) await setAccessTokensToServers([ server ]) - await installPlugin({ - url: server.url, - accessToken: server.accessToken, - path: getPluginTestPath('-unloading') - }) + await server.pluginsCommand.install({ path: PluginsCommand.getPluginTestPath('-unloading') }) }) it('Should return a numeric value', async function () { @@ -54,11 +41,7 @@ describe('Test plugins module unloading', function () { }) it('Should uninstall the plugin and free the route', async function () { - await uninstallPlugin({ - url: server.url, - accessToken: server.accessToken, - npmName: 'peertube-plugin-test-unloading' - }) + await server.pluginsCommand.uninstall({ npmName: 'peertube-plugin-test-unloading' }) await makeGetRequest({ url: server.url, @@ -68,11 +51,8 @@ describe('Test plugins module unloading', function () { }) it('Should return a different numeric value', async function () { - await installPlugin({ - url: server.url, - accessToken: server.accessToken, - path: getPluginTestPath('-unloading') - }) + await server.pluginsCommand.install({ path: PluginsCommand.getPluginTestPath('-unloading') }) + const res = await makeGetRequest({ url: server.url, path: requestPath, diff --git a/server/tests/plugins/translations.ts b/server/tests/plugins/translations.ts index 9fd2ba1c5..0e11a0b53 100644 --- a/server/tests/plugins/translations.ts +++ b/server/tests/plugins/translations.ts @@ -1,20 +1,15 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ -import * as chai from 'chai' import 'mocha' +import * as chai from 'chai' +import { PluginsCommand, setAccessTokensToServers } from '../../../shared/extra-utils' import { cleanupTests, flushAndRunServer, ServerInfo } from '../../../shared/extra-utils/server/servers' -import { - getPluginTestPath, - getPluginTranslations, - installPlugin, - setAccessTokensToServers, - uninstallPlugin -} from '../../../shared/extra-utils' const expect = chai.expect describe('Test plugin translations', function () { let server: ServerInfo + let command: PluginsCommand before(async function () { this.timeout(30000) @@ -22,29 +17,22 @@ describe('Test plugin translations', function () { server = await flushAndRunServer(1) await setAccessTokensToServers([ server ]) - await installPlugin({ - url: server.url, - accessToken: server.accessToken, - path: getPluginTestPath() - }) + command = server.pluginsCommand - await installPlugin({ - url: server.url, - accessToken: server.accessToken, - path: getPluginTestPath('-filter-translations') - }) + await command.install({ path: PluginsCommand.getPluginTestPath() }) + await command.install({ path: PluginsCommand.getPluginTestPath('-filter-translations') }) }) it('Should not have translations for locale pt', async function () { - const res = await getPluginTranslations({ url: server.url, locale: 'pt' }) + const body = await command.getTranslations({ locale: 'pt' }) - expect(res.body).to.deep.equal({}) + expect(body).to.deep.equal({}) }) it('Should have translations for locale fr', async function () { - const res = await getPluginTranslations({ url: server.url, locale: 'fr-FR' }) + const body = await command.getTranslations({ locale: 'fr-FR' }) - expect(res.body).to.deep.equal({ + expect(body).to.deep.equal({ 'peertube-plugin-test': { Hi: 'Coucou' }, @@ -55,9 +43,9 @@ describe('Test plugin translations', function () { }) it('Should have translations of locale it', async function () { - const res = await getPluginTranslations({ url: server.url, locale: 'it-IT' }) + const body = await command.getTranslations({ locale: 'it-IT' }) - expect(res.body).to.deep.equal({ + expect(body).to.deep.equal({ 'peertube-plugin-test-filter-translations': { 'Hello world': 'Ciao, mondo!' } @@ -65,12 +53,12 @@ describe('Test plugin translations', function () { }) it('Should remove the plugin and remove the locales', async function () { - await uninstallPlugin({ url: server.url, accessToken: server.accessToken, npmName: 'peertube-plugin-test-filter-translations' }) + await command.uninstall({ npmName: 'peertube-plugin-test-filter-translations' }) { - const res = await getPluginTranslations({ url: server.url, locale: 'fr-FR' }) + const body = await command.getTranslations({ locale: 'fr-FR' }) - expect(res.body).to.deep.equal({ + expect(body).to.deep.equal({ 'peertube-plugin-test': { Hi: 'Coucou' } @@ -78,9 +66,9 @@ describe('Test plugin translations', function () { } { - const res = await getPluginTranslations({ url: server.url, locale: 'it-IT' }) + const body = await command.getTranslations({ locale: 'it-IT' }) - expect(res.body).to.deep.equal({}) + expect(body).to.deep.equal({}) } }) diff --git a/server/tests/plugins/video-constants.ts b/server/tests/plugins/video-constants.ts index eb014c596..4124e8a52 100644 --- a/server/tests/plugins/video-constants.ts +++ b/server/tests/plugins/video-constants.ts @@ -1,22 +1,24 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ -import * as chai from 'chai' import 'mocha' -import { cleanupTests, flushAndRunServer, ServerInfo } from '../../../shared/extra-utils/server/servers' +import * as chai from 'chai' +import { HttpStatusCode } from '@shared/core-utils' import { + cleanupTests, createVideoPlaylist, - getPluginTestPath, + flushAndRunServer, getVideo, getVideoCategories, getVideoLanguages, - getVideoLicences, getVideoPlaylistPrivacies, getVideoPrivacies, - installPlugin, + getVideoLicences, + getVideoPlaylistPrivacies, + getVideoPrivacies, + PluginsCommand, + ServerInfo, setAccessTokensToServers, - uninstallPlugin, uploadVideo -} from '../../../shared/extra-utils' -import { VideoDetails, VideoPlaylistPrivacy } from '../../../shared/models/videos' -import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' +} from '@shared/extra-utils' +import { VideoDetails, VideoPlaylistPrivacy } from '@shared/models' const expect = chai.expect @@ -29,11 +31,7 @@ describe('Test plugin altering video constants', function () { server = await flushAndRunServer(1) await setAccessTokensToServers([ server ]) - await installPlugin({ - url: server.url, - accessToken: server.accessToken, - path: getPluginTestPath('-video-constants') - }) + await server.pluginsCommand.install({ path: PluginsCommand.getPluginTestPath('-video-constants') }) }) it('Should have updated languages', async function () { @@ -117,7 +115,7 @@ describe('Test plugin altering video constants', function () { }) it('Should uninstall the plugin and reset languages, categories, licences and privacies', async function () { - await uninstallPlugin({ url: server.url, accessToken: server.accessToken, npmName: 'peertube-plugin-test-video-constants' }) + await server.pluginsCommand.uninstall({ npmName: 'peertube-plugin-test-video-constants' }) { const res = await getVideoLanguages(server.url) diff --git a/shared/extra-utils/index.ts b/shared/extra-utils/index.ts index 652779eea..cf6418249 100644 --- a/shared/extra-utils/index.ts +++ b/shared/extra-utils/index.ts @@ -15,7 +15,6 @@ export * from './requests/requests' export * from './server/clients' export * from './server/config' -export * from './server/plugins' export * from './server/servers' export * from './users/accounts' diff --git a/shared/extra-utils/server/index.ts b/shared/extra-utils/server/index.ts index b5b6b2116..e602fec7e 100644 --- a/shared/extra-utils/server/index.ts +++ b/shared/extra-utils/server/index.ts @@ -4,3 +4,5 @@ export * from './follows-command' export * from './follows' export * from './jobs' export * from './jobs-command' +export * from './plugins-command' +export * from './plugins' diff --git a/shared/extra-utils/server/plugins-command.ts b/shared/extra-utils/server/plugins-command.ts new file mode 100644 index 000000000..f06e58a22 --- /dev/null +++ b/shared/extra-utils/server/plugins-command.ts @@ -0,0 +1,245 @@ +/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ + +import { readJSON, writeJSON } from 'fs-extra' +import { join } from 'path' +import { root } from '@server/helpers/core-utils' +import { HttpStatusCode } from '@shared/core-utils' +import { + PeerTubePlugin, + PeerTubePluginIndex, + PeertubePluginIndexList, + PluginPackageJson, + PluginTranslation, + PluginType, + PublicServerSetting, + RegisteredServerSettings, + ResultList +} from '@shared/models' +import { buildServerDirectory } from '../miscs' +import { AbstractCommand, OverrideCommandOptions } from '../shared' + +export class PluginsCommand extends AbstractCommand { + + static getPluginTestPath (suffix = '') { + return join(root(), 'server', 'tests', 'fixtures', 'peertube-plugin-test' + suffix) + } + + list (options: OverrideCommandOptions & { + start?: number + count?: number + sort?: string + pluginType?: PluginType + uninstalled?: boolean + }) { + const { start, count, sort, pluginType, uninstalled } = options + const path = '/api/v1/plugins' + + return this.getRequestBody>({ + ...options, + + path, + query: { + start, + count, + sort, + pluginType, + uninstalled + }, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } + + listAvailable (options: OverrideCommandOptions & { + start?: number + count?: number + sort?: string + pluginType?: PluginType + currentPeerTubeEngine?: string + search?: string + expectedStatus?: HttpStatusCode + }) { + const { start, count, sort, pluginType, search, currentPeerTubeEngine } = options + const path = '/api/v1/plugins/available' + + const query: PeertubePluginIndexList = { + start, + count, + sort, + pluginType, + currentPeerTubeEngine, + search + } + + return this.getRequestBody>({ + ...options, + + path, + query, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } + + get (options: OverrideCommandOptions & { + npmName: string + }) { + const path = '/api/v1/plugins/' + options.npmName + + return this.getRequestBody({ + ...options, + + path, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } + + updateSettings (options: OverrideCommandOptions & { + npmName: string + settings: any + }) { + const { npmName, settings } = options + const path = '/api/v1/plugins/' + npmName + '/settings' + + return this.putBodyRequest({ + ...options, + + path, + fields: { settings }, + defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 + }) + } + + getRegisteredSettings (options: OverrideCommandOptions & { + npmName: string + }) { + const path = '/api/v1/plugins/' + options.npmName + '/registered-settings' + + return this.getRequestBody({ + ...options, + + path, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } + + getPublicSettings (options: OverrideCommandOptions & { + npmName: string + }) { + const { npmName } = options + const path = '/api/v1/plugins/' + npmName + '/public-settings' + + return this.getRequestBody({ + ...options, + + path, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } + + getTranslations (options: OverrideCommandOptions & { + locale: string + }) { + const { locale } = options + const path = '/plugins/translations/' + locale + '.json' + + return this.getRequestBody({ + ...options, + + path, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } + + install (options: OverrideCommandOptions & { + path?: string + npmName?: string + }) { + const { npmName, path } = options + const apiPath = '/api/v1/plugins/install' + + return this.postBodyRequest({ + ...options, + + path: apiPath, + fields: { npmName, path }, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } + + update (options: OverrideCommandOptions & { + path?: string + npmName?: string + }) { + const { npmName, path } = options + const apiPath = '/api/v1/plugins/update' + + return this.postBodyRequest({ + ...options, + + path: apiPath, + fields: { npmName, path }, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } + + uninstall (options: OverrideCommandOptions & { + npmName: string + }) { + const { npmName } = options + const apiPath = '/api/v1/plugins/uninstall' + + return this.postBodyRequest({ + ...options, + + path: apiPath, + fields: { npmName }, + defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 + }) + } + + getCSS (options: OverrideCommandOptions = {}) { + const path = '/plugins/global.css' + + return this.getRequestText({ + ...options, + + path, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } + + getExternalAuth (options: OverrideCommandOptions & { + npmName: string + npmVersion: string + authName: string + query?: any + }) { + const { npmName, npmVersion, authName, query } = options + + const path = '/plugins/' + npmName + '/' + npmVersion + '/auth/' + authName + + return this.getRequest({ + ...options, + + path, + query, + defaultExpectedStatus: HttpStatusCode.OK_200, + redirects: 0 + }) + } + + updatePackageJSON (npmName: string, json: any) { + const path = this.getPackageJSONPath(npmName) + + return writeJSON(path, json) + } + + getPackageJSON (npmName: string): Promise { + const path = this.getPackageJSONPath(npmName) + + return readJSON(path) + } + + private getPackageJSONPath (npmName: string) { + return buildServerDirectory(this.server, join('plugins', 'node_modules', npmName, 'package.json')) + } +} diff --git a/shared/extra-utils/server/plugins.ts b/shared/extra-utils/server/plugins.ts index d53e5b382..1084ea4f4 100644 --- a/shared/extra-utils/server/plugins.ts +++ b/shared/extra-utils/server/plugins.ts @@ -1,307 +1,18 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ import { expect } from 'chai' -import { readJSON, writeJSON } from 'fs-extra' -import { join } from 'path' -import { RegisteredServerSettings } from '@shared/models' -import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' -import { PeertubePluginIndexList } from '../../models/plugins/plugin-index/peertube-plugin-index-list.model' -import { PluginType } from '../../models/plugins/plugin.type' -import { buildServerDirectory, root } from '../miscs/miscs' -import { makeGetRequest, makePostBodyRequest, makePutBodyRequest } from '../requests/requests' -import { ServerInfo } from './servers' - -function listPlugins (parameters: { - url: string - accessToken: string - start?: number - count?: number - sort?: string - pluginType?: PluginType - uninstalled?: boolean - expectedStatus?: HttpStatusCode -}) { - const { url, accessToken, start, count, sort, pluginType, uninstalled, expectedStatus = HttpStatusCode.OK_200 } = parameters - const path = '/api/v1/plugins' - - return makeGetRequest({ - url, - path, - token: accessToken, - query: { - start, - count, - sort, - pluginType, - uninstalled - }, - statusCodeExpected: expectedStatus - }) -} - -function listAvailablePlugins (parameters: { - url: string - accessToken: string - start?: number - count?: number - sort?: string - pluginType?: PluginType - currentPeerTubeEngine?: string - search?: string - expectedStatus?: HttpStatusCode -}) { - const { - url, - accessToken, - start, - count, - sort, - pluginType, - search, - currentPeerTubeEngine, - expectedStatus = HttpStatusCode.OK_200 - } = parameters - const path = '/api/v1/plugins/available' - - const query: PeertubePluginIndexList = { - start, - count, - sort, - pluginType, - currentPeerTubeEngine, - search - } - - return makeGetRequest({ - url, - path, - token: accessToken, - query, - statusCodeExpected: expectedStatus - }) -} - -function getPlugin (parameters: { - url: string - accessToken: string - npmName: string - expectedStatus?: HttpStatusCode -}) { - const { url, accessToken, npmName, expectedStatus = HttpStatusCode.OK_200 } = parameters - const path = '/api/v1/plugins/' + npmName - - return makeGetRequest({ - url, - path, - token: accessToken, - statusCodeExpected: expectedStatus - }) -} - -function updatePluginSettings (parameters: { - url: string - accessToken: string - npmName: string - settings: any - expectedStatus?: HttpStatusCode -}) { - const { url, accessToken, npmName, settings, expectedStatus = HttpStatusCode.NO_CONTENT_204 } = parameters - const path = '/api/v1/plugins/' + npmName + '/settings' - - return makePutBodyRequest({ - url, - path, - token: accessToken, - fields: { settings }, - statusCodeExpected: expectedStatus - }) -} - -function getPluginRegisteredSettings (parameters: { - url: string - accessToken: string - npmName: string - expectedStatus?: HttpStatusCode -}) { - const { url, accessToken, npmName, expectedStatus = HttpStatusCode.OK_200 } = parameters - const path = '/api/v1/plugins/' + npmName + '/registered-settings' - - return makeGetRequest({ - url, - path, - token: accessToken, - statusCodeExpected: expectedStatus - }) -} +import { ServerInfo } from '../server/servers' async function testHelloWorldRegisteredSettings (server: ServerInfo) { - const res = await getPluginRegisteredSettings({ - url: server.url, - accessToken: server.accessToken, - npmName: 'peertube-plugin-hello-world' - }) - - const registeredSettings = (res.body as RegisteredServerSettings).registeredSettings + const body = await server.pluginsCommand.getRegisteredSettings({ npmName: 'peertube-plugin-hello-world' }) + const registeredSettings = body.registeredSettings expect(registeredSettings).to.have.length.at.least(1) const adminNameSettings = registeredSettings.find(s => s.name === 'admin-name') expect(adminNameSettings).to.not.be.undefined } -function getPublicSettings (parameters: { - url: string - npmName: string - expectedStatus?: HttpStatusCode -}) { - const { url, npmName, expectedStatus = HttpStatusCode.OK_200 } = parameters - const path = '/api/v1/plugins/' + npmName + '/public-settings' - - return makeGetRequest({ - url, - path, - statusCodeExpected: expectedStatus - }) -} - -function getPluginTranslations (parameters: { - url: string - locale: string - expectedStatus?: HttpStatusCode -}) { - const { url, locale, expectedStatus = HttpStatusCode.OK_200 } = parameters - const path = '/plugins/translations/' + locale + '.json' - - return makeGetRequest({ - url, - path, - statusCodeExpected: expectedStatus - }) -} - -function installPlugin (parameters: { - url: string - accessToken: string - path?: string - npmName?: string - expectedStatus?: HttpStatusCode -}) { - const { url, accessToken, npmName, path, expectedStatus = HttpStatusCode.OK_200 } = parameters - const apiPath = '/api/v1/plugins/install' - - return makePostBodyRequest({ - url, - path: apiPath, - token: accessToken, - fields: { npmName, path }, - statusCodeExpected: expectedStatus - }) -} - -function updatePlugin (parameters: { - url: string - accessToken: string - path?: string - npmName?: string - expectedStatus?: HttpStatusCode -}) { - const { url, accessToken, npmName, path, expectedStatus = HttpStatusCode.OK_200 } = parameters - const apiPath = '/api/v1/plugins/update' - - return makePostBodyRequest({ - url, - path: apiPath, - token: accessToken, - fields: { npmName, path }, - statusCodeExpected: expectedStatus - }) -} - -function uninstallPlugin (parameters: { - url: string - accessToken: string - npmName: string - expectedStatus?: HttpStatusCode -}) { - const { url, accessToken, npmName, expectedStatus = HttpStatusCode.NO_CONTENT_204 } = parameters - const apiPath = '/api/v1/plugins/uninstall' - - return makePostBodyRequest({ - url, - path: apiPath, - token: accessToken, - fields: { npmName }, - statusCodeExpected: expectedStatus - }) -} - -function getPluginsCSS (url: string) { - const path = '/plugins/global.css' - - return makeGetRequest({ - url, - path, - statusCodeExpected: HttpStatusCode.OK_200 - }) -} - -function getPackageJSONPath (server: ServerInfo, npmName: string) { - return buildServerDirectory(server, join('plugins', 'node_modules', npmName, 'package.json')) -} - -function updatePluginPackageJSON (server: ServerInfo, npmName: string, json: any) { - const path = getPackageJSONPath(server, npmName) - - return writeJSON(path, json) -} - -function getPluginPackageJSON (server: ServerInfo, npmName: string) { - const path = getPackageJSONPath(server, npmName) - - return readJSON(path) -} - -function getPluginTestPath (suffix = '') { - return join(root(), 'server', 'tests', 'fixtures', 'peertube-plugin-test' + suffix) -} - -function getExternalAuth (options: { - url: string - npmName: string - npmVersion: string - authName: string - query?: any - statusCodeExpected?: HttpStatusCode -}) { - const { url, npmName, npmVersion, authName, statusCodeExpected, query } = options - - const path = '/plugins/' + npmName + '/' + npmVersion + '/auth/' + authName - - return makeGetRequest({ - url, - path, - query, - statusCodeExpected: statusCodeExpected || HttpStatusCode.OK_200, - redirects: 0 - }) -} - export { - listPlugins, - listAvailablePlugins, - installPlugin, - getPluginTranslations, - getPluginsCSS, - updatePlugin, - getPlugin, - uninstallPlugin, - testHelloWorldRegisteredSettings, - updatePluginSettings, - getPluginRegisteredSettings, - getPackageJSONPath, - updatePluginPackageJSON, - getPluginPackageJSON, - getPluginTestPath, - getPublicSettings, - getExternalAuth + testHelloWorldRegisteredSettings } diff --git a/shared/extra-utils/server/servers.ts b/shared/extra-utils/server/servers.ts index 5511ce0b0..79d6b7b1a 100644 --- a/shared/extra-utils/server/servers.ts +++ b/shared/extra-utils/server/servers.ts @@ -20,6 +20,7 @@ import { ContactFormCommand } from './contact-form-command' import { DebugCommand } from './debug-command' import { FollowsCommand } from './follows-command' import { JobsCommand } from './jobs-command' +import { PluginsCommand } from './plugins-command' interface ServerInfo { app: ChildProcess @@ -85,6 +86,7 @@ interface ServerInfo { debugCommand?: DebugCommand followsCommand?: FollowsCommand jobsCommand?: JobsCommand + pluginsCommand?: PluginsCommand } function parallelTests () { @@ -302,6 +304,7 @@ async function runServer (server: ServerInfo, configOverrideArg?: any, args = [] server.debugCommand = new DebugCommand(server) server.followsCommand = new FollowsCommand(server) server.jobsCommand = new JobsCommand(server) + server.pluginsCommand = new PluginsCommand(server) res(server) }) diff --git a/shared/extra-utils/shared/abstract-command.ts b/shared/extra-utils/shared/abstract-command.ts index 3815fab0e..dd4598a91 100644 --- a/shared/extra-utils/shared/abstract-command.ts +++ b/shared/extra-utils/shared/abstract-command.ts @@ -16,6 +16,7 @@ interface GetCommandOptions extends CommonCommandOptions { query?: { [ id: string ]: any } contentType?: string accept?: string + redirects?: number } abstract class AbstractCommand { @@ -44,6 +45,19 @@ abstract class AbstractCommand { return unwrapText(this.getRequest(options)) } + protected getRequest (options: GetCommandOptions) { + const { redirects, query, contentType, accept } = options + + return makeGetRequest({ + ...this.buildCommonRequestOptions(options), + + redirects, + query, + contentType, + accept + }) + } + protected deleteRequest (options: CommonCommandOptions) { return makeDeleteRequest(this.buildCommonRequestOptions(options)) } @@ -85,18 +99,6 @@ abstract class AbstractCommand { statusCodeExpected: expectedStatus ?? this.expectedStatus ?? defaultExpectedStatus } } - - private getRequest (options: GetCommandOptions) { - const { query, contentType, accept } = options - - return makeGetRequest({ - ...this.buildCommonRequestOptions(options), - - query, - contentType, - accept - }) - } } export { -- cgit v1.2.3 From dab047092b51b453f175069573d8865fb17acdfc Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Wed, 7 Jul 2021 10:56:45 +0200 Subject: Introduce redundancy command --- server/tests/api/redundancy/manage-redundancy.ts | 165 +++++++-------------- .../tests/api/redundancy/redundancy-constraints.ts | 28 ++-- server/tests/api/redundancy/redundancy.ts | 49 +++--- shared/extra-utils/server/index.ts | 1 + shared/extra-utils/server/redundancy-command.ts | 77 ++++++++++ shared/extra-utils/server/redundancy.ts | 88 ----------- shared/extra-utils/server/servers.ts | 3 + 7 files changed, 165 insertions(+), 246 deletions(-) create mode 100644 shared/extra-utils/server/redundancy-command.ts delete mode 100644 shared/extra-utils/server/redundancy.ts diff --git a/server/tests/api/redundancy/manage-redundancy.ts b/server/tests/api/redundancy/manage-redundancy.ts index 4253124c8..363e4cbfe 100644 --- a/server/tests/api/redundancy/manage-redundancy.ts +++ b/server/tests/api/redundancy/manage-redundancy.ts @@ -1,21 +1,21 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ -import * as chai from 'chai' import 'mocha' +import * as chai from 'chai' import { cleanupTests, doubleFollow, flushAndRunMultipleServers, getLocalIdByUUID, + RedundancyCommand, ServerInfo, setAccessTokensToServers, uploadVideo, uploadVideoAndGetId, + waitJobs, waitUntilLog -} from '../../../../shared/extra-utils' -import { waitJobs } from '../../../../shared/extra-utils/server/jobs' -import { addVideoRedundancy, listVideoRedundancies, removeVideoRedundancy, updateRedundancy } from '@shared/extra-utils/server/redundancy' -import { VideoPrivacy, VideoRedundanciesTarget, VideoRedundancy } from '@shared/models' +} from '@shared/extra-utils' +import { VideoPrivacy, VideoRedundanciesTarget } from '@shared/models' const expect = chai.expect @@ -27,6 +27,8 @@ describe('Test manage videos redundancy', function () { let video2Server2UUID: string let redundanciesToRemove: number[] = [] + let commands: RedundancyCommand[] + before(async function () { this.timeout(120000) @@ -55,6 +57,8 @@ describe('Test manage videos redundancy', function () { // Get the access tokens await setAccessTokensToServers(servers) + commands = servers.map(s => s.redundancyCommand) + { const res = await uploadVideo(servers[1].url, servers[1].accessToken, { name: 'video 1 server 2' }) video1Server2UUID = res.body.video.uuid @@ -69,21 +73,17 @@ describe('Test manage videos redundancy', function () { // Server 1 and server 2 follow each other await doubleFollow(servers[0], servers[1]) - await updateRedundancy(servers[0].url, servers[0].accessToken, servers[1].host, true) + await commands[0].updateRedundancy({ host: servers[1].host, redundancyAllowed: true }) await waitJobs(servers) }) it('Should not have redundancies on server 3', async function () { for (const target of targets) { - const res = await listVideoRedundancies({ - url: servers[2].url, - accessToken: servers[2].accessToken, - target - }) + const body = await commands[2].listVideos({ target }) - expect(res.body.total).to.equal(0) - expect(res.body.data).to.have.lengthOf(0) + expect(body.total).to.equal(0) + expect(body.data).to.have.lengthOf(0) } }) @@ -94,28 +94,19 @@ describe('Test manage videos redundancy', function () { await waitUntilLog(servers[0], 'Duplicated ', 10) await waitJobs(servers) - const res = await listVideoRedundancies({ - url: servers[1].url, - accessToken: servers[1].accessToken, - target: 'remote-videos' - }) + const body = await commands[1].listVideos({ target: 'remote-videos' }) - expect(res.body.total).to.equal(0) - expect(res.body.data).to.have.lengthOf(0) + expect(body.total).to.equal(0) + expect(body.data).to.have.lengthOf(0) }) it('Should have "my-videos" redundancies on server 2', async function () { this.timeout(120000) - const res = await listVideoRedundancies({ - url: servers[1].url, - accessToken: servers[1].accessToken, - target: 'my-videos' - }) - - expect(res.body.total).to.equal(2) + const body = await commands[1].listVideos({ target: 'my-videos' }) + expect(body.total).to.equal(2) - const videos = res.body.data as VideoRedundancy[] + const videos = body.data expect(videos).to.have.lengthOf(2) const videos1 = videos.find(v => v.uuid === video1Server2UUID) @@ -139,28 +130,19 @@ describe('Test manage videos redundancy', function () { }) it('Should not have "my-videos" redundancies on server 1', async function () { - const res = await listVideoRedundancies({ - url: servers[0].url, - accessToken: servers[0].accessToken, - target: 'my-videos' - }) + const body = await commands[0].listVideos({ target: 'my-videos' }) - expect(res.body.total).to.equal(0) - expect(res.body.data).to.have.lengthOf(0) + expect(body.total).to.equal(0) + expect(body.data).to.have.lengthOf(0) }) it('Should have "remote-videos" redundancies on server 1', async function () { this.timeout(120000) - const res = await listVideoRedundancies({ - url: servers[0].url, - accessToken: servers[0].accessToken, - target: 'remote-videos' - }) + const body = await commands[0].listVideos({ target: 'remote-videos' }) + expect(body.total).to.equal(2) - expect(res.body.total).to.equal(2) - - const videos = res.body.data as VideoRedundancy[] + const videos = body.data expect(videos).to.have.lengthOf(2) const videos1 = videos.find(v => v.uuid === video1Server2UUID) @@ -185,47 +167,40 @@ describe('Test manage videos redundancy', function () { it('Should correctly paginate and sort results', async function () { { - const res = await listVideoRedundancies({ - url: servers[0].url, - accessToken: servers[0].accessToken, + const body = await commands[0].listVideos({ target: 'remote-videos', sort: 'name', start: 0, count: 2 }) - const videos = res.body.data + const videos = body.data expect(videos[0].name).to.equal('video 1 server 2') expect(videos[1].name).to.equal('video 2 server 2') } { - const res = await listVideoRedundancies({ - url: servers[0].url, - accessToken: servers[0].accessToken, + const body = await commands[0].listVideos({ target: 'remote-videos', sort: '-name', start: 0, count: 2 }) - const videos = res.body.data + const videos = body.data expect(videos[0].name).to.equal('video 2 server 2') expect(videos[1].name).to.equal('video 1 server 2') } { - const res = await listVideoRedundancies({ - url: servers[0].url, - accessToken: servers[0].accessToken, + const body = await commands[0].listVideos({ target: 'remote-videos', sort: '-name', start: 1, count: 1 }) - const videos = res.body.data - expect(videos[0].name).to.equal('video 1 server 2') + expect(body.data[0].name).to.equal('video 1 server 2') } }) @@ -236,30 +211,23 @@ describe('Test manage videos redundancy', function () { await waitJobs(servers) const videoId = await getLocalIdByUUID(servers[0].url, uuid) - await addVideoRedundancy({ - url: servers[0].url, - accessToken: servers[0].accessToken, - videoId - }) + await commands[0].addVideo({ videoId }) await waitJobs(servers) await waitUntilLog(servers[0], 'Duplicated ', 15) await waitJobs(servers) { - const res = await listVideoRedundancies({ - url: servers[0].url, - accessToken: servers[0].accessToken, + const body = await commands[0].listVideos({ target: 'remote-videos', sort: '-name', start: 0, count: 5 }) - const videos = res.body.data - expect(videos[0].name).to.equal('video 3 server 2') + const video = body.data[0] - const video = videos[0] + expect(video.name).to.equal('video 3 server 2') expect(video.redundancies.files).to.have.lengthOf(4) expect(video.redundancies.streamingPlaylists).to.have.lengthOf(1) @@ -276,19 +244,15 @@ describe('Test manage videos redundancy', function () { } } - const res = await listVideoRedundancies({ - url: servers[1].url, - accessToken: servers[1].accessToken, + const body = await commands[1].listVideos({ target: 'my-videos', sort: '-name', start: 0, count: 5 }) - const videos = res.body.data - expect(videos[0].name).to.equal('video 3 server 2') - - const video = videos[0] + const video = body.data[0] + expect(video.name).to.equal('video 3 server 2') expect(video.redundancies.files).to.have.lengthOf(4) expect(video.redundancies.streamingPlaylists).to.have.lengthOf(1) @@ -307,64 +271,47 @@ describe('Test manage videos redundancy', function () { this.timeout(120000) for (const redundancyId of redundanciesToRemove) { - await removeVideoRedundancy({ - url: servers[0].url, - accessToken: servers[0].accessToken, - redundancyId - }) + await commands[0].removeVideo({ redundancyId }) } { - const res = await listVideoRedundancies({ - url: servers[0].url, - accessToken: servers[0].accessToken, + const body = await commands[0].listVideos({ target: 'remote-videos', sort: '-name', start: 0, count: 5 }) - const videos = res.body.data - expect(videos).to.have.lengthOf(2) + const videos = body.data - expect(videos[0].name).to.equal('video 2 server 2') + expect(videos).to.have.lengthOf(2) - redundanciesToRemove = [] const video = videos[0] + expect(video.name).to.equal('video 2 server 2') expect(video.redundancies.files).to.have.lengthOf(4) expect(video.redundancies.streamingPlaylists).to.have.lengthOf(1) const redundancies = video.redundancies.files.concat(video.redundancies.streamingPlaylists) - for (const r of redundancies) { - redundanciesToRemove.push(r.id) - } + redundanciesToRemove = redundancies.map(r => r.id) } }) it('Should remove another (auto) redundancy', async function () { - { - for (const redundancyId of redundanciesToRemove) { - await removeVideoRedundancy({ - url: servers[0].url, - accessToken: servers[0].accessToken, - redundancyId - }) - } + for (const redundancyId of redundanciesToRemove) { + await commands[0].removeVideo({ redundancyId }) + } - const res = await listVideoRedundancies({ - url: servers[0].url, - accessToken: servers[0].accessToken, - target: 'remote-videos', - sort: '-name', - start: 0, - count: 5 - }) + const body = await commands[0].listVideos({ + target: 'remote-videos', + sort: '-name', + start: 0, + count: 5 + }) - const videos = res.body.data - expect(videos[0].name).to.equal('video 1 server 2') - expect(videos).to.have.lengthOf(1) - } + const videos = body.data + expect(videos).to.have.lengthOf(1) + expect(videos[0].name).to.equal('video 1 server 2') }) after(async function () { diff --git a/server/tests/api/redundancy/redundancy-constraints.ts b/server/tests/api/redundancy/redundancy-constraints.ts index 602f4bc1b..a666976b3 100644 --- a/server/tests/api/redundancy/redundancy-constraints.ts +++ b/server/tests/api/redundancy/redundancy-constraints.ts @@ -1,9 +1,6 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ import 'mocha' -import * as chai from 'chai' -import { listVideoRedundancies, updateRedundancy } from '@shared/extra-utils/server/redundancy' -import { VideoPrivacy } from '@shared/models' import { cleanupTests, flushAndRunServer, @@ -13,9 +10,10 @@ import { setAccessTokensToServers, updateVideo, uploadVideo, + waitJobs, waitUntilLog -} from '../../../../shared/extra-utils' -import { waitJobs } from '../../../../shared/extra-utils/server/jobs' +} from '@shared/extra-utils' +import { VideoPrivacy } from '@shared/models' const expect = chai.expect @@ -50,23 +48,15 @@ describe('Test redundancy constraints', function () { } async function getTotalRedundanciesLocalServer () { - const res = await listVideoRedundancies({ - url: localServer.url, - accessToken: localServer.accessToken, - target: 'my-videos' - }) + const body = await localServer.redundancyCommand.listVideos({ target: 'my-videos' }) - return res.body.total + return body.total } async function getTotalRedundanciesRemoteServer () { - const res = await listVideoRedundancies({ - url: remoteServer.url, - accessToken: remoteServer.accessToken, - target: 'remote-videos' - }) + const body = await remoteServer.redundancyCommand.listVideos({ target: 'remote-videos' }) - return res.body.total + return body.total } before(async function () { @@ -99,7 +89,7 @@ describe('Test redundancy constraints', function () { // Server 1 and server 2 follow each other await remoteServer.followsCommand.follow({ targets: [ localServer.url ] }) await waitJobs(servers) - await updateRedundancy(remoteServer.url, remoteServer.accessToken, localServer.host, true) + await remoteServer.redundancyCommand.updateRedundancy({ host: localServer.host, redundancyAllowed: true }) await waitJobs(servers) }) @@ -161,7 +151,7 @@ describe('Test redundancy constraints', function () { } } } - await killallServers([ localServer ]) + killallServers([ localServer ]) await reRunServer(localServer, config) await uploadWrapper('video 3 server 2') diff --git a/server/tests/api/redundancy/redundancy.ts b/server/tests/api/redundancy/redundancy.ts index dfe8099ed..5b970473c 100644 --- a/server/tests/api/redundancy/redundancy.ts +++ b/server/tests/api/redundancy/redundancy.ts @@ -5,7 +5,8 @@ import * as chai from 'chai' import { readdir } from 'fs-extra' import * as magnetUtil from 'magnet-uri' import { join } from 'path' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' +import { removeVideoRedundancy } from '@server/lib/redundancy' +import { HttpStatusCode } from '@shared/core-utils' import { checkSegmentHash, checkVideoFilesWereRemoved, @@ -26,19 +27,18 @@ import { uploadVideo, viewVideo, wait, + waitJobs, waitUntilLog -} from '../../../../shared/extra-utils' -import { waitJobs } from '../../../../shared/extra-utils/server/jobs' +} from '@shared/extra-utils' +import { getStats } from '@shared/extra-utils/server/stats' import { - addVideoRedundancy, - listVideoRedundancies, - removeVideoRedundancy, - updateRedundancy -} from '../../../../shared/extra-utils/server/redundancy' -import { getStats } from '../../../../shared/extra-utils/server/stats' -import { VideoRedundancy, VideoRedundancyStrategy, VideoRedundancyStrategyWithManual } from '../../../../shared/models/redundancy' -import { ServerStats } from '../../../../shared/models/server/server-stats.model' -import { VideoDetails, VideoPrivacy } from '../../../../shared/models/videos' + ServerStats, + VideoDetails, + VideoPrivacy, + VideoRedundancy, + VideoRedundancyStrategy, + VideoRedundancyStrategyWithManual +} from '@shared/models' const expect = chai.expect @@ -279,7 +279,7 @@ async function findServerFollows () { } async function enableRedundancyOnServer1 () { - await updateRedundancy(servers[0].url, servers[0].accessToken, servers[1].host, true) + await servers[0].redundancyCommand.updateRedundancy({ host: servers[1].host, redundancyAllowed: true }) const { server2, server3 } = await findServerFollows() @@ -291,7 +291,7 @@ async function enableRedundancyOnServer1 () { } async function disableRedundancyOnServer1 () { - await updateRedundancy(servers[0].url, servers[0].accessToken, servers[1].host, false) + await servers[0].redundancyCommand.updateRedundancy({ host: servers[1].host, redundancyAllowed: false }) const { server2, server3 } = await findServerFollows() @@ -551,11 +551,7 @@ describe('Test videos redundancy', function () { }) it('Should create a redundancy on first video', async function () { - await addVideoRedundancy({ - url: servers[0].url, - accessToken: servers[0].accessToken, - videoId: video1Server2Id - }) + await servers[0].redundancyCommand.addVideo({ videoId: video1Server2Id }) }) it('Should have 2 webseeds on the first video', async function () { @@ -573,22 +569,15 @@ describe('Test videos redundancy', function () { it('Should manually remove redundancies on server 1 and remove duplicated videos', async function () { this.timeout(80000) - const res = await listVideoRedundancies({ - url: servers[0].url, - accessToken: servers[0].accessToken, - target: 'remote-videos' - }) + const body = await servers[0].redundancyCommand.listVideos({ target: 'remote-videos' }) - const videos = res.body.data as VideoRedundancy[] + const videos = body.data expect(videos).to.have.lengthOf(1) const video = videos[0] + for (const r of video.redundancies.files.concat(video.redundancies.streamingPlaylists)) { - await removeVideoRedundancy({ - url: servers[0].url, - accessToken: servers[0].accessToken, - redundancyId: r.id - }) + await servers[0].redundancyCommand.removeVideo({ redundancyId: r.id }) } await waitJobs(servers) diff --git a/shared/extra-utils/server/index.ts b/shared/extra-utils/server/index.ts index e602fec7e..3ee70f0cf 100644 --- a/shared/extra-utils/server/index.ts +++ b/shared/extra-utils/server/index.ts @@ -6,3 +6,4 @@ export * from './jobs' export * from './jobs-command' export * from './plugins-command' export * from './plugins' +export * from './redundancy-command' diff --git a/shared/extra-utils/server/redundancy-command.ts b/shared/extra-utils/server/redundancy-command.ts new file mode 100644 index 000000000..d717d35f8 --- /dev/null +++ b/shared/extra-utils/server/redundancy-command.ts @@ -0,0 +1,77 @@ +import { ResultList, VideoRedundanciesTarget, VideoRedundancy } from '@shared/models' +import { HttpStatusCode } from '../../core-utils/miscs/http-error-codes' +import { AbstractCommand, OverrideCommandOptions } from '../shared' + +export class RedundancyCommand extends AbstractCommand { + + updateRedundancy (options: OverrideCommandOptions & { + host: string + redundancyAllowed: boolean + }) { + const { host, redundancyAllowed } = options + const path = '/api/v1/server/redundancy/' + host + + return this.putBodyRequest({ + ...options, + + path, + fields: { redundancyAllowed }, + defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 + }) + } + + listVideos (options: OverrideCommandOptions & { + target: VideoRedundanciesTarget + start?: number + count?: number + sort?: string + }) { + const path = '/api/v1/server/redundancy/videos' + + const { target, start, count, sort } = options + + return this.getRequestBody>({ + ...options, + + path, + + query: { + start: start ?? 0, + count: count ?? 5, + sort: sort ?? 'name', + target + }, + + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } + + addVideo (options: OverrideCommandOptions & { + videoId: number + }) { + const path = '/api/v1/server/redundancy/videos' + const { videoId } = options + + return this.postBodyRequest({ + ...options, + + path, + fields: { videoId }, + defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 + }) + } + + removeVideo (options: OverrideCommandOptions & { + redundancyId: number + }) { + const { redundancyId } = options + const path = '/api/v1/server/redundancy/videos/' + redundancyId + + return this.deleteRequest({ + ...options, + + path, + defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 + }) + } +} diff --git a/shared/extra-utils/server/redundancy.ts b/shared/extra-utils/server/redundancy.ts deleted file mode 100644 index b83815a37..000000000 --- a/shared/extra-utils/server/redundancy.ts +++ /dev/null @@ -1,88 +0,0 @@ -import { makeDeleteRequest, makeGetRequest, makePostBodyRequest, makePutBodyRequest } from '../requests/requests' -import { VideoRedundanciesTarget } from '@shared/models' -import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' - -function updateRedundancy ( - url: string, - accessToken: string, - host: string, - redundancyAllowed: boolean, - expectedStatus = HttpStatusCode.NO_CONTENT_204 -) { - const path = '/api/v1/server/redundancy/' + host - - return makePutBodyRequest({ - url, - path, - token: accessToken, - fields: { redundancyAllowed }, - statusCodeExpected: expectedStatus - }) -} - -function listVideoRedundancies (options: { - url: string - accessToken: string - target: VideoRedundanciesTarget - start?: number - count?: number - sort?: string - statusCodeExpected?: HttpStatusCode -}) { - const path = '/api/v1/server/redundancy/videos' - - const { url, accessToken, target, statusCodeExpected, start, count, sort } = options - - return makeGetRequest({ - url, - token: accessToken, - path, - query: { - start: start ?? 0, - count: count ?? 5, - sort: sort ?? 'name', - target - }, - statusCodeExpected: statusCodeExpected || HttpStatusCode.OK_200 - }) -} - -function addVideoRedundancy (options: { - url: string - accessToken: string - videoId: number -}) { - const path = '/api/v1/server/redundancy/videos' - const { url, accessToken, videoId } = options - - return makePostBodyRequest({ - url, - token: accessToken, - path, - fields: { videoId }, - statusCodeExpected: HttpStatusCode.NO_CONTENT_204 - }) -} - -function removeVideoRedundancy (options: { - url: string - accessToken: string - redundancyId: number -}) { - const { url, accessToken, redundancyId } = options - const path = '/api/v1/server/redundancy/videos/' + redundancyId - - return makeDeleteRequest({ - url, - token: accessToken, - path, - statusCodeExpected: HttpStatusCode.NO_CONTENT_204 - }) -} - -export { - updateRedundancy, - listVideoRedundancies, - addVideoRedundancy, - removeVideoRedundancy -} diff --git a/shared/extra-utils/server/servers.ts b/shared/extra-utils/server/servers.ts index 79d6b7b1a..eaf39ecea 100644 --- a/shared/extra-utils/server/servers.ts +++ b/shared/extra-utils/server/servers.ts @@ -21,6 +21,7 @@ import { DebugCommand } from './debug-command' import { FollowsCommand } from './follows-command' import { JobsCommand } from './jobs-command' import { PluginsCommand } from './plugins-command' +import { RedundancyCommand } from './redundancy-command' interface ServerInfo { app: ChildProcess @@ -87,6 +88,7 @@ interface ServerInfo { followsCommand?: FollowsCommand jobsCommand?: JobsCommand pluginsCommand?: PluginsCommand + redundancyCommand?: RedundancyCommand } function parallelTests () { @@ -305,6 +307,7 @@ async function runServer (server: ServerInfo, configOverrideArg?: any, args = [] server.followsCommand = new FollowsCommand(server) server.jobsCommand = new JobsCommand(server) server.pluginsCommand = new PluginsCommand(server) + server.redundancyCommand = new RedundancyCommand(server) res(server) }) -- cgit v1.2.3 From bc8090411ddaa8d742ce4de3c83f9dba7bc18e2a Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Wed, 7 Jul 2021 11:07:12 +0200 Subject: Introduce stats command --- server/tests/api/redundancy/redundancy.ts | 15 +------ server/tests/api/server/stats.ts | 63 ++++++++++++------------------ shared/extra-utils/index.ts | 4 -- shared/extra-utils/server/index.ts | 3 ++ shared/extra-utils/server/servers.ts | 3 ++ shared/extra-utils/server/stats-command.ts | 25 ++++++++++++ shared/extra-utils/server/stats.ts | 23 ----------- 7 files changed, 58 insertions(+), 78 deletions(-) create mode 100644 shared/extra-utils/server/stats-command.ts delete mode 100644 shared/extra-utils/server/stats.ts diff --git a/server/tests/api/redundancy/redundancy.ts b/server/tests/api/redundancy/redundancy.ts index 5b970473c..e4ea99de6 100644 --- a/server/tests/api/redundancy/redundancy.ts +++ b/server/tests/api/redundancy/redundancy.ts @@ -5,7 +5,6 @@ import * as chai from 'chai' import { readdir } from 'fs-extra' import * as magnetUtil from 'magnet-uri' import { join } from 'path' -import { removeVideoRedundancy } from '@server/lib/redundancy' import { HttpStatusCode } from '@shared/core-utils' import { checkSegmentHash, @@ -30,15 +29,7 @@ import { waitJobs, waitUntilLog } from '@shared/extra-utils' -import { getStats } from '@shared/extra-utils/server/stats' -import { - ServerStats, - VideoDetails, - VideoPrivacy, - VideoRedundancy, - VideoRedundancyStrategy, - VideoRedundancyStrategyWithManual -} from '@shared/models' +import { VideoDetails, VideoPrivacy, VideoRedundancyStrategy, VideoRedundancyStrategyWithManual } from '@shared/models' const expect = chai.expect @@ -241,9 +232,7 @@ async function checkStatsGlobal (strategy: VideoRedundancyStrategyWithManual) { statsLength = 2 } - const res = await getStats(servers[0].url) - const data: ServerStats = res.body - + const data = await servers[0].statsCommand.get() expect(data.videosRedundancy).to.have.lengthOf(statsLength) const stat = data.videosRedundancy[0] diff --git a/server/tests/api/server/stats.ts b/server/tests/api/server/stats.ts index f609ea725..36114a297 100644 --- a/server/tests/api/server/stats.ts +++ b/server/tests/api/server/stats.ts @@ -19,8 +19,7 @@ import { wait, waitJobs } from '@shared/extra-utils' -import { getStats } from '@shared/extra-utils/server/stats' -import { ActivityType, ServerStats, VideoPlaylistPrivacy } from '@shared/models' +import { ActivityType, VideoPlaylistPrivacy } from '@shared/models' const expect = chai.expect @@ -58,8 +57,7 @@ describe('Test stats (excluding redundancy)', function () { }) it('Should have the correct stats on instance 1', async function () { - const res = await getStats(servers[0].url) - const data: ServerStats = res.body + const data = await servers[0].statsCommand.get() expect(data.totalLocalVideoComments).to.equal(1) expect(data.totalLocalVideos).to.equal(1) @@ -74,8 +72,7 @@ describe('Test stats (excluding redundancy)', function () { }) it('Should have the correct stats on instance 2', async function () { - const res = await getStats(servers[1].url) - const data: ServerStats = res.body + const data = await servers[1].statsCommand.get() expect(data.totalLocalVideoComments).to.equal(0) expect(data.totalLocalVideos).to.equal(0) @@ -90,8 +87,7 @@ describe('Test stats (excluding redundancy)', function () { }) it('Should have the correct stats on instance 3', async function () { - const res = await getStats(servers[2].url) - const data: ServerStats = res.body + const data = await servers[2].statsCommand.get() expect(data.totalLocalVideoComments).to.equal(0) expect(data.totalLocalVideos).to.equal(0) @@ -110,8 +106,7 @@ describe('Test stats (excluding redundancy)', function () { await servers[2].followsCommand.unfollow({ target: servers[0] }) await waitJobs(servers) - const res = await getStats(servers[2].url) - const data: ServerStats = res.body + const data = await servers[2].statsCommand.get() expect(data.totalVideos).to.equal(0) }) @@ -120,8 +115,8 @@ describe('Test stats (excluding redundancy)', function () { const server = servers[0] { - const res = await getStats(server.url) - const data: ServerStats = res.body + const data = await server.statsCommand.get() + expect(data.totalDailyActiveUsers).to.equal(1) expect(data.totalWeeklyActiveUsers).to.equal(1) expect(data.totalMonthlyActiveUsers).to.equal(1) @@ -130,8 +125,8 @@ describe('Test stats (excluding redundancy)', function () { { await userLogin(server, user) - const res = await getStats(server.url) - const data: ServerStats = res.body + const data = await server.statsCommand.get() + expect(data.totalDailyActiveUsers).to.equal(2) expect(data.totalWeeklyActiveUsers).to.equal(2) expect(data.totalMonthlyActiveUsers).to.equal(2) @@ -142,8 +137,8 @@ describe('Test stats (excluding redundancy)', function () { const server = servers[0] { - const res = await getStats(server.url) - const data: ServerStats = res.body + const data = await server.statsCommand.get() + expect(data.totalLocalDailyActiveVideoChannels).to.equal(1) expect(data.totalLocalWeeklyActiveVideoChannels).to.equal(1) expect(data.totalLocalMonthlyActiveVideoChannels).to.equal(1) @@ -157,8 +152,8 @@ describe('Test stats (excluding redundancy)', function () { const resChannel = await addVideoChannel(server.url, server.accessToken, channelAttributes) channelId = resChannel.body.videoChannel.id - const res = await getStats(server.url) - const data: ServerStats = res.body + const data = await server.statsCommand.get() + expect(data.totalLocalDailyActiveVideoChannels).to.equal(1) expect(data.totalLocalWeeklyActiveVideoChannels).to.equal(1) expect(data.totalLocalMonthlyActiveVideoChannels).to.equal(1) @@ -167,8 +162,8 @@ describe('Test stats (excluding redundancy)', function () { { await uploadVideo(server.url, server.accessToken, { fixture: 'video_short.webm', channelId }) - const res = await getStats(server.url) - const data: ServerStats = res.body + const data = await server.statsCommand.get() + expect(data.totalLocalDailyActiveVideoChannels).to.equal(2) expect(data.totalLocalWeeklyActiveVideoChannels).to.equal(2) expect(data.totalLocalMonthlyActiveVideoChannels).to.equal(2) @@ -179,9 +174,8 @@ describe('Test stats (excluding redundancy)', function () { const server = servers[0] { - const resStats = await getStats(server.url) - const dataStats: ServerStats = resStats.body - expect(dataStats.totalLocalPlaylists).to.equal(0) + const data = await server.statsCommand.get() + expect(data.totalLocalPlaylists).to.equal(0) } { @@ -195,9 +189,8 @@ describe('Test stats (excluding redundancy)', function () { } }) - const resStats = await getStats(server.url) - const dataStats: ServerStats = resStats.body - expect(dataStats.totalLocalPlaylists).to.equal(1) + const data = await server.statsCommand.get() + expect(data.totalLocalPlaylists).to.equal(1) } }) @@ -231,14 +224,12 @@ describe('Test stats (excluding redundancy)', function () { await waitJobs(servers) { - const res = await getStats(servers[1].url) - const data: ServerStats = res.body + const data = await servers[1].statsCommand.get() expect(data.totalLocalVideoFilesSize).to.equal(0) } { - const res = await getStats(servers[0].url) - const data: ServerStats = res.body + const data = await servers[0].statsCommand.get() expect(data.totalLocalVideoFilesSize).to.be.greaterThan(500000) expect(data.totalLocalVideoFilesSize).to.be.lessThan(600000) } @@ -253,8 +244,7 @@ describe('Test stats (excluding redundancy)', function () { } }) - const res1 = await getStats(servers[1].url) - const first = res1.body as ServerStats + const first = await servers[1].statsCommand.get() for (let i = 0; i < 10; i++) { await uploadVideo(servers[0].url, servers[0].accessToken, { name: 'video' }) @@ -264,10 +254,9 @@ describe('Test stats (excluding redundancy)', function () { await wait(6000) - const res2 = await getStats(servers[1].url) - const second: ServerStats = res2.body - + const second = await servers[1].statsCommand.get() expect(second.totalActivityPubMessagesProcessed).to.be.greaterThan(first.totalActivityPubMessagesProcessed) + const apTypes: ActivityType[] = [ 'Create', 'Update', 'Delete', 'Follow', 'Accept', 'Announce', 'Undo', 'Like', 'Reject', 'View', 'Dislike', 'Flag' ] @@ -287,9 +276,7 @@ describe('Test stats (excluding redundancy)', function () { await wait(6000) - const res3 = await getStats(servers[1].url) - const third: ServerStats = res3.body - + const third = await servers[1].statsCommand.get() expect(third.totalActivityPubMessagesWaiting).to.equal(0) expect(third.activityPubMessagesProcessedPerSecond).to.be.lessThan(second.activityPubMessagesProcessedPerSecond) }) diff --git a/shared/extra-utils/index.ts b/shared/extra-utils/index.ts index cf6418249..f69d7241e 100644 --- a/shared/extra-utils/index.ts +++ b/shared/extra-utils/index.ts @@ -13,10 +13,6 @@ export * from './server' export * from './requests/check-api-params' export * from './requests/requests' -export * from './server/clients' -export * from './server/config' -export * from './server/servers' - export * from './users/accounts' export * from './users/blocklist' export * from './users/login' diff --git a/shared/extra-utils/server/index.ts b/shared/extra-utils/server/index.ts index 3ee70f0cf..d37f46321 100644 --- a/shared/extra-utils/server/index.ts +++ b/shared/extra-utils/server/index.ts @@ -1,3 +1,4 @@ +export * from './config' export * from './contact-form-command' export * from './debug-command' export * from './follows-command' @@ -7,3 +8,5 @@ export * from './jobs-command' export * from './plugins-command' export * from './plugins' export * from './redundancy-command' +export * from './servers' +export * from './stats-command' diff --git a/shared/extra-utils/server/servers.ts b/shared/extra-utils/server/servers.ts index eaf39ecea..4603cf62e 100644 --- a/shared/extra-utils/server/servers.ts +++ b/shared/extra-utils/server/servers.ts @@ -22,6 +22,7 @@ import { FollowsCommand } from './follows-command' import { JobsCommand } from './jobs-command' import { PluginsCommand } from './plugins-command' import { RedundancyCommand } from './redundancy-command' +import { StatsCommand } from './stats-command' interface ServerInfo { app: ChildProcess @@ -89,6 +90,7 @@ interface ServerInfo { jobsCommand?: JobsCommand pluginsCommand?: PluginsCommand redundancyCommand?: RedundancyCommand + statsCommand?: StatsCommand } function parallelTests () { @@ -308,6 +310,7 @@ async function runServer (server: ServerInfo, configOverrideArg?: any, args = [] server.jobsCommand = new JobsCommand(server) server.pluginsCommand = new PluginsCommand(server) server.redundancyCommand = new RedundancyCommand(server) + server.statsCommand = new StatsCommand(server) res(server) }) diff --git a/shared/extra-utils/server/stats-command.ts b/shared/extra-utils/server/stats-command.ts new file mode 100644 index 000000000..b51d9ceef --- /dev/null +++ b/shared/extra-utils/server/stats-command.ts @@ -0,0 +1,25 @@ +import { ServerStats } from '@shared/models' +import { HttpStatusCode } from '../../core-utils/miscs/http-error-codes' +import { AbstractCommand, OverrideCommandOptions } from '../shared' + +export class StatsCommand extends AbstractCommand { + + get (options: OverrideCommandOptions & { + useCache?: boolean // default false + } = {}) { + const { useCache = false } = options + const path = '/api/v1/server/stats' + + const query = { + t: useCache ? undefined : new Date().getTime() + } + + return this.getRequestBody({ + ...options, + + path, + query, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } +} diff --git a/shared/extra-utils/server/stats.ts b/shared/extra-utils/server/stats.ts deleted file mode 100644 index b9dae24e2..000000000 --- a/shared/extra-utils/server/stats.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { makeGetRequest } from '../requests/requests' -import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' - -function getStats (url: string, useCache = false) { - const path = '/api/v1/server/stats' - - const query = { - t: useCache ? undefined : new Date().getTime() - } - - return makeGetRequest({ - url, - path, - query, - statusCodeExpected: HttpStatusCode.OK_200 - }) -} - -// --------------------------------------------------------------------------- - -export { - getStats -} -- cgit v1.2.3 From 65e6e2602c0d5521f3a6740f7469bb92830ecb53 Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Wed, 7 Jul 2021 11:51:09 +0200 Subject: Introduce config command --- server/tests/api/check-params/live.ts | 75 +++--- server/tests/api/check-params/search.ts | 25 +- server/tests/api/check-params/video-imports.ts | 53 ++--- server/tests/api/live/live-constraints.ts | 33 +-- server/tests/api/live/live-permanent.ts | 35 +-- server/tests/api/live/live-save-replay.ts | 21 +- server/tests/api/live/live-socket-messages.ts | 15 +- server/tests/api/live/live-views.ts | 15 +- server/tests/api/live/live.ts | 43 ++-- .../api/notifications/moderation-notifications.ts | 20 +- server/tests/api/search/search-index.ts | 55 +++-- server/tests/api/search/search-videos.ts | 5 +- server/tests/api/server/auto-follows.ts | 9 +- server/tests/api/server/config.ts | 48 ++-- server/tests/api/server/follows-moderation.ts | 9 +- server/tests/api/server/homepage.ts | 5 +- server/tests/api/server/plugins.ts | 21 +- server/tests/api/server/stats.ts | 47 ++-- server/tests/api/users/users-verification.ts | 37 +-- server/tests/api/users/users.ts | 9 +- server/tests/api/videos/video-change-ownership.ts | 15 +- server/tests/api/videos/video-hls.ts | 41 ++-- server/tests/api/videos/video-imports.ts | 5 +- server/tests/api/videos/video-nsfw.ts | 25 +- server/tests/api/videos/video-transcoder.ts | 86 +++---- server/tests/cli/create-transcoding-job.ts | 5 +- server/tests/cli/plugins.ts | 8 +- server/tests/client.ts | 55 +++-- server/tests/plugins/external-auth.ts | 15 +- server/tests/plugins/filter-hooks.ts | 61 ++--- server/tests/plugins/id-and-pass-auth.ts | 15 +- server/tests/plugins/plugin-transcoding.ts | 50 ++-- shared/extra-utils/server/config-command.ts | 260 +++++++++++++++++++++ shared/extra-utils/server/config.ts | 260 --------------------- shared/extra-utils/server/index.ts | 2 +- shared/extra-utils/server/servers.ts | 3 + 36 files changed, 740 insertions(+), 746 deletions(-) create mode 100644 shared/extra-utils/server/config-command.ts delete mode 100644 shared/extra-utils/server/config.ts diff --git a/server/tests/api/check-params/live.ts b/server/tests/api/check-params/live.ts index 933d8abf2..7a623c169 100644 --- a/server/tests/api/check-params/live.ts +++ b/server/tests/api/check-params/live.ts @@ -19,7 +19,6 @@ import { ServerInfo, setAccessTokensToServers, stopFfmpeg, - updateCustomSubConfig, updateLive, uploadVideoAndGetId, userLogin, @@ -43,12 +42,14 @@ describe('Test video lives API validator', function () { await setAccessTokensToServers([ server ]) - await updateCustomSubConfig(server.url, server.accessToken, { - live: { - enabled: true, - maxInstanceLives: 20, - maxUserLives: 20, - allowReplay: true + await server.configCommand.updateCustomSubConfig({ + newConfig: { + live: { + enabled: true, + maxInstanceLives: 20, + maxUserLives: 20, + allowReplay: true + } } }) @@ -234,9 +235,11 @@ describe('Test video lives API validator', function () { }) it('Should forbid if live is disabled', async function () { - await updateCustomSubConfig(server.url, server.accessToken, { - live: { - enabled: false + await server.configCommand.updateCustomSubConfig({ + newConfig: { + live: { + enabled: false + } } }) @@ -252,10 +255,12 @@ describe('Test video lives API validator', function () { it('Should forbid to save replay if not enabled by the admin', async function () { const fields = immutableAssign(baseCorrectParams, { saveReplay: true }) - await updateCustomSubConfig(server.url, server.accessToken, { - live: { - enabled: true, - allowReplay: false + await server.configCommand.updateCustomSubConfig({ + newConfig: { + live: { + enabled: true, + allowReplay: false + } } }) @@ -271,10 +276,12 @@ describe('Test video lives API validator', function () { it('Should allow to save replay if enabled by the admin', async function () { const fields = immutableAssign(baseCorrectParams, { saveReplay: true }) - await updateCustomSubConfig(server.url, server.accessToken, { - live: { - enabled: true, - allowReplay: true + await server.configCommand.updateCustomSubConfig({ + newConfig: { + live: { + enabled: true, + allowReplay: true + } } }) @@ -288,10 +295,12 @@ describe('Test video lives API validator', function () { }) it('Should not allow live if max instance lives is reached', async function () { - await updateCustomSubConfig(server.url, server.accessToken, { - live: { - enabled: true, - maxInstanceLives: 1 + await server.configCommand.updateCustomSubConfig({ + newConfig: { + live: { + enabled: true, + maxInstanceLives: 1 + } } }) @@ -305,11 +314,13 @@ describe('Test video lives API validator', function () { }) it('Should not allow live if max user lives is reached', async function () { - await updateCustomSubConfig(server.url, server.accessToken, { - live: { - enabled: true, - maxInstanceLives: 20, - maxUserLives: 1 + await server.configCommand.updateCustomSubConfig({ + newConfig: { + live: { + enabled: true, + maxInstanceLives: 20, + maxUserLives: 1 + } } }) @@ -393,10 +404,12 @@ describe('Test video lives API validator', function () { }) it('Should fail to update replay status if replay is not allowed on the instance', async function () { - await updateCustomSubConfig(server.url, server.accessToken, { - live: { - enabled: true, - allowReplay: false + await server.configCommand.updateCustomSubConfig({ + newConfig: { + live: { + enabled: true, + allowReplay: false + } } }) diff --git a/server/tests/api/check-params/search.ts b/server/tests/api/check-params/search.ts index 20ad46cff..4a2fc1197 100644 --- a/server/tests/api/check-params/search.ts +++ b/server/tests/api/check-params/search.ts @@ -1,28 +1,27 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ import 'mocha' +import { HttpStatusCode } from '@shared/core-utils' import { + checkBadCountPagination, + checkBadSortPagination, + checkBadStartPagination, cleanupTests, flushAndRunServer, immutableAssign, makeGetRequest, ServerInfo, - updateCustomSubConfig, setAccessTokensToServers -} from '../../../../shared/extra-utils' -import { - checkBadCountPagination, - checkBadSortPagination, - checkBadStartPagination -} from '../../../../shared/extra-utils/requests/check-api-params' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' +} from '@shared/extra-utils' function updateSearchIndex (server: ServerInfo, enabled: boolean, disableLocalSearch = false) { - return updateCustomSubConfig(server.url, server.accessToken, { - search: { - searchIndex: { - enabled, - disableLocalSearch + return server.configCommand.updateCustomSubConfig({ + newConfig: { + search: { + searchIndex: { + enabled, + disableLocalSearch + } } } }) diff --git a/server/tests/api/check-params/video-imports.ts b/server/tests/api/check-params/video-imports.ts index a27b624d0..dae3860ef 100644 --- a/server/tests/api/check-params/video-imports.ts +++ b/server/tests/api/check-params/video-imports.ts @@ -2,9 +2,12 @@ import 'mocha' import { omit } from 'lodash' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '@shared/core-utils' import { buildAbsoluteFixturePath, + checkBadCountPagination, + checkBadSortPagination, + checkBadStartPagination, cleanupTests, createUser, flushAndRunServer, @@ -15,16 +18,10 @@ import { makeUploadRequest, ServerInfo, setAccessTokensToServers, - updateCustomSubConfig, userLogin -} from '../../../../shared/extra-utils' -import { - checkBadCountPagination, - checkBadSortPagination, - checkBadStartPagination -} from '../../../../shared/extra-utils/requests/check-api-params' -import { getGoodVideoUrl, getMagnetURI } from '../../../../shared/extra-utils/videos/video-imports' -import { VideoPrivacy } from '../../../../shared/models/videos/video-privacy.enum' +} from '@shared/extra-utils' +import { getGoodVideoUrl, getMagnetURI } from '@shared/extra-utils/videos/video-imports' +import { VideoPrivacy } from '@shared/models' describe('Test video imports API validator', function () { const path = '/api/v1/videos/imports' @@ -263,14 +260,16 @@ describe('Test video imports API validator', function () { }) it('Should forbid to import http videos', async function () { - await updateCustomSubConfig(server.url, server.accessToken, { - import: { - videos: { - http: { - enabled: false - }, - torrent: { - enabled: true + await server.configCommand.updateCustomSubConfig({ + newConfig: { + import: { + videos: { + http: { + enabled: false + }, + torrent: { + enabled: true + } } } } @@ -286,14 +285,16 @@ describe('Test video imports API validator', function () { }) it('Should forbid to import torrent videos', async function () { - await updateCustomSubConfig(server.url, server.accessToken, { - import: { - videos: { - http: { - enabled: true - }, - torrent: { - enabled: false + await server.configCommand.updateCustomSubConfig({ + newConfig: { + import: { + videos: { + http: { + enabled: true + }, + torrent: { + enabled: false + } } } } diff --git a/server/tests/api/live/live-constraints.ts b/server/tests/api/live/live-constraints.ts index cc635de33..c64d10dcd 100644 --- a/server/tests/api/live/live-constraints.ts +++ b/server/tests/api/live/live-constraints.ts @@ -6,17 +6,16 @@ import { VideoDetails, VideoPrivacy } from '@shared/models' import { checkLiveCleanup, cleanupTests, + ConfigCommand, createLive, doubleFollow, flushAndRunMultipleServers, generateUser, - getCustomConfigResolutions, getVideo, runAndTestFfmpegStreamError, ServerInfo, setAccessTokensToServers, setDefaultVideoChannel, - updateCustomSubConfig, updateUser, wait, waitJobs, @@ -80,12 +79,14 @@ describe('Test live constraints', function () { await setAccessTokensToServers(servers) await setDefaultVideoChannel(servers) - await updateCustomSubConfig(servers[0].url, servers[0].accessToken, { - live: { - enabled: true, - allowReplay: true, - transcoding: { - enabled: false + await servers[0].configCommand.updateCustomSubConfig({ + newConfig: { + live: { + enabled: true, + allowReplay: true, + transcoding: { + enabled: false + } } } }) @@ -157,14 +158,16 @@ describe('Test live constraints', function () { it('Should have max duration limit', async function () { this.timeout(60000) - await updateCustomSubConfig(servers[0].url, servers[0].accessToken, { - live: { - enabled: true, - allowReplay: true, - maxDuration: 1, - transcoding: { + await servers[0].configCommand.updateCustomSubConfig({ + newConfig: { + live: { enabled: true, - resolutions: getCustomConfigResolutions(true) + allowReplay: true, + maxDuration: 1, + transcoding: { + enabled: true, + resolutions: ConfigCommand.getCustomConfigResolutions(true) + } } } }) diff --git a/server/tests/api/live/live-permanent.ts b/server/tests/api/live/live-permanent.ts index 71b7d28a8..b9e37c834 100644 --- a/server/tests/api/live/live-permanent.ts +++ b/server/tests/api/live/live-permanent.ts @@ -5,10 +5,10 @@ import * as chai from 'chai' import { LiveVideoCreate, VideoDetails, VideoPrivacy, VideoState } from '@shared/models' import { cleanupTests, + ConfigCommand, createLive, doubleFollow, flushAndRunMultipleServers, - getCustomConfigResolutions, getLive, getPlaylistsCount, getVideo, @@ -17,7 +17,6 @@ import { setAccessTokensToServers, setDefaultVideoChannel, stopFfmpeg, - updateCustomSubConfig, updateLive, wait, waitJobs, @@ -63,14 +62,16 @@ describe('Permanent live', function () { // Server 1 and server 2 follow each other await doubleFollow(servers[0], servers[1]) - await updateCustomSubConfig(servers[0].url, servers[0].accessToken, { - live: { - enabled: true, - allowReplay: true, - maxDuration: -1, - transcoding: { + await servers[0].configCommand.updateCustomSubConfig({ + newConfig: { + live: { enabled: true, - resolutions: getCustomConfigResolutions(true) + allowReplay: true, + maxDuration: -1, + transcoding: { + enabled: true, + resolutions: ConfigCommand.getCustomConfigResolutions(true) + } } } }) @@ -145,14 +146,16 @@ describe('Permanent live', function () { it('Should be able to stream again in the permanent live', async function () { this.timeout(20000) - await updateCustomSubConfig(servers[0].url, servers[0].accessToken, { - live: { - enabled: true, - allowReplay: true, - maxDuration: -1, - transcoding: { + await servers[0].configCommand.updateCustomSubConfig({ + newConfig: { + live: { enabled: true, - resolutions: getCustomConfigResolutions(false) + allowReplay: true, + maxDuration: -1, + transcoding: { + enabled: true, + resolutions: ConfigCommand.getCustomConfigResolutions(false) + } } } }) diff --git a/server/tests/api/live/live-save-replay.ts b/server/tests/api/live/live-save-replay.ts index 3d4736c8f..e74bc3e8d 100644 --- a/server/tests/api/live/live-save-replay.ts +++ b/server/tests/api/live/live-save-replay.ts @@ -9,10 +9,10 @@ import { addVideoToBlacklist, checkLiveCleanup, cleanupTests, + ConfigCommand, createLive, doubleFollow, flushAndRunMultipleServers, - getCustomConfigResolutions, getVideo, getVideosList, removeVideo, @@ -22,7 +22,6 @@ import { setDefaultVideoChannel, stopFfmpeg, testFfmpegStreamError, - updateCustomSubConfig, updateVideo, wait, waitJobs, @@ -102,14 +101,16 @@ describe('Save replay setting', function () { // Server 1 and server 2 follow each other await doubleFollow(servers[0], servers[1]) - await updateCustomSubConfig(servers[0].url, servers[0].accessToken, { - live: { - enabled: true, - allowReplay: true, - maxDuration: -1, - transcoding: { - enabled: false, - resolutions: getCustomConfigResolutions(true) + await servers[0].configCommand.updateCustomSubConfig({ + newConfig: { + live: { + enabled: true, + allowReplay: true, + maxDuration: -1, + transcoding: { + enabled: false, + resolutions: ConfigCommand.getCustomConfigResolutions(true) + } } } }) diff --git a/server/tests/api/live/live-socket-messages.ts b/server/tests/api/live/live-socket-messages.ts index e00909ade..0159d5199 100644 --- a/server/tests/api/live/live-socket-messages.ts +++ b/server/tests/api/live/live-socket-messages.ts @@ -15,7 +15,6 @@ import { setAccessTokensToServers, setDefaultVideoChannel, stopFfmpeg, - updateCustomSubConfig, viewVideo, wait, waitJobs, @@ -37,12 +36,14 @@ describe('Test live', function () { await setAccessTokensToServers(servers) await setDefaultVideoChannel(servers) - await updateCustomSubConfig(servers[0].url, servers[0].accessToken, { - live: { - enabled: true, - allowReplay: true, - transcoding: { - enabled: false + await servers[0].configCommand.updateCustomSubConfig({ + newConfig: { + live: { + enabled: true, + allowReplay: true, + transcoding: { + enabled: false + } } } }) diff --git a/server/tests/api/live/live-views.ts b/server/tests/api/live/live-views.ts index a44d21ffa..ca571c962 100644 --- a/server/tests/api/live/live-views.ts +++ b/server/tests/api/live/live-views.ts @@ -15,7 +15,6 @@ import { setAccessTokensToServers, setDefaultVideoChannel, stopFfmpeg, - updateCustomSubConfig, viewVideo, wait, waitJobs, @@ -36,12 +35,14 @@ describe('Test live', function () { await setAccessTokensToServers(servers) await setDefaultVideoChannel(servers) - await updateCustomSubConfig(servers[0].url, servers[0].accessToken, { - live: { - enabled: true, - allowReplay: true, - transcoding: { - enabled: false + await servers[0].configCommand.updateCustomSubConfig({ + newConfig: { + live: { + enabled: true, + allowReplay: true, + transcoding: { + enabled: false + } } } }) diff --git a/server/tests/api/live/live.ts b/server/tests/api/live/live.ts index 50397924e..2c3102994 100644 --- a/server/tests/api/live/live.ts +++ b/server/tests/api/live/live.ts @@ -34,7 +34,6 @@ import { stopFfmpeg, testFfmpegStreamError, testImage, - updateCustomSubConfig, updateLive, uploadVideoAndGetId, wait, @@ -59,12 +58,14 @@ describe('Test live', function () { await setAccessTokensToServers(servers) await setDefaultVideoChannel(servers) - await updateCustomSubConfig(servers[0].url, servers[0].accessToken, { - live: { - enabled: true, - allowReplay: true, - transcoding: { - enabled: false + await servers[0].configCommand.updateCustomSubConfig({ + newConfig: { + live: { + enabled: true, + allowReplay: true, + transcoding: { + enabled: false + } } } }) @@ -422,20 +423,22 @@ describe('Test live', function () { } function updateConf (resolutions: number[]) { - return updateCustomSubConfig(servers[0].url, servers[0].accessToken, { - live: { - enabled: true, - allowReplay: true, - maxDuration: -1, - transcoding: { + return servers[0].configCommand.updateCustomSubConfig({ + newConfig: { + live: { enabled: true, - resolutions: { - '240p': resolutions.includes(240), - '360p': resolutions.includes(360), - '480p': resolutions.includes(480), - '720p': resolutions.includes(720), - '1080p': resolutions.includes(1080), - '2160p': resolutions.includes(2160) + allowReplay: true, + maxDuration: -1, + transcoding: { + enabled: true, + resolutions: { + '240p': resolutions.includes(240), + '360p': resolutions.includes(360), + '480p': resolutions.includes(480), + '720p': resolutions.includes(720), + '1080p': resolutions.includes(1080), + '2160p': resolutions.includes(2160) + } } } } diff --git a/server/tests/api/notifications/moderation-notifications.ts b/server/tests/api/notifications/moderation-notifications.ts index 9a93ce401..3e66e7517 100644 --- a/server/tests/api/notifications/moderation-notifications.ts +++ b/server/tests/api/notifications/moderation-notifications.ts @@ -23,7 +23,6 @@ import { createUser, generateUserAccessToken, getAccount, - getCustomConfig, getVideoCommentThreads, getVideoIdFromUUID, immutableAssign, @@ -34,8 +33,6 @@ import { removeUserSubscription, removeVideoFromBlacklist, ServerInfo, - updateCustomConfig, - updateCustomSubConfig, uploadVideo, wait, waitJobs @@ -407,7 +404,7 @@ describe('Test moderation notifications', function () { } } } - await updateCustomSubConfig(servers[0].url, servers[0].accessToken, config) + await servers[0].configCommand.updateCustomSubConfig({ newConfig: config }) await servers[2].followsCommand.follow({ targets: [ servers[0].url ] }) @@ -421,7 +418,7 @@ describe('Test moderation notifications', function () { await checkAutoInstanceFollowing(immutableAssign(baseParams, userOverride), followerHost, followingHost, 'absence') config.followings.instance.autoFollowBack.enabled = false - await updateCustomSubConfig(servers[0].url, servers[0].accessToken, config) + await servers[0].configCommand.updateCustomSubConfig({ newConfig: config }) await servers[0].followsCommand.unfollow({ target: servers[2] }) await servers[2].followsCommand.unfollow({ target: servers[0] }) }) @@ -430,7 +427,7 @@ describe('Test moderation notifications', function () { this.timeout(30000) await servers[0].followsCommand.unfollow({ target: servers[1] }) - await updateCustomSubConfig(servers[0].url, servers[0].accessToken, config) + await servers[0].configCommand.updateCustomSubConfig({ newConfig: config }) await wait(5000) await waitJobs(servers) @@ -440,7 +437,7 @@ describe('Test moderation notifications', function () { await checkAutoInstanceFollowing(baseParams, followerHost, followingHost, 'presence') config.followings.instance.autoFollowIndex.enabled = false - await updateCustomSubConfig(servers[0].url, servers[0].accessToken, config) + await servers[0].configCommand.updateCustomSubConfig({ newConfig: config }) await servers[0].followsCommand.unfollow({ target: servers[1] }) }) }) @@ -476,8 +473,8 @@ describe('Test moderation notifications', function () { token: userAccessToken } - const resCustomConfig = await getCustomConfig(servers[0].url, servers[0].accessToken) - currentCustomConfig = resCustomConfig.body + currentCustomConfig = await servers[0].configCommand.getCustomConfig() + const autoBlacklistTestsCustomConfig = immutableAssign(currentCustomConfig, { autoBlacklist: { videos: { @@ -487,9 +484,10 @@ describe('Test moderation notifications', function () { } } }) + // enable transcoding otherwise own publish notification after transcoding not expected autoBlacklistTestsCustomConfig.transcoding.enabled = true - await updateCustomConfig(servers[0].url, servers[0].accessToken, autoBlacklistTestsCustomConfig) + await servers[0].configCommand.updateCustomConfig({ newCustomConfig: autoBlacklistTestsCustomConfig }) await addUserSubscription(servers[0].url, servers[0].accessToken, 'user_1_channel@localhost:' + servers[0].port) await addUserSubscription(servers[1].url, servers[1].accessToken, 'user_1_channel@localhost:' + servers[0].port) @@ -612,7 +610,7 @@ describe('Test moderation notifications', function () { }) after(async () => { - await updateCustomConfig(servers[0].url, servers[0].accessToken, currentCustomConfig) + await servers[0].configCommand.updateCustomConfig({ newCustomConfig: currentCustomConfig }) await removeUserSubscription(servers[0].url, servers[0].accessToken, 'user_1_channel@localhost:' + servers[0].port) await removeUserSubscription(servers[1].url, servers[1].accessToken, 'user_1_channel@localhost:' + servers[0].port) diff --git a/server/tests/api/search/search-index.ts b/server/tests/api/search/search-index.ts index b2c0857a7..e4c5f5796 100644 --- a/server/tests/api/search/search-index.ts +++ b/server/tests/api/search/search-index.ts @@ -9,7 +9,6 @@ import { SearchCommand, ServerInfo, setAccessTokensToServers, - updateCustomSubConfig, uploadVideo } from '@shared/extra-utils' import { VideoPlaylistPrivacy, VideoPlaylistType, VideosSearchQuery } from '@shared/models' @@ -39,12 +38,14 @@ describe('Test videos search', function () { it('Should make a local videos search by default', async function () { this.timeout(10000) - await updateCustomSubConfig(server.url, server.accessToken, { - search: { - searchIndex: { - enabled: true, - isDefaultSearch: false, - disableLocalSearch: false + await server.configCommand.updateCustomSubConfig({ + newConfig: { + search: { + searchIndex: { + enabled: true, + isDefaultSearch: false, + disableLocalSearch: false + } } } }) @@ -64,12 +65,14 @@ describe('Test videos search', function () { }) it('Should make an index videos search by default', async function () { - await updateCustomSubConfig(server.url, server.accessToken, { - search: { - searchIndex: { - enabled: true, - isDefaultSearch: true, - disableLocalSearch: false + await server.configCommand.updateCustomSubConfig({ + newConfig: { + search: { + searchIndex: { + enabled: true, + isDefaultSearch: true, + disableLocalSearch: false + } } } }) @@ -84,12 +87,14 @@ describe('Test videos search', function () { }) it('Should make an index videos search if local search is disabled', async function () { - await updateCustomSubConfig(server.url, server.accessToken, { - search: { - searchIndex: { - enabled: true, - isDefaultSearch: false, - disableLocalSearch: true + await server.configCommand.updateCustomSubConfig({ + newConfig: { + search: { + searchIndex: { + enabled: true, + isDefaultSearch: false, + disableLocalSearch: true + } } } }) @@ -216,7 +221,11 @@ describe('Test videos search', function () { let nsfwUUID: string { - await updateCustomSubConfig(server.url, server.accessToken, { instance: { defaultNSFWPolicy: 'display' } }) + await server.configCommand.updateCustomSubConfig({ + newConfig: { + instance: { defaultNSFWPolicy: 'display' } + } + }) const body = await command.searchVideos({ search: 'NSFW search index', sort: '-match' }) expect(body.data).to.have.length.greaterThan(0) @@ -228,7 +237,11 @@ describe('Test videos search', function () { } { - await updateCustomSubConfig(server.url, server.accessToken, { instance: { defaultNSFWPolicy: 'do_not_list' } }) + await server.configCommand.updateCustomSubConfig({ + newConfig: { + instance: { defaultNSFWPolicy: 'do_not_list' } + } + }) const body = await command.searchVideos({ search: 'NSFW search index', sort: '-match' }) diff --git a/server/tests/api/search/search-videos.ts b/server/tests/api/search/search-videos.ts index f0482c7e0..7dc89c447 100644 --- a/server/tests/api/search/search-videos.ts +++ b/server/tests/api/search/search-videos.ts @@ -14,7 +14,6 @@ import { setAccessTokensToServers, setDefaultVideoChannel, stopFfmpeg, - updateCustomSubConfig, uploadVideo, wait, waitUntilLivePublished @@ -486,13 +485,13 @@ describe('Test videos search', function () { this.timeout(30000) { - const options = { + const newConfig = { search: { searchIndex: { enabled: false } }, live: { enabled: true } } - await updateCustomSubConfig(server.url, server.accessToken, options) + await server.configCommand.updateCustomSubConfig({ newConfig }) } { diff --git a/server/tests/api/server/auto-follows.ts b/server/tests/api/server/auto-follows.ts index 02389b1e9..34c4f6882 100644 --- a/server/tests/api/server/auto-follows.ts +++ b/server/tests/api/server/auto-follows.ts @@ -8,7 +8,6 @@ import { MockInstancesIndex, ServerInfo, setAccessTokensToServers, - updateCustomSubConfig, wait, waitJobs } from '@shared/extra-utils' @@ -87,7 +86,7 @@ describe('Test auto follows', function () { } } } - await updateCustomSubConfig(servers[1].url, servers[1].accessToken, config) + await servers[1].configCommand.updateCustomSubConfig({ newConfig: config }) await server1Follows2(servers) @@ -112,7 +111,7 @@ describe('Test auto follows', function () { } } } - await updateCustomSubConfig(servers[1].url, servers[1].accessToken, config) + await servers[1].configCommand.updateCustomSubConfig({ newConfig: config }) await server1Follows2(servers) @@ -129,7 +128,7 @@ describe('Test auto follows', function () { config.followings.instance.autoFollowBack.enabled = false config.followers.instance.manualApproval = false - await updateCustomSubConfig(servers[1].url, servers[1].accessToken, config) + await servers[1].configCommand.updateCustomSubConfig({ newConfig: config }) }) }) @@ -166,7 +165,7 @@ describe('Test auto follows', function () { } } } - await updateCustomSubConfig(servers[0].url, servers[0].accessToken, config) + await servers[0].configCommand.updateCustomSubConfig({ newConfig: config }) await wait(5000) await waitJobs(servers) diff --git a/server/tests/api/server/config.ts b/server/tests/api/server/config.ts index 19bf9582c..037628c9d 100644 --- a/server/tests/api/server/config.ts +++ b/server/tests/api/server/config.ts @@ -2,15 +2,10 @@ import 'mocha' import * as chai from 'chai' -import { About } from '../../../../shared/models/server/about.model' -import { CustomConfig } from '../../../../shared/models/server/custom-config.model' +import { HttpStatusCode } from '@shared/core-utils' import { cleanupTests, - deleteCustomConfig, flushAndRunServer, - getAbout, - getConfig, - getCustomConfig, killallServers, makeGetRequest, parallelTests, @@ -18,11 +13,9 @@ import { reRunServer, ServerInfo, setAccessTokensToServers, - updateCustomConfig, uploadVideo -} from '../../../../shared/extra-utils' -import { ServerConfig } from '../../../../shared/models' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' +} from '@shared/extra-utils' +import { CustomConfig } from '@shared/models' const expect = chai.expect @@ -213,7 +206,7 @@ function checkUpdatedConfig (data: CustomConfig) { } describe('Test config', function () { - let server = null + let server: ServerInfo = null before(async function () { this.timeout(30000) @@ -223,8 +216,7 @@ describe('Test config', function () { }) it('Should have a correct config on a server with registration enabled', async function () { - const res = await getConfig(server.url) - const data: ServerConfig = res.body + const data = await server.configCommand.getConfig() expect(data.signup.allowed).to.be.true }) @@ -238,15 +230,13 @@ describe('Test config', function () { registerUser(server.url, 'user3', 'super password') ]) - const res = await getConfig(server.url) - const data: ServerConfig = res.body + const data = await server.configCommand.getConfig() expect(data.signup.allowed).to.be.false }) it('Should have the correct video allowed extensions', async function () { - const res = await getConfig(server.url) - const data: ServerConfig = res.body + const data = await server.configCommand.getConfig() expect(data.video.file.extensions).to.have.lengthOf(3) expect(data.video.file.extensions).to.contain('.mp4') @@ -260,8 +250,7 @@ describe('Test config', function () { }) it('Should get the customized configuration', async function () { - const res = await getCustomConfig(server.url, server.accessToken) - const data = res.body as CustomConfig + const data = await server.configCommand.getCustomConfig() checkInitialConfig(server, data) }) @@ -438,19 +427,16 @@ describe('Test config', function () { } } } - await updateCustomConfig(server.url, server.accessToken, newCustomConfig) - - const res = await getCustomConfig(server.url, server.accessToken) - const data = res.body + await server.configCommand.updateCustomConfig({ newCustomConfig }) + const data = await server.configCommand.getCustomConfig() checkUpdatedConfig(data) }) it('Should have the correct updated video allowed extensions', async function () { this.timeout(10000) - const res = await getConfig(server.url) - const data: ServerConfig = res.body + const data = await server.configCommand.getConfig() expect(data.video.file.extensions).to.have.length.above(4) expect(data.video.file.extensions).to.contain('.mp4') @@ -474,15 +460,13 @@ describe('Test config', function () { await reRunServer(server) - const res = await getCustomConfig(server.url, server.accessToken) - const data = res.body + const data = await server.configCommand.getCustomConfig() checkUpdatedConfig(data) }) it('Should fetch the about information', async function () { - const res = await getAbout(server.url) - const data: About = res.body + const data = await server.configCommand.getAbout() expect(data.instance.name).to.equal('PeerTube updated') expect(data.instance.shortDescription).to.equal('my short description') @@ -504,11 +488,9 @@ describe('Test config', function () { it('Should remove the custom configuration', async function () { this.timeout(10000) - await deleteCustomConfig(server.url, server.accessToken) - - const res = await getCustomConfig(server.url, server.accessToken) - const data = res.body + await server.configCommand.deleteCustomConfig() + const data = await server.configCommand.getCustomConfig() checkInitialConfig(server, data) }) diff --git a/server/tests/api/server/follows-moderation.ts b/server/tests/api/server/follows-moderation.ts index 4853b647d..6d6eca9a8 100644 --- a/server/tests/api/server/follows-moderation.ts +++ b/server/tests/api/server/follows-moderation.ts @@ -8,7 +8,6 @@ import { FollowsCommand, ServerInfo, setAccessTokensToServers, - updateCustomSubConfig, waitJobs } from '@shared/extra-utils' @@ -94,7 +93,7 @@ describe('Test follows moderation', function () { } } - await updateCustomSubConfig(servers[1].url, servers[1].accessToken, subConfig) + await servers[1].configCommand.updateCustomSubConfig({ newConfig: subConfig }) await commands[0].follow({ targets: [ servers[1].url ] }) await waitJobs(servers) @@ -114,7 +113,7 @@ describe('Test follows moderation', function () { } } - await updateCustomSubConfig(servers[1].url, servers[1].accessToken, subConfig) + await servers[1].configCommand.updateCustomSubConfig({ newConfig: subConfig }) await commands[0].follow({ targets: [ servers[1].url ] }) await waitJobs(servers) @@ -137,8 +136,8 @@ describe('Test follows moderation', function () { } } - await updateCustomSubConfig(servers[1].url, servers[1].accessToken, subConfig) - await updateCustomSubConfig(servers[2].url, servers[2].accessToken, subConfig) + await servers[1].configCommand.updateCustomSubConfig({ newConfig: subConfig }) + await servers[2].configCommand.updateCustomSubConfig({ newConfig: subConfig }) await commands[0].follow({ targets: [ servers[1].url ] }) await waitJobs(servers) diff --git a/server/tests/api/server/homepage.ts b/server/tests/api/server/homepage.ts index 4a3ec0479..c08067f3c 100644 --- a/server/tests/api/server/homepage.ts +++ b/server/tests/api/server/homepage.ts @@ -3,12 +3,10 @@ import 'mocha' import * as chai from 'chai' import { HttpStatusCode } from '@shared/core-utils' -import { ServerConfig } from '@shared/models' import { cleanupTests, CustomPagesCommand, flushAndRunServer, - getConfig, killallServers, reRunServer, ServerInfo, @@ -18,9 +16,8 @@ import { const expect = chai.expect async function getHomepageState (server: ServerInfo) { - const res = await getConfig(server.url) + const config = await server.configCommand.getConfig() - const config = res.body as ServerConfig return config.homepage.enabled } diff --git a/server/tests/api/server/plugins.ts b/server/tests/api/server/plugins.ts index 1536997d5..528bbbe58 100644 --- a/server/tests/api/server/plugins.ts +++ b/server/tests/api/server/plugins.ts @@ -7,7 +7,6 @@ import { cleanupTests, closeAllSequelize, flushAndRunServer, - getConfig, getMyUserInformation, killallServers, PluginsCommand, @@ -16,12 +15,11 @@ import { setAccessTokensToServers, setPluginVersion, testHelloWorldRegisteredSettings, - updateCustomSubConfig, updateMyUser, wait, waitUntilLog } from '@shared/extra-utils' -import { PluginType, ServerConfig, User } from '@shared/models' +import { PluginType, User } from '@shared/models' const expect = chai.expect @@ -102,8 +100,7 @@ describe('Test plugins', function () { }) it('Should have the plugin loaded in the configuration', async function () { - const res = await getConfig(server.url) - const config: ServerConfig = res.body + const config = await server.configCommand.getConfig() const theme = config.theme.registered.find(r => r.name === 'background-red') expect(theme).to.not.be.undefined @@ -113,11 +110,13 @@ describe('Test plugins', function () { }) it('Should update the default theme in the configuration', async function () { - await updateCustomSubConfig(server.url, server.accessToken, { theme: { default: 'background-red' } }) - - const res = await getConfig(server.url) - const config: ServerConfig = res.body + await server.configCommand.updateCustomSubConfig({ + newConfig: { + theme: { default: 'background-red' } + } + }) + const config = await server.configCommand.getConfig() expect(config.theme.default).to.equal('background-red') }) @@ -302,9 +301,7 @@ describe('Test plugins', function () { }) it('Should have updated the configuration', async function () { - // get /config (default theme + registered themes + registered plugins) - const res = await getConfig(server.url) - const config: ServerConfig = res.body + const config = await server.configCommand.getConfig() expect(config.theme.default).to.equal('default') diff --git a/server/tests/api/server/stats.ts b/server/tests/api/server/stats.ts index 36114a297..f01188d67 100644 --- a/server/tests/api/server/stats.ts +++ b/server/tests/api/server/stats.ts @@ -12,7 +12,6 @@ import { flushAndRunMultipleServers, ServerInfo, setAccessTokensToServers, - updateCustomSubConfig, uploadVideo, userLogin, viewVideo, @@ -197,24 +196,26 @@ describe('Test stats (excluding redundancy)', function () { it('Should correctly count video file sizes if transcoding is enabled', async function () { this.timeout(60000) - await updateCustomSubConfig(servers[0].url, servers[0].accessToken, { - transcoding: { - enabled: true, - webtorrent: { - enabled: true - }, - hls: { - enabled: true - }, - resolutions: { - '0p': false, - '240p': false, - '360p': false, - '480p': false, - '720p': false, - '1080p': false, - '1440p': false, - '2160p': false + await servers[0].configCommand.updateCustomSubConfig({ + newConfig: { + transcoding: { + enabled: true, + webtorrent: { + enabled: true + }, + hls: { + enabled: true + }, + resolutions: { + '0p': false, + '240p': false, + '360p': false, + '480p': false, + '720p': false, + '1080p': false, + '1440p': false, + '2160p': false + } } } }) @@ -238,9 +239,11 @@ describe('Test stats (excluding redundancy)', function () { it('Should have the correct AP stats', async function () { this.timeout(60000) - await updateCustomSubConfig(servers[0].url, servers[0].accessToken, { - transcoding: { - enabled: false + await servers[0].configCommand.updateCustomSubConfig({ + newConfig: { + transcoding: { + enabled: false + } } }) diff --git a/server/tests/api/users/users-verification.ts b/server/tests/api/users/users-verification.ts index 265cd6050..23f81d804 100644 --- a/server/tests/api/users/users-verification.ts +++ b/server/tests/api/users/users-verification.ts @@ -11,7 +11,6 @@ import { login, registerUser, ServerInfo, - updateCustomSubConfig, updateMyUser, userLogin, verifyEmail @@ -58,11 +57,13 @@ describe('Test users account verification', function () { it('Should register user and send verification email if verification required', async function () { this.timeout(30000) - await updateCustomSubConfig(server.url, server.accessToken, { - signup: { - enabled: true, - requiresEmailVerification: true, - limit: 10 + await server.configCommand.updateCustomSubConfig({ + newConfig: { + signup: { + enabled: true, + requiresEmailVerification: true, + limit: 10 + } } }) @@ -148,11 +149,13 @@ describe('Test users account verification', function () { it('Should register user not requiring email verification if setting not enabled', async function () { this.timeout(5000) - await updateCustomSubConfig(server.url, server.accessToken, { - signup: { - enabled: true, - requiresEmailVerification: false, - limit: 10 + await server.configCommand.updateCustomSubConfig({ + newConfig: { + signup: { + enabled: true, + requiresEmailVerification: false, + limit: 10 + } } }) @@ -168,11 +171,13 @@ describe('Test users account verification', function () { }) it('Should allow login for user with unverified email when setting later enabled', async function () { - await updateCustomSubConfig(server.url, server.accessToken, { - signup: { - enabled: true, - requiresEmailVerification: true, - limit: 10 + await server.configCommand.updateCustomSubConfig({ + newConfig: { + signup: { + enabled: true, + requiresEmailVerification: true, + limit: 10 + } } }) diff --git a/server/tests/api/users/users.ts b/server/tests/api/users/users.ts index ba4183e08..33bcc8701 100644 --- a/server/tests/api/users/users.ts +++ b/server/tests/api/users/users.ts @@ -13,7 +13,6 @@ import { flushAndRunServer, getAccountRatings, getBlacklistedVideosList, - getCustomConfig, getMyUserInformation, getMyUserVideoQuotaUsed, getMyUserVideoRating, @@ -38,7 +37,6 @@ import { setTokenField, testImage, unblockUser, - updateCustomSubConfig, updateMyAvatar, updateMyUser, updateUser, @@ -46,7 +44,7 @@ import { userLogin, waitJobs } from '@shared/extra-utils' -import { AbuseState, CustomConfig, MyUser, OAuth2ErrorCode, User, UserAdminFlag, UserRole, Video, VideoPlaylistType } from '@shared/models' +import { AbuseState, MyUser, OAuth2ErrorCode, User, UserAdminFlag, UserRole, Video, VideoPlaylistType } from '@shared/models' const expect = chai.expect @@ -418,12 +416,11 @@ describe('Test users', function () { this.timeout(60000) { - const res = await getCustomConfig(server.url, server.accessToken) - const config = res.body as CustomConfig + const config = await server.configCommand.getCustomConfig() config.transcoding.webtorrent.enabled = false config.transcoding.hls.enabled = true config.transcoding.enabled = true - await updateCustomSubConfig(server.url, server.accessToken, config) + await server.configCommand.updateCustomSubConfig({ newConfig: config }) } { diff --git a/server/tests/api/videos/video-change-ownership.ts b/server/tests/api/videos/video-change-ownership.ts index a3384851b..89dba14b1 100644 --- a/server/tests/api/videos/video-change-ownership.ts +++ b/server/tests/api/videos/video-change-ownership.ts @@ -20,7 +20,6 @@ import { ServerInfo, setAccessTokensToServers, setDefaultVideoChannel, - updateCustomSubConfig, uploadVideo, userLogin } from '../../../../shared/extra-utils' @@ -58,12 +57,14 @@ describe('Test video change ownership - nominal', function () { await setAccessTokensToServers(servers) await setDefaultVideoChannel(servers) - await updateCustomSubConfig(servers[0].url, servers[0].accessToken, { - transcoding: { - enabled: false - }, - live: { - enabled: true + await servers[0].configCommand.updateCustomSubConfig({ + newConfig: { + transcoding: { + enabled: false + }, + live: { + enabled: true + } } }) diff --git a/server/tests/api/videos/video-hls.ts b/server/tests/api/videos/video-hls.ts index 03ac3f321..3821cfed0 100644 --- a/server/tests/api/videos/video-hls.ts +++ b/server/tests/api/videos/video-hls.ts @@ -3,6 +3,7 @@ import 'mocha' import * as chai from 'chai' import { join } from 'path' +import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' import { checkDirectoryIsEmpty, checkResolutionsInMasterPlaylist, @@ -17,7 +18,6 @@ import { removeVideo, ServerInfo, setAccessTokensToServers, - updateCustomSubConfig, updateVideo, uploadVideo, waitJobs, @@ -26,7 +26,6 @@ import { import { VideoDetails } from '../../../../shared/models/videos' import { VideoStreamingPlaylistType } from '../../../../shared/models/videos/video-streaming-playlist.type' import { DEFAULT_AUDIO_RESOLUTION } from '../../../initializers/constants' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' const expect = chai.expect @@ -192,24 +191,26 @@ describe('Test HLS videos', function () { describe('With only HLS enabled', function () { before(async function () { - await updateCustomSubConfig(servers[0].url, servers[0].accessToken, { - transcoding: { - enabled: true, - allowAudioFiles: true, - resolutions: { - '240p': true, - '360p': true, - '480p': true, - '720p': true, - '1080p': true, - '1440p': true, - '2160p': true - }, - hls: { - enabled: true - }, - webtorrent: { - enabled: false + await servers[0].configCommand.updateCustomSubConfig({ + newConfig: { + transcoding: { + enabled: true, + allowAudioFiles: true, + resolutions: { + '240p': true, + '360p': true, + '480p': true, + '720p': true, + '1080p': true, + '1440p': true, + '2160p': true + }, + hls: { + enabled: true + }, + webtorrent: { + enabled: false + } } } }) diff --git a/server/tests/api/videos/video-imports.ts b/server/tests/api/videos/video-imports.ts index 80834ca86..a4a9132b4 100644 --- a/server/tests/api/videos/video-imports.ts +++ b/server/tests/api/videos/video-imports.ts @@ -14,8 +14,7 @@ import { listVideoCaptions, ServerInfo, setAccessTokensToServers, - testCaptionFile, - updateCustomSubConfig + testCaptionFile } from '../../../../shared/extra-utils' import { areHttpImportTestsDisabled, testImage } from '../../../../shared/extra-utils/miscs/miscs' import { waitJobs } from '../../../../shared/extra-utils/server/jobs' @@ -333,7 +332,7 @@ Ajouter un sous-titre est vraiment facile`) } } } - await updateCustomSubConfig(servers[0].url, servers[0].accessToken, config) + await servers[0].configCommand.updateCustomSubConfig({ newConfig: config }) const attributes = { name: 'hdr video', diff --git a/server/tests/api/videos/video-nsfw.ts b/server/tests/api/videos/video-nsfw.ts index 24a4c6152..65813517d 100644 --- a/server/tests/api/videos/video-nsfw.ts +++ b/server/tests/api/videos/video-nsfw.ts @@ -7,8 +7,6 @@ import { createUser, flushAndRunServer, getAccountVideos, - getConfig, - getCustomConfig, getMyUserInformation, getMyVideos, getVideoChannelVideos, @@ -16,12 +14,11 @@ import { getVideosListWithToken, ServerInfo, setAccessTokensToServers, - updateCustomConfig, updateMyUser, uploadVideo, userLogin } from '@shared/extra-utils' -import { BooleanBothQuery, CustomConfig, ServerConfig, User, VideosOverview } from '@shared/models' +import { BooleanBothQuery, CustomConfig, User, VideosOverview } from '@shared/models' const expect = chai.expect @@ -97,16 +94,12 @@ describe('Test video NSFW policy', function () { await uploadVideo(server.url, server.accessToken, attributes) } - { - const res = await getCustomConfig(server.url, server.accessToken) - customConfig = res.body - } + customConfig = await server.configCommand.getCustomConfig() }) describe('Instance default NSFW policy', function () { it('Should display NSFW videos with display default NSFW policy', async function () { - const resConfig = await getConfig(server.url) - const serverConfig: ServerConfig = resConfig.body + const serverConfig = await server.configCommand.getConfig() expect(serverConfig.instance.defaultNSFWPolicy).to.equal('display') for (const res of await getVideosFunctions()) { @@ -121,10 +114,9 @@ describe('Test video NSFW policy', function () { it('Should not display NSFW videos with do_not_list default NSFW policy', async function () { customConfig.instance.defaultNSFWPolicy = 'do_not_list' - await updateCustomConfig(server.url, server.accessToken, customConfig) + await server.configCommand.updateCustomConfig({ newCustomConfig: customConfig }) - const resConfig = await getConfig(server.url) - const serverConfig: ServerConfig = resConfig.body + const serverConfig = await server.configCommand.getConfig() expect(serverConfig.instance.defaultNSFWPolicy).to.equal('do_not_list') for (const res of await getVideosFunctions()) { @@ -138,10 +130,9 @@ describe('Test video NSFW policy', function () { it('Should display NSFW videos with blur default NSFW policy', async function () { customConfig.instance.defaultNSFWPolicy = 'blur' - await updateCustomConfig(server.url, server.accessToken, customConfig) + await server.configCommand.updateCustomConfig({ newCustomConfig: customConfig }) - const resConfig = await getConfig(server.url) - const serverConfig: ServerConfig = resConfig.body + const serverConfig = await server.configCommand.getConfig() expect(serverConfig.instance.defaultNSFWPolicy).to.equal('blur') for (const res of await getVideosFunctions()) { @@ -172,7 +163,7 @@ describe('Test video NSFW policy', function () { it('Should display NSFW videos with blur user NSFW policy', async function () { customConfig.instance.defaultNSFWPolicy = 'do_not_list' - await updateCustomConfig(server.url, server.accessToken, customConfig) + await server.configCommand.updateCustomConfig({ newCustomConfig: customConfig }) for (const res of await getVideosFunctions(userAccessToken)) { expect(res.body.total).to.equal(2) diff --git a/server/tests/api/videos/video-transcoder.ts b/server/tests/api/videos/video-transcoder.ts index c95053a29..e74fb5bef 100644 --- a/server/tests/api/videos/video-transcoder.ts +++ b/server/tests/api/videos/video-transcoder.ts @@ -5,7 +5,6 @@ import * as chai from 'chai' import { FfprobeData } from 'fluent-ffmpeg' import { omit } from 'lodash' import { join } from 'path' -import { Job } from '@shared/models' import { VIDEO_TRANSCODING_FPS } from '../../../../server/initializers/constants' import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' import { @@ -24,7 +23,6 @@ import { makeGetRequest, ServerInfo, setAccessTokensToServers, - updateCustomSubConfig, uploadVideo, uploadVideoAndGetId, waitJobs, @@ -43,22 +41,24 @@ import { const expect = chai.expect function updateConfigForTranscoding (server: ServerInfo) { - return updateCustomSubConfig(server.url, server.accessToken, { - transcoding: { - enabled: true, - allowAdditionalExtensions: true, - allowAudioFiles: true, - hls: { enabled: true }, - webtorrent: { enabled: true }, - resolutions: { - '0p': false, - '240p': true, - '360p': true, - '480p': true, - '720p': true, - '1080p': true, - '1440p': true, - '2160p': true + return server.configCommand.updateCustomSubConfig({ + newConfig: { + transcoding: { + enabled: true, + allowAdditionalExtensions: true, + allowAudioFiles: true, + hls: { enabled: true }, + webtorrent: { enabled: true }, + resolutions: { + '0p': false, + '240p': true, + '360p': true, + '480p': true, + '720p': true, + '1080p': true, + '1440p': true, + '2160p': true + } } } }) @@ -363,19 +363,21 @@ describe('Test video transcoding', function () { function runSuite (mode: 'legacy' | 'resumable') { before(async function () { - await updateCustomSubConfig(servers[1].url, servers[1].accessToken, { - transcoding: { - hls: { enabled: true }, - webtorrent: { enabled: true }, - resolutions: { - '0p': false, - '240p': false, - '360p': false, - '480p': false, - '720p': false, - '1080p': false, - '1440p': false, - '2160p': false + await servers[1].configCommand.updateCustomSubConfig({ + newConfig: { + transcoding: { + hls: { enabled: true }, + webtorrent: { enabled: true }, + resolutions: { + '0p': false, + '240p': false, + '360p': false, + '480p': false, + '720p': false, + '1080p': false, + '1440p': false, + '2160p': false + } } } }) @@ -434,14 +436,16 @@ describe('Test video transcoding', function () { it('Should upload an audio file and create an audio version only', async function () { this.timeout(60_000) - await updateCustomSubConfig(servers[1].url, servers[1].accessToken, { - transcoding: { - hls: { enabled: true }, - webtorrent: { enabled: true }, - resolutions: { - '0p': true, - '240p': false, - '360p': false + await servers[1].configCommand.updateCustomSubConfig({ + newConfig: { + transcoding: { + hls: { enabled: true }, + webtorrent: { enabled: true }, + resolutions: { + '0p': true, + '240p': false, + '360p': false + } } } }) @@ -601,7 +605,7 @@ describe('Test video transcoding', function () { it('Should not transcode to an higher bitrate than the original file', async function () { this.timeout(160_000) - const config = { + const newConfig = { transcoding: { enabled: true, resolutions: { @@ -617,7 +621,7 @@ describe('Test video transcoding', function () { hls: { enabled: true } } } - await updateCustomSubConfig(servers[1].url, servers[1].accessToken, config) + await servers[1].configCommand.updateCustomSubConfig({ newConfig }) const videoAttributes = { name: 'low bitrate', diff --git a/server/tests/cli/create-transcoding-job.ts b/server/tests/cli/create-transcoding-job.ts index be46dec25..e3211882d 100644 --- a/server/tests/cli/create-transcoding-job.ts +++ b/server/tests/cli/create-transcoding-job.ts @@ -10,7 +10,6 @@ import { getVideosList, ServerInfo, setAccessTokensToServers, - updateCustomSubConfig, uploadVideo } from '../../../shared/extra-utils' import { waitJobs } from '../../../shared/extra-utils/server/jobs' @@ -47,7 +46,7 @@ describe('Test create transcoding jobs', function () { servers = await flushAndRunMultipleServers(2) await setAccessTokensToServers(servers) - await updateCustomSubConfig(servers[0].url, servers[0].accessToken, config) + await servers[0].configCommand.updateCustomSubConfig({ newConfig: config }) await doubleFollow(servers[0], servers[1]) @@ -199,7 +198,7 @@ describe('Test create transcoding jobs', function () { this.timeout(120000) config.transcoding.hls.enabled = true - await updateCustomSubConfig(servers[0].url, servers[0].accessToken, config) + await servers[0].configCommand.updateCustomSubConfig({ newConfig: config }) await servers[0].cliCommand.execWithEnv(`npm run create-transcoding-job -- -v ${videosUUID[4]}`) diff --git a/server/tests/cli/plugins.ts b/server/tests/cli/plugins.ts index 7b8746a5d..e5efae36b 100644 --- a/server/tests/cli/plugins.ts +++ b/server/tests/cli/plugins.ts @@ -5,14 +5,12 @@ import { expect } from 'chai' import { cleanupTests, flushAndRunServer, - getConfig, killallServers, PluginsCommand, reRunServer, ServerInfo, setAccessTokensToServers } from '../../../shared/extra-utils' -import { ServerConfig } from '../../../shared/models/server' describe('Test plugin scripts', function () { let server: ServerInfo @@ -44,8 +42,7 @@ describe('Test plugin scripts', function () { killallServers([ server ]) await reRunServer(server) - const res = await getConfig(server.url) - const config: ServerConfig = res.body + const config = await server.configCommand.getConfig() const plugin = config.plugin.registered .find(p => p.name === 'test') @@ -68,8 +65,7 @@ describe('Test plugin scripts', function () { killallServers([ server ]) await reRunServer(server) - const res = await getConfig(server.url) - const config: ServerConfig = res.body + const config = await server.configCommand.getConfig() const plugin = config.plugin.registered .find(p => p.name === 'test') diff --git a/server/tests/client.ts b/server/tests/client.ts index 7c4fb4e46..be7ce18b4 100644 --- a/server/tests/client.ts +++ b/server/tests/client.ts @@ -4,7 +4,7 @@ import 'mocha' import * as chai from 'chai' import { omit } from 'lodash' import { HttpStatusCode } from '@shared/core-utils/miscs/http-error-codes' -import { Account, CustomConfig, HTMLServerConfig, ServerConfig, VideoPlaylistCreateResult, VideoPlaylistPrivacy } from '@shared/models' +import { Account, HTMLServerConfig, ServerConfig, VideoPlaylistCreateResult, VideoPlaylistPrivacy } from '@shared/models' import { addVideoInPlaylist, cleanupTests, @@ -12,16 +12,12 @@ import { doubleFollow, flushAndRunMultipleServers, getAccount, - getConfig, - getCustomConfig, getVideosList, makeGetRequest, makeHTMLRequest, ServerInfo, setAccessTokensToServers, setDefaultVideoChannel, - updateCustomConfig, - updateCustomSubConfig, updateMyUser, updateVideoChannel, uploadVideo, @@ -307,14 +303,13 @@ describe('Test a client controllers', function () { describe('Whitelisted', function () { before(async function () { - const res = await getCustomConfig(servers[0].url, servers[0].accessToken) - const config = res.body as CustomConfig + const config = await servers[0].configCommand.getCustomConfig() config.services.twitter = { username: '@Kuja', whitelisted: true } - await updateCustomConfig(servers[0].url, servers[0].accessToken, config) + await servers[0].configCommand.updateCustomConfig({ newCustomConfig: config }) }) async function accountPageTest (path: string) { @@ -382,40 +377,42 @@ describe('Test a client controllers', function () { describe('Index HTML', function () { it('Should have valid index html tags (title, description...)', async function () { - const resConfig = await getConfig(servers[0].url) + const config = await servers[0].configCommand.getConfig() const res = await makeHTMLRequest(servers[0].url, '/videos/trending') const description = 'PeerTube, an ActivityPub-federated video streaming platform using P2P directly in your web browser.' - checkIndexTags(res.text, 'PeerTube', description, '', resConfig.body) + checkIndexTags(res.text, 'PeerTube', description, '', config) }) it('Should update the customized configuration and have the correct index html tags', async function () { - await updateCustomSubConfig(servers[0].url, servers[0].accessToken, { - instance: { - name: 'PeerTube updated', - shortDescription: 'my short description', - description: 'my super description', - terms: 'my super terms', - defaultNSFWPolicy: 'blur', - defaultClientRoute: '/videos/recently-added', - customizations: { - javascript: 'alert("coucou")', - css: 'body { background-color: red; }' + await servers[0].configCommand.updateCustomSubConfig({ + newConfig: { + instance: { + name: 'PeerTube updated', + shortDescription: 'my short description', + description: 'my super description', + terms: 'my super terms', + defaultNSFWPolicy: 'blur', + defaultClientRoute: '/videos/recently-added', + customizations: { + javascript: 'alert("coucou")', + css: 'body { background-color: red; }' + } } } }) - const resConfig = await getConfig(servers[0].url) + const config = await servers[0].configCommand.getConfig() const res = await makeHTMLRequest(servers[0].url, '/videos/trending') - checkIndexTags(res.text, 'PeerTube updated', 'my short description', 'body { background-color: red; }', resConfig.body) + checkIndexTags(res.text, 'PeerTube updated', 'my short description', 'body { background-color: red; }', config) }) it('Should have valid index html updated tags (title, description...)', async function () { - const resConfig = await getConfig(servers[0].url) + const config = await servers[0].configCommand.getConfig() const res = await makeHTMLRequest(servers[0].url, '/videos/trending') - checkIndexTags(res.text, 'PeerTube updated', 'my short description', 'body { background-color: red; }', resConfig.body) + checkIndexTags(res.text, 'PeerTube updated', 'my short description', 'body { background-color: red; }', config) }) it('Should use the original video URL for the canonical tag', async function () { @@ -428,7 +425,7 @@ describe('Test a client controllers', function () { }) it('Should use the original account URL for the canonical tag', async function () { - const accountURLtest = (res) => { + const accountURLtest = res => { expect(res.text).to.contain(``) } @@ -438,7 +435,7 @@ describe('Test a client controllers', function () { }) it('Should use the original channel URL for the canonical tag', async function () { - const channelURLtests = (res) => { + const channelURLtests = res => { expect(res.text).to.contain(``) } @@ -460,10 +457,10 @@ describe('Test a client controllers', function () { describe('Embed HTML', function () { it('Should have the correct embed html tags', async function () { - const resConfig = await getConfig(servers[0].url) + const config = await servers[0].configCommand.getConfig() const res = await makeHTMLRequest(servers[0].url, servers[0].video.embedPath) - checkIndexTags(res.text, 'PeerTube updated', 'my short description', 'body { background-color: red; }', resConfig.body) + checkIndexTags(res.text, 'PeerTube updated', 'my short description', 'body { background-color: red; }', config) }) }) diff --git a/server/tests/plugins/external-auth.ts b/server/tests/plugins/external-auth.ts index 424302786..09a107ca2 100644 --- a/server/tests/plugins/external-auth.ts +++ b/server/tests/plugins/external-auth.ts @@ -8,7 +8,6 @@ import { createUser, decodeQueryString, flushAndRunServer, - getConfig, getMyUserInformation, loginUsingExternalToken, logout, @@ -21,7 +20,7 @@ import { wait, waitUntilLog } from '@shared/extra-utils' -import { ServerConfig, User, UserRole } from '@shared/models' +import { User, UserRole } from '@shared/models' async function loginExternal (options: { server: ServerInfo @@ -78,9 +77,7 @@ describe('Test external auth plugins', function () { }) it('Should display the correct configuration', async function () { - const res = await getConfig(server.url) - - const config: ServerConfig = res.body + const config = await server.configCommand.getConfig() const auths = config.plugin.registeredExternalAuths expect(auths).to.have.lengthOf(8) @@ -288,9 +285,7 @@ describe('Test external auth plugins', function () { }) it('Should have disabled this auth', async function () { - const res = await getConfig(server.url) - - const config: ServerConfig = res.body + const config = await server.configCommand.getConfig() const auths = config.plugin.registeredExternalAuths expect(auths).to.have.lengthOf(7) @@ -354,9 +349,7 @@ describe('Test external auth plugins', function () { }) it('Should display the correct configuration', async function () { - const res = await getConfig(server.url) - - const config: ServerConfig = res.body + const config = await server.configCommand.getConfig() const auths = config.plugin.registeredExternalAuths expect(auths).to.have.lengthOf(6) diff --git a/server/tests/plugins/filter-hooks.ts b/server/tests/plugins/filter-hooks.ts index c51e96ab7..e254046bf 100644 --- a/server/tests/plugins/filter-hooks.ts +++ b/server/tests/plugins/filter-hooks.ts @@ -12,7 +12,6 @@ import { doubleFollow, flushAndRunMultipleServers, getAccountVideos, - getConfig, getMyVideos, getVideo, getVideoChannelVideos, @@ -28,7 +27,6 @@ import { ServerInfo, setAccessTokensToServers, setDefaultVideoChannel, - updateCustomSubConfig, updateVideo, uploadVideo, uploadVideoAndGetId, @@ -37,7 +35,6 @@ import { } from '@shared/extra-utils' import { getGoodVideoUrl, getMyVideoImports, importVideo } from '@shared/extra-utils/videos/video-imports' import { - ServerConfig, VideoCommentThreadTree, VideoDetails, VideoImport, @@ -72,13 +69,15 @@ describe('Test plugin filter hooks', function () { const res = await getVideosList(servers[0].url) videoUUID = res.body.data[0].uuid - await updateCustomSubConfig(servers[0].url, servers[0].accessToken, { - live: { enabled: true }, - signup: { enabled: true }, - import: { - videos: { - http: { enabled: true }, - torrent: { enabled: true } + await servers[0].configCommand.updateCustomSubConfig({ + newConfig: { + live: { enabled: true }, + signup: { enabled: true }, + import: { + videos: { + http: { enabled: true }, + torrent: { enabled: true } + } } } }) @@ -344,8 +343,8 @@ describe('Test plugin filter hooks', function () { describe('Should run filter:api.user.signup.allowed.result', function () { it('Should run on config endpoint', async function () { - const res = await getConfig(servers[0].url) - expect((res.body as ServerConfig).signup.allowed).to.be.true + const body = await servers[0].configCommand.getConfig() + expect(body.signup.allowed).to.be.true }) it('Should allow a signup', async function () { @@ -365,13 +364,15 @@ describe('Test plugin filter hooks', function () { before(async function () { this.timeout(120000) - await updateCustomSubConfig(servers[0].url, servers[0].accessToken, { - transcoding: { - webtorrent: { - enabled: true - }, - hls: { - enabled: true + await servers[0].configCommand.updateCustomSubConfig({ + newConfig: { + transcoding: { + webtorrent: { + enabled: true + }, + hls: { + enabled: true + } } } }) @@ -427,9 +428,11 @@ describe('Test plugin filter hooks', function () { before(async function () { this.timeout(60000) - await updateCustomSubConfig(servers[0].url, servers[0].accessToken, { - transcoding: { - enabled: false + await servers[0].configCommand.updateCustomSubConfig({ + newConfig: { + transcoding: { + enabled: false + } } }) @@ -464,12 +467,14 @@ describe('Test plugin filter hooks', function () { describe('Search filters', function () { before(async function () { - await updateCustomSubConfig(servers[0].url, servers[0].accessToken, { - search: { - searchIndex: { - enabled: true, - isDefaultSearch: false, - disableLocalSearch: false + await servers[0].configCommand.updateCustomSubConfig({ + newConfig: { + search: { + searchIndex: { + enabled: true, + isDefaultSearch: false, + disableLocalSearch: false + } } } }) diff --git a/server/tests/plugins/id-and-pass-auth.ts b/server/tests/plugins/id-and-pass-auth.ts index 545968040..99de28d3f 100644 --- a/server/tests/plugins/id-and-pass-auth.ts +++ b/server/tests/plugins/id-and-pass-auth.ts @@ -5,7 +5,6 @@ import { expect } from 'chai' import { cleanupTests, flushAndRunServer, - getConfig, getMyUserInformation, getUsersList, login, @@ -19,7 +18,7 @@ import { wait, waitUntilLog } from '@shared/extra-utils' -import { ServerConfig, User, UserRole } from '@shared/models' +import { User, UserRole } from '@shared/models' describe('Test id and pass auth plugins', function () { let server: ServerInfo @@ -42,9 +41,7 @@ describe('Test id and pass auth plugins', function () { }) it('Should display the correct configuration', async function () { - const res = await getConfig(server.url) - - const config: ServerConfig = res.body + const config = await server.configCommand.getConfig() const auths = config.plugin.registeredIdAndPassAuths expect(auths).to.have.lengthOf(8) @@ -190,9 +187,7 @@ describe('Test id and pass auth plugins', function () { }) it('Should have disabled this auth', async function () { - const res = await getConfig(server.url) - - const config: ServerConfig = res.body + const config = await server.configCommand.getConfig() const auths = config.plugin.registeredIdAndPassAuths expect(auths).to.have.lengthOf(7) @@ -208,9 +203,7 @@ describe('Test id and pass auth plugins', function () { }) it('Should display the correct configuration', async function () { - const res = await getConfig(server.url) - - const config: ServerConfig = res.body + const config = await server.configCommand.getConfig() const auths = config.plugin.registeredIdAndPassAuths expect(auths).to.have.lengthOf(6) diff --git a/server/tests/plugins/plugin-transcoding.ts b/server/tests/plugins/plugin-transcoding.ts index f1ff91077..71c2adc72 100644 --- a/server/tests/plugins/plugin-transcoding.ts +++ b/server/tests/plugins/plugin-transcoding.ts @@ -9,7 +9,6 @@ import { cleanupTests, createLive, flushAndRunServer, - getConfig, getVideo, PluginsCommand, sendRTMPStreamInVideo, @@ -17,12 +16,11 @@ import { setAccessTokensToServers, setDefaultVideoChannel, testFfmpegStreamError, - updateCustomSubConfig, uploadVideoAndGetId, waitJobs, waitUntilLivePublished } from '@shared/extra-utils' -import { ServerConfig, VideoDetails, VideoPrivacy } from '@shared/models' +import { VideoDetails, VideoPrivacy } from '@shared/models' async function createLiveWrapper (server: ServerInfo) { const liveAttributes = { @@ -36,33 +34,35 @@ async function createLiveWrapper (server: ServerInfo) { } function updateConf (server: ServerInfo, vodProfile: string, liveProfile: string) { - return updateCustomSubConfig(server.url, server.accessToken, { - transcoding: { - enabled: true, - profile: vodProfile, - hls: { - enabled: true - }, - webtorrent: { - enabled: true - }, - resolutions: { - '240p': true, - '360p': false, - '480p': false, - '720p': true - } - }, - live: { + return server.configCommand.updateCustomSubConfig({ + newConfig: { transcoding: { - profile: liveProfile, enabled: true, + profile: vodProfile, + hls: { + enabled: true + }, + webtorrent: { + enabled: true + }, resolutions: { '240p': true, '360p': false, '480p': false, '720p': true } + }, + live: { + transcoding: { + profile: liveProfile, + enabled: true, + resolutions: { + '240p': true, + '360p': false, + '480p': false, + '720p': true + } + } } } }) @@ -113,8 +113,7 @@ describe('Test transcoding plugins', function () { }) it('Should have the appropriate available profiles', async function () { - const res = await getConfig(server.url) - const config = res.body as ServerConfig + const config = await server.configCommand.getConfig() expect(config.transcoding.availableProfiles).to.have.members([ 'default', 'low-vod', 'input-options-vod', 'bad-scale-vod' ]) expect(config.live.transcoding.availableProfiles).to.have.members([ 'default', 'low-live', 'input-options-live', 'bad-scale-live' ]) @@ -223,8 +222,7 @@ describe('Test transcoding plugins', function () { await server.pluginsCommand.uninstall({ npmName: 'peertube-plugin-test-transcoding-one' }) - const res = await getConfig(server.url) - const config = res.body as ServerConfig + const config = await server.configCommand.getConfig() expect(config.transcoding.availableProfiles).to.deep.equal([ 'default' ]) expect(config.live.transcoding.availableProfiles).to.deep.equal([ 'default' ]) diff --git a/shared/extra-utils/server/config-command.ts b/shared/extra-utils/server/config-command.ts new file mode 100644 index 000000000..959848706 --- /dev/null +++ b/shared/extra-utils/server/config-command.ts @@ -0,0 +1,260 @@ +import { merge } from 'lodash' +import { DeepPartial, HttpStatusCode } from '@shared/core-utils' +import { About, ServerConfig } from '@shared/models' +import { CustomConfig } from '../../models/server/custom-config.model' +import { AbstractCommand, OverrideCommandOptions } from '../shared' + +export class ConfigCommand extends AbstractCommand { + + static getCustomConfigResolutions (enabled: boolean) { + return { + '240p': enabled, + '360p': enabled, + '480p': enabled, + '720p': enabled, + '1080p': enabled, + '1440p': enabled, + '2160p': enabled + } + } + + getConfig (options: OverrideCommandOptions = {}) { + const path = '/api/v1/config' + + return this.getRequestBody({ + ...options, + + token: null, + path, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } + + getAbout (options: OverrideCommandOptions = {}) { + const path = '/api/v1/config/about' + + return this.getRequestBody({ + ...options, + + token: null, + path, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } + + getCustomConfig (options: OverrideCommandOptions = {}) { + const path = '/api/v1/config/custom' + + return this.getRequestBody({ + ...options, + + path, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } + + updateCustomConfig (options: OverrideCommandOptions & { + newCustomConfig: CustomConfig + }) { + const path = '/api/v1/config/custom' + + return this.putBodyRequest({ + ...options, + + path, + fields: options.newCustomConfig, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } + + deleteCustomConfig (options: OverrideCommandOptions = {}) { + const path = '/api/v1/config/custom' + + return this.deleteRequest({ + ...options, + + path, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } + + updateCustomSubConfig (options: OverrideCommandOptions & { + newConfig: DeepPartial + }) { + const newCustomConfig: CustomConfig = { + instance: { + name: 'PeerTube updated', + shortDescription: 'my short description', + description: 'my super description', + terms: 'my super terms', + codeOfConduct: 'my super coc', + + creationReason: 'my super creation reason', + moderationInformation: 'my super moderation information', + administrator: 'Kuja', + maintenanceLifetime: 'forever', + businessModel: 'my super business model', + hardwareInformation: '2vCore 3GB RAM', + + languages: [ 'en', 'es' ], + categories: [ 1, 2 ], + + isNSFW: true, + defaultNSFWPolicy: 'blur', + + defaultClientRoute: '/videos/recently-added', + + customizations: { + javascript: 'alert("coucou")', + css: 'body { background-color: red; }' + } + }, + theme: { + default: 'default' + }, + services: { + twitter: { + username: '@MySuperUsername', + whitelisted: true + } + }, + cache: { + previews: { + size: 2 + }, + captions: { + size: 3 + }, + torrents: { + size: 4 + } + }, + signup: { + enabled: false, + limit: 5, + requiresEmailVerification: false, + minimumAge: 16 + }, + admin: { + email: 'superadmin1@example.com' + }, + contactForm: { + enabled: true + }, + user: { + videoQuota: 5242881, + videoQuotaDaily: 318742 + }, + transcoding: { + enabled: true, + allowAdditionalExtensions: true, + allowAudioFiles: true, + threads: 1, + concurrency: 3, + profile: 'default', + resolutions: { + '0p': false, + '240p': false, + '360p': true, + '480p': true, + '720p': false, + '1080p': false, + '1440p': false, + '2160p': false + }, + webtorrent: { + enabled: true + }, + hls: { + enabled: false + } + }, + live: { + enabled: true, + allowReplay: false, + maxDuration: -1, + maxInstanceLives: -1, + maxUserLives: 50, + transcoding: { + enabled: true, + threads: 4, + profile: 'default', + resolutions: { + '240p': true, + '360p': true, + '480p': true, + '720p': true, + '1080p': true, + '1440p': true, + '2160p': true + } + } + }, + import: { + videos: { + concurrency: 3, + http: { + enabled: false + }, + torrent: { + enabled: false + } + } + }, + trending: { + videos: { + algorithms: { + enabled: [ 'best', 'hot', 'most-viewed', 'most-liked' ], + default: 'hot' + } + } + }, + autoBlacklist: { + videos: { + ofUsers: { + enabled: false + } + } + }, + followers: { + instance: { + enabled: true, + manualApproval: false + } + }, + followings: { + instance: { + autoFollowBack: { + enabled: false + }, + autoFollowIndex: { + indexUrl: 'https://instances.joinpeertube.org/api/v1/instances/hosts', + enabled: false + } + } + }, + broadcastMessage: { + enabled: true, + level: 'warning', + message: 'hello', + dismissable: true + }, + search: { + remoteUri: { + users: true, + anonymous: true + }, + searchIndex: { + enabled: true, + url: 'https://search.joinpeertube.org', + disableLocalSearch: true, + isDefaultSearch: true + } + } + } + + merge(newCustomConfig, options.newConfig) + + return this.updateCustomConfig({ ...options, newCustomConfig }) + } +} diff --git a/shared/extra-utils/server/config.ts b/shared/extra-utils/server/config.ts deleted file mode 100644 index 9fcfb31fd..000000000 --- a/shared/extra-utils/server/config.ts +++ /dev/null @@ -1,260 +0,0 @@ -import { makeDeleteRequest, makeGetRequest, makePutBodyRequest } from '../requests/requests' -import { CustomConfig } from '../../models/server/custom-config.model' -import { DeepPartial, HttpStatusCode } from '@shared/core-utils' -import { merge } from 'lodash' - -function getConfig (url: string) { - const path = '/api/v1/config' - - return makeGetRequest({ - url, - path, - statusCodeExpected: HttpStatusCode.OK_200 - }) -} - -function getAbout (url: string) { - const path = '/api/v1/config/about' - - return makeGetRequest({ - url, - path, - statusCodeExpected: HttpStatusCode.OK_200 - }) -} - -function getCustomConfig (url: string, token: string, statusCodeExpected = HttpStatusCode.OK_200) { - const path = '/api/v1/config/custom' - - return makeGetRequest({ - url, - token, - path, - statusCodeExpected - }) -} - -function updateCustomConfig (url: string, token: string, newCustomConfig: CustomConfig, statusCodeExpected = HttpStatusCode.OK_200) { - const path = '/api/v1/config/custom' - - return makePutBodyRequest({ - url, - token, - path, - fields: newCustomConfig, - statusCodeExpected - }) -} - -function updateCustomSubConfig (url: string, token: string, newConfig: DeepPartial) { - const updateParams: CustomConfig = { - instance: { - name: 'PeerTube updated', - shortDescription: 'my short description', - description: 'my super description', - terms: 'my super terms', - codeOfConduct: 'my super coc', - - creationReason: 'my super creation reason', - moderationInformation: 'my super moderation information', - administrator: 'Kuja', - maintenanceLifetime: 'forever', - businessModel: 'my super business model', - hardwareInformation: '2vCore 3GB RAM', - - languages: [ 'en', 'es' ], - categories: [ 1, 2 ], - - isNSFW: true, - defaultNSFWPolicy: 'blur', - - defaultClientRoute: '/videos/recently-added', - - customizations: { - javascript: 'alert("coucou")', - css: 'body { background-color: red; }' - } - }, - theme: { - default: 'default' - }, - services: { - twitter: { - username: '@MySuperUsername', - whitelisted: true - } - }, - cache: { - previews: { - size: 2 - }, - captions: { - size: 3 - }, - torrents: { - size: 4 - } - }, - signup: { - enabled: false, - limit: 5, - requiresEmailVerification: false, - minimumAge: 16 - }, - admin: { - email: 'superadmin1@example.com' - }, - contactForm: { - enabled: true - }, - user: { - videoQuota: 5242881, - videoQuotaDaily: 318742 - }, - transcoding: { - enabled: true, - allowAdditionalExtensions: true, - allowAudioFiles: true, - threads: 1, - concurrency: 3, - profile: 'default', - resolutions: { - '0p': false, - '240p': false, - '360p': true, - '480p': true, - '720p': false, - '1080p': false, - '1440p': false, - '2160p': false - }, - webtorrent: { - enabled: true - }, - hls: { - enabled: false - } - }, - live: { - enabled: true, - allowReplay: false, - maxDuration: -1, - maxInstanceLives: -1, - maxUserLives: 50, - transcoding: { - enabled: true, - threads: 4, - profile: 'default', - resolutions: { - '240p': true, - '360p': true, - '480p': true, - '720p': true, - '1080p': true, - '1440p': true, - '2160p': true - } - } - }, - import: { - videos: { - concurrency: 3, - http: { - enabled: false - }, - torrent: { - enabled: false - } - } - }, - trending: { - videos: { - algorithms: { - enabled: [ 'best', 'hot', 'most-viewed', 'most-liked' ], - default: 'hot' - } - } - }, - autoBlacklist: { - videos: { - ofUsers: { - enabled: false - } - } - }, - followers: { - instance: { - enabled: true, - manualApproval: false - } - }, - followings: { - instance: { - autoFollowBack: { - enabled: false - }, - autoFollowIndex: { - indexUrl: 'https://instances.joinpeertube.org/api/v1/instances/hosts', - enabled: false - } - } - }, - broadcastMessage: { - enabled: true, - level: 'warning', - message: 'hello', - dismissable: true - }, - search: { - remoteUri: { - users: true, - anonymous: true - }, - searchIndex: { - enabled: true, - url: 'https://search.joinpeertube.org', - disableLocalSearch: true, - isDefaultSearch: true - } - } - } - - merge(updateParams, newConfig) - - return updateCustomConfig(url, token, updateParams) -} - -function getCustomConfigResolutions (enabled: boolean) { - return { - '240p': enabled, - '360p': enabled, - '480p': enabled, - '720p': enabled, - '1080p': enabled, - '1440p': enabled, - '2160p': enabled - } -} - -function deleteCustomConfig (url: string, token: string, statusCodeExpected = HttpStatusCode.OK_200) { - const path = '/api/v1/config/custom' - - return makeDeleteRequest({ - url, - token, - path, - statusCodeExpected - }) -} - -// --------------------------------------------------------------------------- - -export { - getConfig, - getCustomConfig, - updateCustomConfig, - getAbout, - deleteCustomConfig, - updateCustomSubConfig, - getCustomConfigResolutions -} diff --git a/shared/extra-utils/server/index.ts b/shared/extra-utils/server/index.ts index d37f46321..03c3b0123 100644 --- a/shared/extra-utils/server/index.ts +++ b/shared/extra-utils/server/index.ts @@ -1,4 +1,4 @@ -export * from './config' +export * from './config-command' export * from './contact-form-command' export * from './debug-command' export * from './follows-command' diff --git a/shared/extra-utils/server/servers.ts b/shared/extra-utils/server/servers.ts index 4603cf62e..c33b68316 100644 --- a/shared/extra-utils/server/servers.ts +++ b/shared/extra-utils/server/servers.ts @@ -16,6 +16,7 @@ import { AbusesCommand } from '../moderation' import { OverviewsCommand } from '../overviews' import { makeGetRequest } from '../requests/requests' import { SearchCommand } from '../search' +import { ConfigCommand } from './config-command' import { ContactFormCommand } from './contact-form-command' import { DebugCommand } from './debug-command' import { FollowsCommand } from './follows-command' @@ -91,6 +92,7 @@ interface ServerInfo { pluginsCommand?: PluginsCommand redundancyCommand?: RedundancyCommand statsCommand?: StatsCommand + configCommand?: ConfigCommand } function parallelTests () { @@ -311,6 +313,7 @@ async function runServer (server: ServerInfo, configOverrideArg?: any, args = [] server.pluginsCommand = new PluginsCommand(server) server.redundancyCommand = new RedundancyCommand(server) server.statsCommand = new StatsCommand(server) + server.configCommand = new ConfigCommand(server) res(server) }) -- cgit v1.2.3 From 87e2635a50ac2decb1c330e55c2ff7b6d07a85de Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Wed, 7 Jul 2021 11:55:16 +0200 Subject: Introduce socket io command --- server/tests/api/live/live-socket-messages.ts | 11 +++++------ shared/extra-utils/index.ts | 1 + shared/extra-utils/server/servers.ts | 3 +++ shared/extra-utils/socket/index.ts | 1 + shared/extra-utils/socket/socket-io-command.ts | 15 +++++++++++++++ shared/extra-utils/socket/socket-io.ts | 18 ------------------ shared/extra-utils/users/user-notifications.ts | 7 +++---- 7 files changed, 28 insertions(+), 28 deletions(-) create mode 100644 shared/extra-utils/socket/index.ts create mode 100644 shared/extra-utils/socket/socket-io-command.ts delete mode 100644 shared/extra-utils/socket/socket-io.ts diff --git a/server/tests/api/live/live-socket-messages.ts b/server/tests/api/live/live-socket-messages.ts index 0159d5199..20fec16a9 100644 --- a/server/tests/api/live/live-socket-messages.ts +++ b/server/tests/api/live/live-socket-messages.ts @@ -2,7 +2,6 @@ import 'mocha' import * as chai from 'chai' -import { getLiveNotificationSocket } from '@shared/extra-utils/socket/socket-io' import { VideoPrivacy, VideoState } from '@shared/models' import { cleanupTests, @@ -77,7 +76,7 @@ describe('Test live', function () { { const videoId = await getVideoIdFromUUID(servers[0].url, liveVideoUUID) - const localSocket = getLiveNotificationSocket(servers[0].url) + const localSocket = servers[0].socketIOCommand.getLiveNotificationSocket() localSocket.on('state-change', data => localStateChanges.push(data.state)) localSocket.emit('subscribe', { videoId }) } @@ -85,7 +84,7 @@ describe('Test live', function () { { const videoId = await getVideoIdFromUUID(servers[1].url, liveVideoUUID) - const remoteSocket = getLiveNotificationSocket(servers[1].url) + const remoteSocket = servers[1].socketIOCommand.getLiveNotificationSocket() remoteSocket.on('state-change', data => remoteStateChanges.push(data.state)) remoteSocket.emit('subscribe', { videoId }) } @@ -125,7 +124,7 @@ describe('Test live', function () { { const videoId = await getVideoIdFromUUID(servers[0].url, liveVideoUUID) - const localSocket = getLiveNotificationSocket(servers[0].url) + const localSocket = servers[0].socketIOCommand.getLiveNotificationSocket() localSocket.on('views-change', data => { localLastVideoViews = data.views }) localSocket.emit('subscribe', { videoId }) } @@ -133,7 +132,7 @@ describe('Test live', function () { { const videoId = await getVideoIdFromUUID(servers[1].url, liveVideoUUID) - const remoteSocket = getLiveNotificationSocket(servers[1].url) + const remoteSocket = servers[1].socketIOCommand.getLiveNotificationSocket() remoteSocket.on('views-change', data => { remoteLastVideoViews = data.views }) remoteSocket.emit('subscribe', { videoId }) } @@ -169,7 +168,7 @@ describe('Test live', function () { const videoId = await getVideoIdFromUUID(servers[0].url, liveVideoUUID) - const socket = getLiveNotificationSocket(servers[0].url) + const socket = servers[0].socketIOCommand.getLiveNotificationSocket() socket.on('state-change', data => stateChanges.push(data.state)) socket.emit('subscribe', { videoId }) diff --git a/shared/extra-utils/index.ts b/shared/extra-utils/index.ts index f69d7241e..ed7d7ab04 100644 --- a/shared/extra-utils/index.ts +++ b/shared/extra-utils/index.ts @@ -9,6 +9,7 @@ export * from './moderation' export * from './overviews' export * from './search' export * from './server' +export * from './socket' export * from './requests/check-api-params' export * from './requests/requests' diff --git a/shared/extra-utils/server/servers.ts b/shared/extra-utils/server/servers.ts index c33b68316..8bd4446be 100644 --- a/shared/extra-utils/server/servers.ts +++ b/shared/extra-utils/server/servers.ts @@ -16,6 +16,7 @@ import { AbusesCommand } from '../moderation' import { OverviewsCommand } from '../overviews' import { makeGetRequest } from '../requests/requests' import { SearchCommand } from '../search' +import { SocketIOCommand } from '../socket' import { ConfigCommand } from './config-command' import { ContactFormCommand } from './contact-form-command' import { DebugCommand } from './debug-command' @@ -93,6 +94,7 @@ interface ServerInfo { redundancyCommand?: RedundancyCommand statsCommand?: StatsCommand configCommand?: ConfigCommand + socketIOCommand?: SocketIOCommand } function parallelTests () { @@ -314,6 +316,7 @@ async function runServer (server: ServerInfo, configOverrideArg?: any, args = [] server.redundancyCommand = new RedundancyCommand(server) server.statsCommand = new StatsCommand(server) server.configCommand = new ConfigCommand(server) + server.socketIOCommand = new SocketIOCommand(server) res(server) }) diff --git a/shared/extra-utils/socket/index.ts b/shared/extra-utils/socket/index.ts new file mode 100644 index 000000000..594329b2f --- /dev/null +++ b/shared/extra-utils/socket/index.ts @@ -0,0 +1 @@ +export * from './socket-io-command' diff --git a/shared/extra-utils/socket/socket-io-command.ts b/shared/extra-utils/socket/socket-io-command.ts new file mode 100644 index 000000000..545561bed --- /dev/null +++ b/shared/extra-utils/socket/socket-io-command.ts @@ -0,0 +1,15 @@ +import { io } from 'socket.io-client' +import { AbstractCommand, OverrideCommandOptions } from '../shared' + +export class SocketIOCommand extends AbstractCommand { + + getUserNotificationSocket (options: OverrideCommandOptions = {}) { + return io(this.server.url + '/user-notifications', { + query: { accessToken: this.server.accessToken } + }) + } + + getLiveNotificationSocket () { + return io(this.server.url + '/live-videos') + } +} diff --git a/shared/extra-utils/socket/socket-io.ts b/shared/extra-utils/socket/socket-io.ts deleted file mode 100644 index 4ca93f453..000000000 --- a/shared/extra-utils/socket/socket-io.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { io } from 'socket.io-client' - -function getUserNotificationSocket (serverUrl: string, accessToken: string) { - return io(serverUrl + '/user-notifications', { - query: { accessToken } - }) -} - -function getLiveNotificationSocket (serverUrl: string) { - return io(serverUrl + '/live-videos') -} - -// --------------------------------------------------------------------------- - -export { - getUserNotificationSocket, - getLiveNotificationSocket -} diff --git a/shared/extra-utils/users/user-notifications.ts b/shared/extra-utils/users/user-notifications.ts index e75946eec..961cfcc0f 100644 --- a/shared/extra-utils/users/user-notifications.ts +++ b/shared/extra-utils/users/user-notifications.ts @@ -9,7 +9,6 @@ import { MockSmtpServer } from '../mock-servers/mock-email' import { makeGetRequest, makePostBodyRequest, makePutBodyRequest } from '../requests/requests' import { doubleFollow } from '../server/follows' import { flushAndRunMultipleServers, ServerInfo } from '../server/servers' -import { getUserNotificationSocket } from '../socket/socket-io' import { setAccessTokensToServers, userLogin } from './login' import { createUser, getMyUserInformation } from './users' @@ -748,16 +747,16 @@ async function prepareNotificationsTest (serversCount = 3, overrideConfigArg: an } { - const socket = getUserNotificationSocket(servers[0].url, userAccessToken) + const socket = servers[0].socketIOCommand.getUserNotificationSocket({ token: userAccessToken }) socket.on('new-notification', n => userNotifications.push(n)) } { - const socket = getUserNotificationSocket(servers[0].url, servers[0].accessToken) + const socket = servers[0].socketIOCommand.getUserNotificationSocket() socket.on('new-notification', n => adminNotifications.push(n)) } if (serversCount > 1) { - const socket = getUserNotificationSocket(servers[1].url, servers[1].accessToken) + const socket = servers[1].socketIOCommand.getUserNotificationSocket() socket.on('new-notification', n => adminNotificationsServer2.push(n)) } -- cgit v1.2.3 From 9fff08cf83f34339df7ed4ac770e1dee536adf9d Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Wed, 7 Jul 2021 13:38:26 +0200 Subject: Introduce accounts command --- server/tests/api/activitypub/refresher.ts | 20 +++--- server/tests/api/check-params/accounts.ts | 15 ++-- server/tests/api/moderation/abuses.ts | 13 ++-- .../api/notifications/moderation-notifications.ts | 5 +- server/tests/api/server/follows.ts | 40 +++++------ server/tests/api/users/users-multiple-servers.ts | 37 +++++----- server/tests/api/users/users.ts | 20 +++--- server/tests/cli/prune-storage.ts | 17 ++--- server/tests/cli/update-host.ts | 18 +++-- server/tests/client.ts | 4 +- shared/extra-utils/index.ts | 8 +-- shared/extra-utils/server/servers.ts | 3 + shared/extra-utils/users/accounts-command.ts | 54 ++++++++++++++ shared/extra-utils/users/accounts.ts | 83 ++++++---------------- shared/extra-utils/users/index.ts | 8 +++ 15 files changed, 175 insertions(+), 170 deletions(-) create mode 100644 shared/extra-utils/users/accounts-command.ts create mode 100644 shared/extra-utils/users/index.ts diff --git a/server/tests/api/activitypub/refresher.ts b/server/tests/api/activitypub/refresher.ts index c717f1a30..0d5452ea4 100644 --- a/server/tests/api/activitypub/refresher.ts +++ b/server/tests/api/activitypub/refresher.ts @@ -1,8 +1,10 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ import 'mocha' +import { HttpStatusCode } from '@shared/core-utils' import { - cleanupTests, closeAllSequelize, + cleanupTests, + closeAllSequelize, createVideoPlaylist, doubleFollow, flushAndRunMultipleServers, @@ -21,10 +23,8 @@ import { uploadVideoAndGetId, wait, waitJobs -} from '../../../../shared/extra-utils' -import { getAccount } from '../../../../shared/extra-utils/users/accounts' -import { VideoPlaylistPrivacy } from '../../../../shared/models/videos' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' +} from '@shared/extra-utils' +import { VideoPlaylistPrivacy } from '@shared/models' describe('Test AP refresher', function () { let servers: ServerInfo[] = [] @@ -116,19 +116,21 @@ describe('Test AP refresher', function () { it('Should remove a deleted actor', async function () { this.timeout(60000) + const command = servers[0].accountsCommand + await wait(10000) // Change actor name so the remote server returns a 404 const to = 'http://localhost:' + servers[1].port + '/accounts/user2' await setActorField(servers[1].internalServerNumber, to, 'preferredUsername', 'toto') - await getAccount(servers[0].url, 'user1@localhost:' + servers[1].port) - await getAccount(servers[0].url, 'user2@localhost:' + servers[1].port) + await command.get({ accountName: 'user1@localhost:' + servers[1].port }) + await command.get({ accountName: 'user2@localhost:' + servers[1].port }) await waitJobs(servers) - await getAccount(servers[0].url, 'user1@localhost:' + servers[1].port, HttpStatusCode.OK_200) - await getAccount(servers[0].url, 'user2@localhost:' + servers[1].port, HttpStatusCode.NOT_FOUND_404) + await command.get({ accountName: 'user1@localhost:' + servers[1].port, expectedStatus: HttpStatusCode.OK_200 }) + await command.get({ accountName: 'user2@localhost:' + servers[1].port, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) }) diff --git a/server/tests/api/check-params/accounts.ts b/server/tests/api/check-params/accounts.ts index d1712cff6..45d440c47 100644 --- a/server/tests/api/check-params/accounts.ts +++ b/server/tests/api/check-params/accounts.ts @@ -1,15 +1,15 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ import 'mocha' - -import { cleanupTests, flushAndRunServer, ServerInfo } from '../../../../shared/extra-utils' +import { HttpStatusCode } from '@shared/core-utils' import { checkBadCountPagination, checkBadSortPagination, - checkBadStartPagination -} from '../../../../shared/extra-utils/requests/check-api-params' -import { getAccount } from '../../../../shared/extra-utils/users/accounts' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' + checkBadStartPagination, + cleanupTests, + flushAndRunServer, + ServerInfo +} from '@shared/extra-utils' describe('Test accounts API validators', function () { const path = '/api/v1/accounts/' @@ -38,8 +38,9 @@ describe('Test accounts API validators', function () { }) describe('When getting an account', function () { + it('Should return 404 with a non existing name', async function () { - await getAccount(server.url, 'arfaze', HttpStatusCode.NOT_FOUND_404) + await server.accountsCommand.get({ accountName: 'arfaze', expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) }) diff --git a/server/tests/api/moderation/abuses.ts b/server/tests/api/moderation/abuses.ts index a9f5332ce..124833cf6 100644 --- a/server/tests/api/moderation/abuses.ts +++ b/server/tests/api/moderation/abuses.ts @@ -13,7 +13,6 @@ import { doubleFollow, flushAndRunMultipleServers, generateUserAccessToken, - getAccount, getVideoCommentThreads, getVideoIdFromUUID, getVideosList, @@ -606,10 +605,8 @@ describe('Test abuses', function () { describe('Account abuses', function () { - async function getAccountFromServer (url: string, name: string, server: ServerInfo) { - const res = await getAccount(url, name + '@' + server.host) - - return res.body as Account + function getAccountFromServer (server: ServerInfo, targetName: string, targetServer: ServerInfo) { + return server.accountsCommand.get({ accountName: targetName + '@' + targetServer.host }) } before(async function () { @@ -626,7 +623,7 @@ describe('Test abuses', function () { it('Should report abuse on an account', async function () { this.timeout(15000) - const account = await getAccountFromServer(servers[0].url, 'user_1', servers[0]) + const account = await getAccountFromServer(servers[0], 'user_1', servers[0]) const reason = 'it is a bad account' await commands[0].report({ accountId: account.id, reason }) @@ -664,7 +661,7 @@ describe('Test abuses', function () { it('Should report abuse on a remote account', async function () { this.timeout(10000) - const account = await getAccountFromServer(servers[0].url, 'user_2', servers[1]) + const account = await getAccountFromServer(servers[0], 'user_2', servers[1]) const reason = 'it is a really bad account' await commands[0].report({ accountId: account.id, reason }) @@ -718,7 +715,7 @@ describe('Test abuses', function () { it('Should keep the account abuse when deleting the account', async function () { this.timeout(10000) - const account = await getAccountFromServer(servers[1].url, 'user_2', servers[1]) + const account = await getAccountFromServer(servers[1], 'user_2', servers[1]) await removeUser(servers[1].url, account.userId, servers[1].accessToken) await waitJobs(servers) diff --git a/server/tests/api/notifications/moderation-notifications.ts b/server/tests/api/notifications/moderation-notifications.ts index 3e66e7517..e90640ad6 100644 --- a/server/tests/api/notifications/moderation-notifications.ts +++ b/server/tests/api/notifications/moderation-notifications.ts @@ -22,7 +22,6 @@ import { cleanupTests, createUser, generateUserAccessToken, - getAccount, getVideoCommentThreads, getVideoIdFromUUID, immutableAssign, @@ -157,8 +156,8 @@ describe('Test moderation notifications', function () { await waitJobs(servers) - const resAccount = await getAccount(servers[1].url, username + '@' + servers[0].host) - await servers[1].abusesCommand.report({ accountId: resAccount.body.id, reason: 'super reason' }) + const account = await servers[1].accountsCommand.get({ accountName: username + '@' + servers[0].host }) + await servers[1].abusesCommand.report({ accountId: account.id, reason: 'super reason' }) await waitJobs(servers) await checkNewAccountAbuseForModerators(baseParams, username, 'presence') diff --git a/server/tests/api/server/follows.ts b/server/tests/api/server/follows.ts index c8fcca02c..466932d63 100644 --- a/server/tests/api/server/follows.ts +++ b/server/tests/api/server/follows.ts @@ -242,16 +242,16 @@ describe('Test follows', function () { }) it('Should have the correct follows counts', async function () { - await expectAccountFollows(servers[0].url, 'peertube@localhost:' + servers[0].port, 0, 2) - await expectAccountFollows(servers[0].url, 'peertube@localhost:' + servers[1].port, 1, 0) - await expectAccountFollows(servers[0].url, 'peertube@localhost:' + servers[2].port, 1, 0) + await expectAccountFollows({ server: servers[0], handle: 'peertube@localhost:' + servers[0].port, followers: 0, following: 2 }) + await expectAccountFollows({ server: servers[0], handle: 'peertube@localhost:' + servers[1].port, followers: 1, following: 0 }) + await expectAccountFollows({ server: servers[0], handle: 'peertube@localhost:' + servers[2].port, followers: 1, following: 0 }) // Server 2 and 3 does not know server 1 follow another server (there was not a refresh) - await expectAccountFollows(servers[1].url, 'peertube@localhost:' + servers[0].port, 0, 1) - await expectAccountFollows(servers[1].url, 'peertube@localhost:' + servers[1].port, 1, 0) + await expectAccountFollows({ server: servers[1], handle: 'peertube@localhost:' + servers[0].port, followers: 0, following: 1 }) + await expectAccountFollows({ server: servers[1], handle: 'peertube@localhost:' + servers[1].port, followers: 1, following: 0 }) - await expectAccountFollows(servers[2].url, 'peertube@localhost:' + servers[0].port, 0, 1) - await expectAccountFollows(servers[2].url, 'peertube@localhost:' + servers[2].port, 1, 0) + await expectAccountFollows({ server: servers[2], handle: 'peertube@localhost:' + servers[0].port, followers: 0, following: 1 }) + await expectAccountFollows({ server: servers[2], handle: 'peertube@localhost:' + servers[2].port, followers: 1, following: 0 }) }) it('Should unfollow server 3 on server 1', async function () { @@ -283,14 +283,14 @@ describe('Test follows', function () { }) it('Should have the correct follows counts 2', async function () { - await expectAccountFollows(servers[0].url, 'peertube@localhost:' + servers[0].port, 0, 1) - await expectAccountFollows(servers[0].url, 'peertube@localhost:' + servers[1].port, 1, 0) + await expectAccountFollows({ server: servers[0], handle: 'peertube@localhost:' + servers[0].port, followers: 0, following: 1 }) + await expectAccountFollows({ server: servers[0], handle: 'peertube@localhost:' + servers[1].port, followers: 1, following: 0 }) - await expectAccountFollows(servers[1].url, 'peertube@localhost:' + servers[0].port, 0, 1) - await expectAccountFollows(servers[1].url, 'peertube@localhost:' + servers[1].port, 1, 0) + await expectAccountFollows({ server: servers[1], handle: 'peertube@localhost:' + servers[0].port, followers: 0, following: 1 }) + await expectAccountFollows({ server: servers[1], handle: 'peertube@localhost:' + servers[1].port, followers: 1, following: 0 }) - await expectAccountFollows(servers[2].url, 'peertube@localhost:' + servers[0].port, 0, 0) - await expectAccountFollows(servers[2].url, 'peertube@localhost:' + servers[2].port, 0, 0) + await expectAccountFollows({ server: servers[2], handle: 'peertube@localhost:' + servers[0].port, followers: 0, following: 0 }) + await expectAccountFollows({ server: servers[2], handle: 'peertube@localhost:' + servers[2].port, followers: 0, following: 0 }) }) it('Should upload a video on server 2 and 3 and propagate only the video of server 2', async function () { @@ -404,15 +404,15 @@ describe('Test follows', function () { }) it('Should have the correct follows counts 3', async function () { - await expectAccountFollows(servers[0].url, 'peertube@localhost:' + servers[0].port, 0, 2) - await expectAccountFollows(servers[0].url, 'peertube@localhost:' + servers[1].port, 1, 0) - await expectAccountFollows(servers[0].url, 'peertube@localhost:' + servers[2].port, 1, 0) + await expectAccountFollows({ server: servers[0], handle: 'peertube@localhost:' + servers[0].port, followers: 0, following: 2 }) + await expectAccountFollows({ server: servers[0], handle: 'peertube@localhost:' + servers[1].port, followers: 1, following: 0 }) + await expectAccountFollows({ server: servers[0], handle: 'peertube@localhost:' + servers[2].port, followers: 1, following: 0 }) - await expectAccountFollows(servers[1].url, 'peertube@localhost:' + servers[0].port, 0, 1) - await expectAccountFollows(servers[1].url, 'peertube@localhost:' + servers[1].port, 1, 0) + await expectAccountFollows({ server: servers[1], handle: 'peertube@localhost:' + servers[0].port, followers: 0, following: 1 }) + await expectAccountFollows({ server: servers[1], handle: 'peertube@localhost:' + servers[1].port, followers: 1, following: 0 }) - await expectAccountFollows(servers[2].url, 'peertube@localhost:' + servers[0].port, 0, 1) - await expectAccountFollows(servers[2].url, 'peertube@localhost:' + servers[2].port, 1, 0) + await expectAccountFollows({ server: servers[2], handle: 'peertube@localhost:' + servers[0].port, followers: 0, following: 1 }) + await expectAccountFollows({ server: servers[2], handle: 'peertube@localhost:' + servers[2].port, followers: 1, following: 0 }) }) it('Should have propagated videos', async function () { diff --git a/server/tests/api/users/users-multiple-servers.ts b/server/tests/api/users/users-multiple-servers.ts index f60c66e4b..03fbfabeb 100644 --- a/server/tests/api/users/users-multiple-servers.ts +++ b/server/tests/api/users/users-multiple-servers.ts @@ -1,9 +1,9 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ -import * as chai from 'chai' import 'mocha' -import { Account } from '../../../../shared/models/actors' +import * as chai from 'chai' import { + checkActorFilesWereRemoved, checkTmpIsEmpty, checkVideoFilesWereRemoved, cleanupTests, @@ -11,17 +11,19 @@ import { doubleFollow, flushAndRunMultipleServers, getAccountVideos, + getMyUserInformation, getVideoChannelsList, removeUser, + ServerInfo, + setAccessTokensToServers, + testImage, + updateMyAvatar, updateMyUser, - userLogin -} from '../../../../shared/extra-utils' -import { getMyUserInformation, ServerInfo, testImage, updateMyAvatar, uploadVideo } from '../../../../shared/extra-utils/index' -import { checkActorFilesWereRemoved, getAccount, getAccountsList } from '../../../../shared/extra-utils/users/accounts' -import { setAccessTokensToServers } from '../../../../shared/extra-utils/users/login' -import { User } from '../../../../shared/models/users' -import { VideoChannel } from '../../../../shared/models/videos' -import { waitJobs } from '../../../../shared/extra-utils/server/jobs' + uploadVideo, + userLogin, + waitJobs +} from '@shared/extra-utils' +import { User, VideoChannel } from '@shared/models' const expect = chai.expect @@ -133,13 +135,12 @@ describe('Test users with multiple servers', function () { let createdAt: string | Date for (const server of servers) { - const resAccounts = await getAccountsList(server.url, '-createdAt') + const body = await server.accountsCommand.list({ sort: '-createdAt' }) - const resList = resAccounts.body.data.find(a => a.name === 'root' && a.host === 'localhost:' + servers[0].port) as Account + const resList = body.data.find(a => a.name === 'root' && a.host === 'localhost:' + servers[0].port) expect(resList).not.to.be.undefined - const resAccount = await getAccount(server.url, resList.name + '@' + resList.host) - const account = resAccount.body as Account + const account = await server.accountsCommand.get({ accountName: resList.name + '@' + resList.host }) if (!createdAt) createdAt = account.createdAt @@ -193,9 +194,9 @@ describe('Test users with multiple servers', function () { this.timeout(10_000) for (const server of servers) { - const resAccounts = await getAccountsList(server.url, '-createdAt') + const body = await server.accountsCommand.list({ sort: '-createdAt' }) - const accountDeleted = resAccounts.body.data.find(a => a.name === 'user1' && a.host === 'localhost:' + servers[0].port) as Account + const accountDeleted = body.data.find(a => a.name === 'user1' && a.host === 'localhost:' + servers[0].port) expect(accountDeleted).not.to.be.undefined const resVideoChannels = await getVideoChannelsList(server.url, 0, 10) @@ -210,9 +211,9 @@ describe('Test users with multiple servers', function () { await waitJobs(servers) for (const server of servers) { - const resAccounts = await getAccountsList(server.url, '-createdAt') + const body = await server.accountsCommand.list({ sort: '-createdAt' }) - const accountDeleted = resAccounts.body.data.find(a => a.name === 'user1' && a.host === 'localhost:' + servers[0].port) as Account + const accountDeleted = body.data.find(a => a.name === 'user1' && a.host === 'localhost:' + servers[0].port) expect(accountDeleted).to.be.undefined const resVideoChannels = await getVideoChannelsList(server.url, 0, 10) diff --git a/server/tests/api/users/users.ts b/server/tests/api/users/users.ts index 33bcc8701..3beea5d50 100644 --- a/server/tests/api/users/users.ts +++ b/server/tests/api/users/users.ts @@ -11,7 +11,6 @@ import { createUser, deleteMe, flushAndRunServer, - getAccountRatings, getBlacklistedVideosList, getMyUserInformation, getMyUserVideoQuotaUsed, @@ -194,25 +193,22 @@ describe('Test users', function () { it('Should retrieve ratings list', async function () { await rateVideo(server.url, accessToken, videoId, 'like') - const res = await getAccountRatings(server.url, server.user.username, server.accessToken, null, HttpStatusCode.OK_200) - const ratings = res.body + const body = await server.accountsCommand.listRatings({ accountName: server.user.username }) - expect(ratings.total).to.equal(1) - expect(ratings.data[0].video.id).to.equal(videoId) - expect(ratings.data[0].rating).to.equal('like') + expect(body.total).to.equal(1) + expect(body.data[0].video.id).to.equal(videoId) + expect(body.data[0].rating).to.equal('like') }) it('Should retrieve ratings list by rating type', async function () { { - const res = await getAccountRatings(server.url, server.user.username, server.accessToken, 'like') - const ratings = res.body - expect(ratings.data.length).to.equal(1) + const body = await server.accountsCommand.listRatings({ accountName: server.user.username, rating: 'like' }) + expect(body.data.length).to.equal(1) } { - const res = await getAccountRatings(server.url, server.user.username, server.accessToken, 'dislike') - const ratings = res.body - expect(ratings.data.length).to.equal(0) + const body = await server.accountsCommand.listRatings({ accountName: server.user.username, rating: 'dislike' }) + expect(body.data.length).to.equal(0) } }) }) diff --git a/server/tests/cli/prune-storage.ts b/server/tests/cli/prune-storage.ts index 81f91105c..95f573e50 100644 --- a/server/tests/cli/prune-storage.ts +++ b/server/tests/cli/prune-storage.ts @@ -5,7 +5,7 @@ import * as chai from 'chai' import { createFile, readdir } from 'fs-extra' import { join } from 'path' import { buildUUID } from '@server/helpers/uuid' -import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '@shared/core-utils' import { buildServerDirectory, cleanupTests, @@ -13,7 +13,6 @@ import { createVideoPlaylist, doubleFollow, flushAndRunMultipleServers, - getAccount, killallServers, makeGetRequest, ServerInfo, @@ -21,10 +20,10 @@ import { setDefaultVideoChannel, updateMyAvatar, uploadVideo, - wait -} from '../../../shared/extra-utils' -import { waitJobs } from '../../../shared/extra-utils/server/jobs' -import { Account, VideoPlaylistPrivacy } from '../../../shared/models' + wait, + waitJobs +} from '@shared/extra-utils' +import { VideoPlaylistPrivacy } from '@shared/models' const expect = chai.expect @@ -94,8 +93,7 @@ describe('Test prune storage scripts', function () { // Lazy load the remote avatar { - const res = await getAccount(servers[0].url, 'root@localhost:' + servers[1].port) - const account: Account = res.body + const account = await servers[0].accountsCommand.get({ accountName: 'root@localhost:' + servers[1].port }) await makeGetRequest({ url: servers[0].url, path: account.avatar.path, @@ -104,8 +102,7 @@ describe('Test prune storage scripts', function () { } { - const res = await getAccount(servers[1].url, 'root@localhost:' + servers[0].port) - const account: Account = res.body + const account = await servers[1].accountsCommand.get({ accountName: 'root@localhost:' + servers[0].port }) await makeGetRequest({ url: servers[1].url, path: account.avatar.path, diff --git a/server/tests/cli/update-host.ts b/server/tests/cli/update-host.ts index 1b1a76aef..f6131a99f 100644 --- a/server/tests/cli/update-host.ts +++ b/server/tests/cli/update-host.ts @@ -1,9 +1,9 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ import 'mocha' -import * as chai from 'chai' import { addVideoChannel, + addVideoCommentThread, cleanupTests, createUser, flushAndRunServer, @@ -16,12 +16,10 @@ import { reRunServer, ServerInfo, setAccessTokensToServers, - uploadVideo -} from '../../../shared/extra-utils' -import { waitJobs } from '../../../shared/extra-utils/server/jobs' -import { getAccountsList } from '../../../shared/extra-utils/users/accounts' -import { addVideoCommentThread } from '../../../shared/extra-utils/videos/video-comments' -import { VideoDetails } from '../../../shared/models/videos' + uploadVideo, + waitJobs +} from '@shared/extra-utils' +import { VideoDetails } from '@shared/models' const expect = chai.expect @@ -104,10 +102,10 @@ describe('Test update host scripts', function () { }) it('Should have updated accounts url', async function () { - const res = await getAccountsList(server.url) - expect(res.body.total).to.equal(3) + const body = await server.accountsCommand.list() + expect(body.total).to.equal(3) - for (const account of res.body.data) { + for (const account of body.data) { const usernameWithDomain = account.name const { body } = await makeActivityPubGetRequest(server.url, '/accounts/' + usernameWithDomain) diff --git a/server/tests/client.ts b/server/tests/client.ts index be7ce18b4..60df878d7 100644 --- a/server/tests/client.ts +++ b/server/tests/client.ts @@ -11,7 +11,6 @@ import { createVideoPlaylist, doubleFollow, flushAndRunMultipleServers, - getAccount, getVideosList, makeGetRequest, makeHTMLRequest, @@ -105,8 +104,7 @@ describe('Test a client controllers', function () { await updateMyUser({ url: servers[0].url, accessToken: servers[0].accessToken, description: 'my account description' }) - const resAccountRequest = await getAccount(servers[0].url, `${servers[0].user.username}@${servers[0].host}`) - account = resAccountRequest.body + account = await servers[0].accountsCommand.get({ accountName: `${servers[0].user.username}@${servers[0].host}` }) await waitJobs(servers) }) diff --git a/shared/extra-utils/index.ts b/shared/extra-utils/index.ts index ed7d7ab04..68900af26 100644 --- a/shared/extra-utils/index.ts +++ b/shared/extra-utils/index.ts @@ -10,17 +10,11 @@ export * from './overviews' export * from './search' export * from './server' export * from './socket' +export * from './users' export * from './requests/check-api-params' export * from './requests/requests' -export * from './users/accounts' -export * from './users/blocklist' -export * from './users/login' -export * from './users/user-notifications' -export * from './users/user-subscriptions' -export * from './users/users' - export * from './videos/live' export * from './videos/services' export * from './videos/video-blacklist' diff --git a/shared/extra-utils/server/servers.ts b/shared/extra-utils/server/servers.ts index 8bd4446be..c2cab9818 100644 --- a/shared/extra-utils/server/servers.ts +++ b/shared/extra-utils/server/servers.ts @@ -17,6 +17,7 @@ import { OverviewsCommand } from '../overviews' import { makeGetRequest } from '../requests/requests' import { SearchCommand } from '../search' import { SocketIOCommand } from '../socket' +import { AccountsCommand } from '../users' import { ConfigCommand } from './config-command' import { ContactFormCommand } from './contact-form-command' import { DebugCommand } from './debug-command' @@ -95,6 +96,7 @@ interface ServerInfo { statsCommand?: StatsCommand configCommand?: ConfigCommand socketIOCommand?: SocketIOCommand + accountsCommand?: AccountsCommand } function parallelTests () { @@ -317,6 +319,7 @@ async function runServer (server: ServerInfo, configOverrideArg?: any, args = [] server.statsCommand = new StatsCommand(server) server.configCommand = new ConfigCommand(server) server.socketIOCommand = new SocketIOCommand(server) + server.accountsCommand = new AccountsCommand(server) res(server) }) diff --git a/shared/extra-utils/users/accounts-command.ts b/shared/extra-utils/users/accounts-command.ts new file mode 100644 index 000000000..89c080e93 --- /dev/null +++ b/shared/extra-utils/users/accounts-command.ts @@ -0,0 +1,54 @@ +import { ResultList } from '@shared/models' +import { HttpStatusCode } from '../../core-utils/miscs/http-error-codes' +import { Account } from '../../models/actors' +import { AccountVideoRate, VideoRateType } from '../../models/videos' +import { AbstractCommand, OverrideCommandOptions } from '../shared' + +export class AccountsCommand extends AbstractCommand { + + list (options: OverrideCommandOptions & { + sort?: string // default -createdAt + } = {}) { + const { sort = '-createdAt' } = options + const path = '/api/v1/accounts' + + return this.getRequestBody>({ + ...options, + + path, + query: { sort }, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } + + get (options: OverrideCommandOptions & { + accountName: string + }) { + const path = '/api/v1/accounts/' + options.accountName + + return this.getRequestBody({ + ...options, + + path, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } + + listRatings (options: OverrideCommandOptions & { + accountName: string + rating?: VideoRateType + }) { + const { rating, accountName } = options + const path = '/api/v1/accounts/' + accountName + '/ratings' + + const query = { rating } + + return this.getRequestBody>({ + ...options, + + path, + query, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } +} diff --git a/shared/extra-utils/users/accounts.ts b/shared/extra-utils/users/accounts.ts index 4ea7f1402..ee94351e8 100644 --- a/shared/extra-utils/users/accounts.ts +++ b/shared/extra-utils/users/accounts.ts @@ -1,43 +1,25 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ -import * as request from 'supertest' import { expect } from 'chai' -import { existsSync, readdir } from 'fs-extra' +import { pathExists, readdir } from 'fs-extra' import { join } from 'path' -import { Account } from '../../models/actors' -import { root } from '../miscs/miscs' -import { makeGetRequest } from '../requests/requests' -import { VideoRateType } from '../../models/videos' -import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' - -function getAccountsList (url: string, sort = '-createdAt', statusCodeExpected = HttpStatusCode.OK_200) { - const path = '/api/v1/accounts' - - return makeGetRequest({ - url, - query: { sort }, - path, - statusCodeExpected - }) -} - -function getAccount (url: string, accountName: string, statusCodeExpected = HttpStatusCode.OK_200) { - const path = '/api/v1/accounts/' + accountName - - return makeGetRequest({ - url, - path, - statusCodeExpected - }) -} - -async function expectAccountFollows (url: string, nameWithDomain: string, followersCount: number, followingCount: number) { - const res = await getAccountsList(url) - const account = res.body.data.find((a: Account) => a.name + '@' + a.host === nameWithDomain) - - const message = `${nameWithDomain} on ${url}` - expect(account.followersCount).to.equal(followersCount, message) - expect(account.followingCount).to.equal(followingCount, message) +import { root } from '@server/helpers/core-utils' +import { ServerInfo } from '../server' + +async function expectAccountFollows (options: { + server: ServerInfo + handle: string + followers: number + following: number +}) { + const { server, handle, followers, following } = options + + const body = await server.accountsCommand.list() + const account = body.data.find(a => a.name + '@' + a.host === handle) + + const message = `${handle} on ${server.url}` + expect(account.followersCount).to.equal(followers, message) + expect(account.followingCount).to.equal(following, message) } async function checkActorFilesWereRemoved (filename: string, serverNumber: number) { @@ -46,7 +28,7 @@ async function checkActorFilesWereRemoved (filename: string, serverNumber: numbe for (const directory of [ 'avatars' ]) { const directoryPath = join(root(), testDirectory, directory) - const directoryExists = existsSync(directoryPath) + const directoryExists = await pathExists(directoryPath) expect(directoryExists).to.be.true const files = await readdir(directoryPath) @@ -56,32 +38,7 @@ async function checkActorFilesWereRemoved (filename: string, serverNumber: numbe } } -function getAccountRatings ( - url: string, - accountName: string, - accessToken: string, - rating?: VideoRateType, - statusCodeExpected = HttpStatusCode.OK_200 -) { - const path = '/api/v1/accounts/' + accountName + '/ratings' - - const query = rating ? { rating } : {} - - return request(url) - .get(path) - .query(query) - .set('Accept', 'application/json') - .set('Authorization', 'Bearer ' + accessToken) - .expect(statusCodeExpected) - .expect('Content-Type', /json/) -} - -// --------------------------------------------------------------------------- - export { - getAccount, expectAccountFollows, - getAccountsList, - checkActorFilesWereRemoved, - getAccountRatings + checkActorFilesWereRemoved } diff --git a/shared/extra-utils/users/index.ts b/shared/extra-utils/users/index.ts new file mode 100644 index 000000000..b3387ed8a --- /dev/null +++ b/shared/extra-utils/users/index.ts @@ -0,0 +1,8 @@ +export * from './accounts' +export * from './accounts-command' + +export * from './blocklist' +export * from './login' +export * from './user-notifications' +export * from './user-subscriptions' +export * from './users' -- cgit v1.2.3 From 5f8bd4cbb178290da7d8f81e996f19f0eccc8e4c Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Wed, 7 Jul 2021 16:02:46 +0200 Subject: Introduce blocklist command --- server/tests/api/moderation/abuses.ts | 14 +- .../tests/api/moderation/blocklist-notification.ts | 41 ++-- server/tests/api/moderation/blocklist.ts | 100 ++++----- .../api/notifications/comments-notifications.ts | 10 +- server/tests/api/videos/video-playlists.ts | 26 +-- server/tests/api/videos/videos-overview.ts | 3 +- server/tests/external-plugins/auto-mute.ts | 9 +- server/tests/feeds/feeds.ts | 29 ++- shared/extra-utils/server/servers.ts | 4 +- shared/extra-utils/socket/socket-io-command.ts | 2 +- shared/extra-utils/users/blocklist-command.ts | 135 ++++++++++++ shared/extra-utils/users/blocklist.ts | 238 --------------------- shared/extra-utils/users/index.ts | 4 +- 13 files changed, 230 insertions(+), 385 deletions(-) create mode 100644 shared/extra-utils/users/blocklist-command.ts delete mode 100644 shared/extra-utils/users/blocklist.ts diff --git a/server/tests/api/moderation/abuses.ts b/server/tests/api/moderation/abuses.ts index 124833cf6..a2bd07b12 100644 --- a/server/tests/api/moderation/abuses.ts +++ b/server/tests/api/moderation/abuses.ts @@ -4,8 +4,6 @@ import 'mocha' import * as chai from 'chai' import { AbusesCommand, - addAccountToServerBlocklist, - addServerToServerBlocklist, addVideoCommentThread, cleanupTests, createUser, @@ -16,8 +14,6 @@ import { getVideoCommentThreads, getVideoIdFromUUID, getVideosList, - removeAccountFromServerBlocklist, - removeServerFromServerBlocklist, removeUser, removeVideo, ServerInfo, @@ -27,7 +23,7 @@ import { userLogin, waitJobs } from '@shared/extra-utils' -import { AbuseMessage, AbusePredefinedReasonsString, AbuseState, Account, AdminAbuse, UserAbuse, VideoComment } from '@shared/models' +import { AbuseMessage, AbusePredefinedReasonsString, AbuseState, AdminAbuse, UserAbuse, VideoComment } from '@shared/models' const expect = chai.expect @@ -225,7 +221,7 @@ describe('Test abuses', function () { const accountToBlock = 'root@' + servers[1].host { - await addAccountToServerBlocklist(servers[0].url, servers[0].accessToken, accountToBlock) + await servers[0].blocklistCommand.addToServerBlocklist({ account: accountToBlock }) const body = await commands[0].getAdminList() expect(body.total).to.equal(2) @@ -235,7 +231,7 @@ describe('Test abuses', function () { } { - await removeAccountFromServerBlocklist(servers[0].url, servers[0].accessToken, accountToBlock) + await servers[0].blocklistCommand.removeFromServerBlocklist({ account: accountToBlock }) const body = await commands[0].getAdminList() expect(body.total).to.equal(3) @@ -246,7 +242,7 @@ describe('Test abuses', function () { const serverToBlock = servers[1].host { - await addServerToServerBlocklist(servers[0].url, servers[0].accessToken, servers[1].host) + await servers[0].blocklistCommand.addToServerBlocklist({ server: serverToBlock }) const body = await commands[0].getAdminList() expect(body.total).to.equal(2) @@ -256,7 +252,7 @@ describe('Test abuses', function () { } { - await removeServerFromServerBlocklist(servers[0].url, servers[0].accessToken, serverToBlock) + await servers[0].blocklistCommand.removeFromServerBlocklist({ server: serverToBlock }) const body = await commands[0].getAdminList() expect(body.total).to.equal(3) diff --git a/server/tests/api/moderation/blocklist-notification.ts b/server/tests/api/moderation/blocklist-notification.ts index 4fb3c95f2..99da64a2d 100644 --- a/server/tests/api/moderation/blocklist-notification.ts +++ b/server/tests/api/moderation/blocklist-notification.ts @@ -2,30 +2,23 @@ import 'mocha' import * as chai from 'chai' -import { getUserNotifications, markAsReadAllNotifications } from '@shared/extra-utils/users/user-notifications' -import { addUserSubscription, removeUserSubscription } from '@shared/extra-utils/users/user-subscriptions' -import { UserNotification, UserNotificationType } from '@shared/models' import { + addUserSubscription, + addVideoCommentThread, cleanupTests, createUser, doubleFollow, flushAndRunMultipleServers, + getUserNotifications, + markAsReadAllNotifications, + removeUserSubscription, ServerInfo, + setAccessTokensToServers, uploadVideo, - userLogin -} from '../../../../shared/extra-utils/index' -import { waitJobs } from '../../../../shared/extra-utils/server/jobs' -import { - addAccountToAccountBlocklist, - addAccountToServerBlocklist, - addServerToAccountBlocklist, - addServerToServerBlocklist, - removeAccountFromAccountBlocklist, - removeAccountFromServerBlocklist, - removeServerFromAccountBlocklist -} from '../../../../shared/extra-utils/users/blocklist' -import { setAccessTokensToServers } from '../../../../shared/extra-utils/users/login' -import { addVideoCommentThread } from '../../../../shared/extra-utils/videos/video-comments' + userLogin, + waitJobs +} from '@shared/extra-utils' +import { UserNotification, UserNotificationType } from '@shared/models' const expect = chai.expect @@ -134,7 +127,7 @@ describe('Test blocklist', function () { it('Should block an account', async function () { this.timeout(10000) - await addAccountToAccountBlocklist(servers[0].url, userToken1, 'user3@' + servers[1].host) + await servers[0].blocklistCommand.addToMyBlocklist({ token: userToken1, account: 'user3@' + servers[1].host }) await waitJobs(servers) }) @@ -147,7 +140,7 @@ describe('Test blocklist', function () { await checkNotifications(servers[0].url, userToken2, notifs) - await removeAccountFromAccountBlocklist(servers[0].url, userToken1, 'user3@' + servers[1].host) + await servers[0].blocklistCommand.removeFromMyBlocklist({ token: userToken1, account: 'user3@' + servers[1].host }) }) }) @@ -167,7 +160,7 @@ describe('Test blocklist', function () { it('Should block an account', async function () { this.timeout(10000) - await addServerToAccountBlocklist(servers[0].url, userToken1, servers[1].host) + await servers[0].blocklistCommand.addToMyBlocklist({ token: userToken1, server: servers[1].host }) await waitJobs(servers) }) @@ -180,7 +173,7 @@ describe('Test blocklist', function () { await checkNotifications(servers[0].url, userToken2, notifs) - await removeServerFromAccountBlocklist(servers[0].url, userToken1, servers[1].host) + await servers[0].blocklistCommand.removeFromMyBlocklist({ token: userToken1, server: servers[1].host }) }) }) @@ -207,7 +200,7 @@ describe('Test blocklist', function () { it('Should block an account', async function () { this.timeout(10000) - await addAccountToServerBlocklist(servers[0].url, servers[0].accessToken, 'user3@' + servers[1].host) + await servers[0].blocklistCommand.addToServerBlocklist({ account: 'user3@' + servers[1].host }) await waitJobs(servers) }) @@ -215,7 +208,7 @@ describe('Test blocklist', function () { await checkNotifications(servers[0].url, userToken1, []) await checkNotifications(servers[0].url, userToken2, []) - await removeAccountFromServerBlocklist(servers[0].url, servers[0].accessToken, 'user3@' + servers[1].host) + await servers[0].blocklistCommand.removeFromServerBlocklist({ account: 'user3@' + servers[1].host }) }) }) @@ -242,7 +235,7 @@ describe('Test blocklist', function () { it('Should block an account', async function () { this.timeout(10000) - await addServerToServerBlocklist(servers[0].url, servers[0].accessToken, servers[1].host) + await servers[0].blocklistCommand.addToServerBlocklist({ server: servers[1].host }) await waitJobs(servers) }) diff --git a/server/tests/api/moderation/blocklist.ts b/server/tests/api/moderation/blocklist.ts index 9ca6324c2..1b8860571 100644 --- a/server/tests/api/moderation/blocklist.ts +++ b/server/tests/api/moderation/blocklist.ts @@ -3,46 +3,27 @@ import 'mocha' import * as chai from 'chai' import { - addAccountToAccountBlocklist, - addAccountToServerBlocklist, - addServerToAccountBlocklist, - addServerToServerBlocklist, addVideoCommentReply, addVideoCommentThread, + BlocklistCommand, cleanupTests, createUser, deleteVideoComment, doubleFollow, findCommentId, flushAndRunMultipleServers, - getAccountBlocklistByAccount, - getAccountBlocklistByServer, - getServerBlocklistByAccount, - getServerBlocklistByServer, getUserNotifications, getVideoCommentThreads, getVideosList, getVideosListWithToken, getVideoThreadComments, - removeAccountFromAccountBlocklist, - removeAccountFromServerBlocklist, - removeServerFromAccountBlocklist, - removeServerFromServerBlocklist, ServerInfo, setAccessTokensToServers, uploadVideo, userLogin, waitJobs } from '@shared/extra-utils' -import { - AccountBlock, - ServerBlock, - UserNotification, - UserNotificationType, - Video, - VideoComment, - VideoCommentThreadTree -} from '@shared/models' +import { UserNotification, UserNotificationType, Video, VideoComment, VideoCommentThreadTree } from '@shared/models' const expect = chai.expect @@ -108,6 +89,8 @@ describe('Test blocklist', function () { let userModeratorToken: string let userToken2: string + let command: BlocklistCommand + before(async function () { this.timeout(120000) @@ -167,6 +150,8 @@ describe('Test blocklist', function () { } await waitJobs(servers) + + command = servers[0].blocklistCommand }) describe('User blocklist', function () { @@ -181,7 +166,7 @@ describe('Test blocklist', function () { }) it('Should block a remote account', async function () { - await addAccountToAccountBlocklist(servers[0].url, servers[0].accessToken, 'user2@localhost:' + servers[1].port) + await command.addToMyBlocklist({ account: 'user2@localhost:' + servers[1].port }) }) it('Should hide its videos', async function () { @@ -195,7 +180,7 @@ describe('Test blocklist', function () { }) it('Should block a local account', async function () { - await addAccountToAccountBlocklist(servers[0].url, servers[0].accessToken, 'user1') + await command.addToMyBlocklist({ account: 'user1' }) }) it('Should hide its videos', async function () { @@ -251,12 +236,10 @@ describe('Test blocklist', function () { it('Should list blocked accounts', async function () { { - const res = await getAccountBlocklistByAccount(servers[0].url, servers[0].accessToken, 0, 1, 'createdAt') - const blocks: AccountBlock[] = res.body.data + const body = await command.listMyAccountBlocklist({ start: 0, count: 1, sort: 'createdAt' }) + expect(body.total).to.equal(2) - expect(res.body.total).to.equal(2) - - const block = blocks[0] + const block = body.data[0] expect(block.byAccount.displayName).to.equal('root') expect(block.byAccount.name).to.equal('root') expect(block.blockedAccount.displayName).to.equal('user2') @@ -265,12 +248,10 @@ describe('Test blocklist', function () { } { - const res = await getAccountBlocklistByAccount(servers[0].url, servers[0].accessToken, 1, 2, 'createdAt') - const blocks: AccountBlock[] = res.body.data - - expect(res.body.total).to.equal(2) + const body = await command.listMyAccountBlocklist({ start: 1, count: 2, sort: 'createdAt' }) + expect(body.total).to.equal(2) - const block = blocks[0] + const block = body.data[0] expect(block.byAccount.displayName).to.equal('root') expect(block.byAccount.name).to.equal('root') expect(block.blockedAccount.displayName).to.equal('user1') @@ -335,7 +316,7 @@ describe('Test blocklist', function () { }) it('Should unblock the remote account', async function () { - await removeAccountFromAccountBlocklist(servers[0].url, servers[0].accessToken, 'user2@localhost:' + servers[1].port) + await command.removeFromMyBlocklist({ account: 'user2@localhost:' + servers[1].port }) }) it('Should display its videos', async function () { @@ -374,7 +355,7 @@ describe('Test blocklist', function () { }) it('Should unblock the local account', async function () { - await removeAccountFromAccountBlocklist(servers[0].url, servers[0].accessToken, 'user1') + await command.removeFromMyBlocklist({ account: 'user1' }) }) it('Should display its comments', function () { @@ -402,6 +383,7 @@ describe('Test blocklist', function () { }) describe('When managing server blocklist', function () { + it('Should list all videos', function () { return checkAllVideos(servers[0].url, servers[0].accessToken) }) @@ -411,7 +393,7 @@ describe('Test blocklist', function () { }) it('Should block a remote server', async function () { - await addServerToAccountBlocklist(servers[0].url, servers[0].accessToken, 'localhost:' + servers[1].port) + await command.addToMyBlocklist({ server: 'localhost:' + servers[1].port }) }) it('Should hide its videos', async function () { @@ -464,19 +446,17 @@ describe('Test blocklist', function () { }) it('Should list blocked servers', async function () { - const res = await getServerBlocklistByAccount(servers[0].url, servers[0].accessToken, 0, 1, 'createdAt') - const blocks: ServerBlock[] = res.body.data - - expect(res.body.total).to.equal(1) + const body = await command.listMyServerBlocklist({ start: 0, count: 1, sort: 'createdAt' }) + expect(body.total).to.equal(1) - const block = blocks[0] + const block = body.data[0] expect(block.byAccount.displayName).to.equal('root') expect(block.byAccount.name).to.equal('root') expect(block.blockedServer.host).to.equal('localhost:' + servers[1].port) }) it('Should unblock the remote server', async function () { - await removeServerFromAccountBlocklist(servers[0].url, servers[0].accessToken, 'localhost:' + servers[1].port) + await command.removeFromMyBlocklist({ server: 'localhost:' + servers[1].port }) }) it('Should display its videos', function () { @@ -524,7 +504,7 @@ describe('Test blocklist', function () { }) it('Should block a remote account', async function () { - await addAccountToServerBlocklist(servers[0].url, servers[0].accessToken, 'user2@localhost:' + servers[1].port) + await command.addToServerBlocklist({ account: 'user2@localhost:' + servers[1].port }) }) it('Should hide its videos', async function () { @@ -540,7 +520,7 @@ describe('Test blocklist', function () { }) it('Should block a local account', async function () { - await addAccountToServerBlocklist(servers[0].url, servers[0].accessToken, 'user1') + await command.addToServerBlocklist({ account: 'user1' }) }) it('Should hide its videos', async function () { @@ -598,12 +578,10 @@ describe('Test blocklist', function () { it('Should list blocked accounts', async function () { { - const res = await getAccountBlocklistByServer(servers[0].url, servers[0].accessToken, 0, 1, 'createdAt') - const blocks: AccountBlock[] = res.body.data - - expect(res.body.total).to.equal(2) + const body = await command.listServerAccountBlocklist({ start: 0, count: 1, sort: 'createdAt' }) + expect(body.total).to.equal(2) - const block = blocks[0] + const block = body.data[0] expect(block.byAccount.displayName).to.equal('peertube') expect(block.byAccount.name).to.equal('peertube') expect(block.blockedAccount.displayName).to.equal('user2') @@ -612,12 +590,10 @@ describe('Test blocklist', function () { } { - const res = await getAccountBlocklistByServer(servers[0].url, servers[0].accessToken, 1, 2, 'createdAt') - const blocks: AccountBlock[] = res.body.data + const body = await command.listServerAccountBlocklist({ start: 1, count: 2, sort: 'createdAt' }) + expect(body.total).to.equal(2) - expect(res.body.total).to.equal(2) - - const block = blocks[0] + const block = body.data[0] expect(block.byAccount.displayName).to.equal('peertube') expect(block.byAccount.name).to.equal('peertube') expect(block.blockedAccount.displayName).to.equal('user1') @@ -627,7 +603,7 @@ describe('Test blocklist', function () { }) it('Should unblock the remote account', async function () { - await removeAccountFromServerBlocklist(servers[0].url, servers[0].accessToken, 'user2@localhost:' + servers[1].port) + await command.removeFromServerBlocklist({ account: 'user2@localhost:' + servers[1].port }) }) it('Should display its videos', async function () { @@ -643,7 +619,7 @@ describe('Test blocklist', function () { }) it('Should unblock the local account', async function () { - await removeAccountFromServerBlocklist(servers[0].url, servers[0].accessToken, 'user1') + await command.removeFromServerBlocklist({ account: 'user1' }) }) it('Should display its comments', async function () { @@ -686,7 +662,7 @@ describe('Test blocklist', function () { }) it('Should block a remote server', async function () { - await addServerToServerBlocklist(servers[0].url, servers[0].accessToken, 'localhost:' + servers[1].port) + await command.addToServerBlocklist({ server: 'localhost:' + servers[1].port }) }) it('Should hide its videos', async function () { @@ -758,19 +734,17 @@ describe('Test blocklist', function () { }) it('Should list blocked servers', async function () { - const res = await getServerBlocklistByServer(servers[0].url, servers[0].accessToken, 0, 1, 'createdAt') - const blocks: ServerBlock[] = res.body.data - - expect(res.body.total).to.equal(1) + const body = await command.listServerServerBlocklist({ start: 0, count: 1, sort: 'createdAt' }) + expect(body.total).to.equal(1) - const block = blocks[0] + const block = body.data[0] expect(block.byAccount.displayName).to.equal('peertube') expect(block.byAccount.name).to.equal('peertube') expect(block.blockedServer.host).to.equal('localhost:' + servers[1].port) }) it('Should unblock the remote server', async function () { - await removeServerFromServerBlocklist(servers[0].url, servers[0].accessToken, 'localhost:' + servers[1].port) + await command.removeFromServerBlocklist({ server: 'localhost:' + servers[1].port }) }) it('Should list all videos', async function () { diff --git a/server/tests/api/notifications/comments-notifications.ts b/server/tests/api/notifications/comments-notifications.ts index d2badf237..13fcee843 100644 --- a/server/tests/api/notifications/comments-notifications.ts +++ b/server/tests/api/notifications/comments-notifications.ts @@ -3,7 +3,6 @@ import 'mocha' import * as chai from 'chai' import { - addAccountToAccountBlocklist, addVideoCommentReply, addVideoCommentThread, checkCommentMention, @@ -14,7 +13,6 @@ import { getVideoThreadComments, MockSmtpServer, prepareNotificationsTest, - removeAccountFromAccountBlocklist, ServerInfo, updateMyUser, uploadVideo, @@ -86,7 +84,7 @@ describe('Test comments notifications', function () { it('Should not send a new comment notification if the account is muted', async function () { this.timeout(20000) - await addAccountToAccountBlocklist(servers[0].url, userAccessToken, 'root') + await servers[0].blocklistCommand.addToMyBlocklist({ token: userAccessToken, account: 'root' }) const resVideo = await uploadVideo(servers[0].url, userAccessToken, { name: 'super video' }) const uuid = resVideo.body.video.uuid @@ -97,7 +95,7 @@ describe('Test comments notifications', function () { await waitJobs(servers) await checkNewCommentOnMyVideo(baseParams, uuid, commentId, commentId, 'absence') - await removeAccountFromAccountBlocklist(servers[0].url, userAccessToken, 'root') + await servers[0].blocklistCommand.removeFromMyBlocklist({ token: userAccessToken, account: 'root' }) }) it('Should send a new comment notification after a local comment on my video', async function () { @@ -244,7 +242,7 @@ describe('Test comments notifications', function () { it('Should not send a new mention notification if the account is muted', async function () { this.timeout(10000) - await addAccountToAccountBlocklist(servers[0].url, userAccessToken, 'root') + await servers[0].blocklistCommand.addToMyBlocklist({ token: userAccessToken, account: 'root' }) const resVideo = await uploadVideo(servers[0].url, servers[0].accessToken, { name: 'super video' }) const uuid = resVideo.body.video.uuid @@ -255,7 +253,7 @@ describe('Test comments notifications', function () { await waitJobs(servers) await checkCommentMention(baseParams, uuid, commentId, commentId, 'super root name', 'absence') - await removeAccountFromAccountBlocklist(servers[0].url, userAccessToken, 'root') + await servers[0].blocklistCommand.removeFromMyBlocklist({ token: userAccessToken, account: 'root' }) }) it('Should not send a new mention notification if the remote account mention a local account', async function () { diff --git a/server/tests/api/videos/video-playlists.ts b/server/tests/api/videos/video-playlists.ts index 28f68dcfe..90189721a 100644 --- a/server/tests/api/videos/video-playlists.ts +++ b/server/tests/api/videos/video-playlists.ts @@ -4,10 +4,6 @@ import 'mocha' import * as chai from 'chai' import { HttpStatusCode } from '@shared/core-utils' import { - addAccountToAccountBlocklist, - addAccountToServerBlocklist, - addServerToAccountBlocklist, - addServerToServerBlocklist, addVideoChannel, addVideoInPlaylist, addVideoToBlacklist, @@ -31,10 +27,6 @@ import { getVideoPlaylistPrivacies, getVideoPlaylistsList, getVideoPlaylistWithToken, - removeAccountFromAccountBlocklist, - removeAccountFromServerBlocklist, - removeServerFromAccountBlocklist, - removeServerFromServerBlocklist, removeUser, removeVideoFromBlacklist, removeVideoFromPlaylist, @@ -760,56 +752,58 @@ describe('Test video playlists', function () { it('Should update the element type if the account or server of the video is blocked', async function () { this.timeout(90000) + const command = servers[0].blocklistCommand + const name = 'video 90' const position = 2 { - await addAccountToAccountBlocklist(servers[0].url, userAccessTokenServer1, 'root@localhost:' + servers[1].port) + await command.addToMyBlocklist({ token: userAccessTokenServer1, account: 'root@localhost:' + servers[1].port }) await waitJobs(servers) await checkPlaylistElementType(groupUser1, playlistServer1UUID2, VideoPlaylistElementType.UNAVAILABLE, position, name, 3) await checkPlaylistElementType(group2, playlistServer1UUID2, VideoPlaylistElementType.REGULAR, position, name, 3) - await removeAccountFromAccountBlocklist(servers[0].url, userAccessTokenServer1, 'root@localhost:' + servers[1].port) + await command.removeFromMyBlocklist({ token: userAccessTokenServer1, account: 'root@localhost:' + servers[1].port }) await waitJobs(servers) await checkPlaylistElementType(group2, playlistServer1UUID2, VideoPlaylistElementType.REGULAR, position, name, 3) } { - await addServerToAccountBlocklist(servers[0].url, userAccessTokenServer1, 'localhost:' + servers[1].port) + await command.addToMyBlocklist({ token: userAccessTokenServer1, server: 'localhost:' + servers[1].port }) await waitJobs(servers) await checkPlaylistElementType(groupUser1, playlistServer1UUID2, VideoPlaylistElementType.UNAVAILABLE, position, name, 3) await checkPlaylistElementType(group2, playlistServer1UUID2, VideoPlaylistElementType.REGULAR, position, name, 3) - await removeServerFromAccountBlocklist(servers[0].url, userAccessTokenServer1, 'localhost:' + servers[1].port) + await command.removeFromMyBlocklist({ token: userAccessTokenServer1, server: 'localhost:' + servers[1].port }) await waitJobs(servers) await checkPlaylistElementType(group2, playlistServer1UUID2, VideoPlaylistElementType.REGULAR, position, name, 3) } { - await addAccountToServerBlocklist(servers[0].url, servers[0].accessToken, 'root@localhost:' + servers[1].port) + await command.addToServerBlocklist({ account: 'root@localhost:' + servers[1].port }) await waitJobs(servers) await checkPlaylistElementType(groupUser1, playlistServer1UUID2, VideoPlaylistElementType.UNAVAILABLE, position, name, 3) await checkPlaylistElementType(group2, playlistServer1UUID2, VideoPlaylistElementType.REGULAR, position, name, 3) - await removeAccountFromServerBlocklist(servers[0].url, servers[0].accessToken, 'root@localhost:' + servers[1].port) + await command.removeFromServerBlocklist({ account: 'root@localhost:' + servers[1].port }) await waitJobs(servers) await checkPlaylistElementType(group2, playlistServer1UUID2, VideoPlaylistElementType.REGULAR, position, name, 3) } { - await addServerToServerBlocklist(servers[0].url, servers[0].accessToken, 'localhost:' + servers[1].port) + await command.addToServerBlocklist({ server: 'localhost:' + servers[1].port }) await waitJobs(servers) await checkPlaylistElementType(groupUser1, playlistServer1UUID2, VideoPlaylistElementType.UNAVAILABLE, position, name, 3) await checkPlaylistElementType(group2, playlistServer1UUID2, VideoPlaylistElementType.REGULAR, position, name, 3) - await removeServerFromServerBlocklist(servers[0].url, servers[0].accessToken, 'localhost:' + servers[1].port) + await command.removeFromServerBlocklist({ server: 'localhost:' + servers[1].port }) await waitJobs(servers) await checkPlaylistElementType(group2, playlistServer1UUID2, VideoPlaylistElementType.REGULAR, position, name, 3) diff --git a/server/tests/api/videos/videos-overview.ts b/server/tests/api/videos/videos-overview.ts index b3ab9e070..ccbc6f4a4 100644 --- a/server/tests/api/videos/videos-overview.ts +++ b/server/tests/api/videos/videos-overview.ts @@ -3,7 +3,6 @@ import 'mocha' import * as chai from 'chai' import { - addAccountToAccountBlocklist, cleanupTests, flushAndRunServer, generateUserAccessToken, @@ -115,7 +114,7 @@ describe('Test a videos overview', function () { it('Should hide muted accounts', async function () { const token = await generateUserAccessToken(server, 'choco') - await addAccountToAccountBlocklist(server.url, token, 'root@' + server.host) + await server.blocklistCommand.addToMyBlocklist({ token, account: 'root@' + server.host }) { const body = await server.overviewsCommand.getVideos({ page: 1 }) diff --git a/server/tests/external-plugins/auto-mute.ts b/server/tests/external-plugins/auto-mute.ts index 8fcf94452..f86c83808 100644 --- a/server/tests/external-plugins/auto-mute.ts +++ b/server/tests/external-plugins/auto-mute.ts @@ -4,8 +4,6 @@ import 'mocha' import { expect } from 'chai' import { HttpStatusCode } from '@shared/core-utils' import { - addAccountToServerBlocklist, - addServerToAccountBlocklist, cleanupTests, doubleFollow, flushAndRunMultipleServers, @@ -13,7 +11,6 @@ import { killallServers, makeGetRequest, MockBlocklist, - removeAccountFromServerBlocklist, reRunServer, ServerInfo, setAccessTokensToServers, @@ -147,7 +144,7 @@ describe('Official plugin auto-mute', function () { expect(res.body.total).to.equal(1) } - await removeAccountFromServerBlocklist(servers[0].url, servers[0].accessToken, account) + await servers[0].blocklistCommand.removeFromServerBlocklist({ account }) { const res = await getVideosList(servers[0].url) @@ -201,8 +198,8 @@ describe('Official plugin auto-mute', function () { } }) - await addAccountToServerBlocklist(servers[0].url, servers[0].accessToken, 'root@localhost:' + servers[1].port) - await addServerToAccountBlocklist(servers[0].url, servers[0].accessToken, 'localhost:' + servers[1].port) + await servers[0].blocklistCommand.addToServerBlocklist({ account: 'root@localhost:' + servers[1].port }) + await servers[0].blocklistCommand.addToMyBlocklist({ server: 'localhost:' + servers[1].port }) const res = await makeGetRequest({ url: servers[0].url, diff --git a/server/tests/feeds/feeds.ts b/server/tests/feeds/feeds.ts index 4d29a2e39..17efc666d 100644 --- a/server/tests/feeds/feeds.ts +++ b/server/tests/feeds/feeds.ts @@ -3,16 +3,10 @@ import 'mocha' import * as chai from 'chai' import * as xmlParser from 'fast-xml-parser' +import { HttpStatusCode } from '@shared/core-utils' import { - addAccountToAccountBlocklist, - addAccountToServerBlocklist, - removeAccountFromServerBlocklist -} from '@shared/extra-utils/users/blocklist' -import { addUserSubscription, listUserSubscriptionVideos } from '@shared/extra-utils/users/user-subscriptions' -import { VideoPrivacy } from '@shared/models' -import { ScopedToken } from '@shared/models/users/user-scoped-token' -import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' -import { + addUserSubscription, + addVideoCommentThread, cleanupTests, createUser, doubleFollow, @@ -20,16 +14,17 @@ import { flushAndRunServer, getMyUserInformation, getUserScopedTokens, + listUserSubscriptionVideos, renewUserScopedTokens, ServerInfo, setAccessTokensToServers, uploadVideo, uploadVideoAndGetId, - userLogin -} from '../../../shared/extra-utils' -import { waitJobs } from '../../../shared/extra-utils/server/jobs' -import { addVideoCommentThread } from '../../../shared/extra-utils/videos/video-comments' -import { User } from '../../../shared/models/users' + userLogin, + waitJobs +} from '@shared/extra-utils' +import { User, VideoPrivacy } from '@shared/models' +import { ScopedToken } from '@shared/models/users/user-scoped-token' chai.use(require('chai-xml')) chai.use(require('chai-json-schema')) @@ -271,7 +266,7 @@ describe('Test syndication feeds', () => { const remoteHandle = 'root@localhost:' + servers[0].port - await addAccountToServerBlocklist(servers[1].url, servers[1].accessToken, remoteHandle) + await servers[1].blocklistCommand.addToServerBlocklist({ account: remoteHandle }) { const json = await servers[1].feedCommand.getJSON({ feed: 'video-comments', query: { version: 2 } }) @@ -279,7 +274,7 @@ describe('Test syndication feeds', () => { expect(jsonObj.items.length).to.be.equal(0) } - await removeAccountFromServerBlocklist(servers[1].url, servers[1].accessToken, remoteHandle) + await servers[1].blocklistCommand.removeFromServerBlocklist({ account: remoteHandle }) { const videoUUID = (await uploadVideoAndGetId({ server: servers[1], videoName: 'server 2' })).uuid @@ -292,7 +287,7 @@ describe('Test syndication feeds', () => { expect(jsonObj.items.length).to.be.equal(3) } - await addAccountToAccountBlocklist(servers[1].url, servers[1].accessToken, remoteHandle) + await servers[1].blocklistCommand.addToMyBlocklist({ account: remoteHandle }) { const json = await servers[1].feedCommand.getJSON({ feed: 'video-comments', query: { version: 4 } }) diff --git a/shared/extra-utils/server/servers.ts b/shared/extra-utils/server/servers.ts index c2cab9818..3c709666d 100644 --- a/shared/extra-utils/server/servers.ts +++ b/shared/extra-utils/server/servers.ts @@ -17,7 +17,7 @@ import { OverviewsCommand } from '../overviews' import { makeGetRequest } from '../requests/requests' import { SearchCommand } from '../search' import { SocketIOCommand } from '../socket' -import { AccountsCommand } from '../users' +import { AccountsCommand, BlocklistCommand } from '../users' import { ConfigCommand } from './config-command' import { ContactFormCommand } from './contact-form-command' import { DebugCommand } from './debug-command' @@ -97,6 +97,7 @@ interface ServerInfo { configCommand?: ConfigCommand socketIOCommand?: SocketIOCommand accountsCommand?: AccountsCommand + blocklistCommand?: BlocklistCommand } function parallelTests () { @@ -320,6 +321,7 @@ async function runServer (server: ServerInfo, configOverrideArg?: any, args = [] server.configCommand = new ConfigCommand(server) server.socketIOCommand = new SocketIOCommand(server) server.accountsCommand = new AccountsCommand(server) + server.blocklistCommand = new BlocklistCommand(server) res(server) }) diff --git a/shared/extra-utils/socket/socket-io-command.ts b/shared/extra-utils/socket/socket-io-command.ts index 545561bed..c277ead28 100644 --- a/shared/extra-utils/socket/socket-io-command.ts +++ b/shared/extra-utils/socket/socket-io-command.ts @@ -5,7 +5,7 @@ export class SocketIOCommand extends AbstractCommand { getUserNotificationSocket (options: OverrideCommandOptions = {}) { return io(this.server.url + '/user-notifications', { - query: { accessToken: this.server.accessToken } + query: { accessToken: options.token ?? this.server.accessToken } }) } diff --git a/shared/extra-utils/users/blocklist-command.ts b/shared/extra-utils/users/blocklist-command.ts new file mode 100644 index 000000000..96afdc3fd --- /dev/null +++ b/shared/extra-utils/users/blocklist-command.ts @@ -0,0 +1,135 @@ +/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ + +import { HttpStatusCode } from '@shared/core-utils' +import { AccountBlock, ResultList, ServerBlock } from '@shared/models' +import { AbstractCommand, OverrideCommandOptions } from '../shared' + +type ListBlocklistOptions = OverrideCommandOptions & { + start: number + count: number + sort: string // default -createdAt +} + +export class BlocklistCommand extends AbstractCommand { + + listMyAccountBlocklist (options: ListBlocklistOptions) { + const path = '/api/v1/users/me/blocklist/accounts' + + return this.listBlocklist(options, path) + } + + listMyServerBlocklist (options: ListBlocklistOptions) { + const path = '/api/v1/users/me/blocklist/servers' + + return this.listBlocklist(options, path) + } + + listServerAccountBlocklist (options: ListBlocklistOptions) { + const path = '/api/v1/server/blocklist/accounts' + + return this.listBlocklist(options, path) + } + + listServerServerBlocklist (options: ListBlocklistOptions) { + const path = '/api/v1/server/blocklist/servers' + + return this.listBlocklist(options, path) + } + + // --------------------------------------------------------------------------- + + addToMyBlocklist (options: OverrideCommandOptions & { + account?: string + server?: string + }) { + const { account, server } = options + + const path = account + ? '/api/v1/users/me/blocklist/accounts' + : '/api/v1/users/me/blocklist/servers' + + return this.postBodyRequest({ + ...options, + + path, + fields: { + accountName: account, + host: server + }, + defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 + }) + } + + addToServerBlocklist (options: OverrideCommandOptions & { + account?: string + server?: string + }) { + const { account, server } = options + + const path = account + ? '/api/v1/server/blocklist/accounts' + : '/api/v1/server/blocklist/servers' + + return this.postBodyRequest({ + ...options, + + path, + fields: { + accountName: account, + host: server + }, + defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 + }) + } + + // --------------------------------------------------------------------------- + + removeFromMyBlocklist (options: OverrideCommandOptions & { + account?: string + server?: string + }) { + const { account, server } = options + + const path = account + ? '/api/v1/users/me/blocklist/accounts/' + account + : '/api/v1/users/me/blocklist/servers/' + server + + return this.deleteRequest({ + ...options, + + path, + defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 + }) + } + + removeFromServerBlocklist (options: OverrideCommandOptions & { + account?: string + server?: string + }) { + const { account, server } = options + + const path = account + ? '/api/v1/server/blocklist/accounts/' + account + : '/api/v1/server/blocklist/servers/' + server + + return this.deleteRequest({ + ...options, + + path, + defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 + }) + } + + private listBlocklist (options: ListBlocklistOptions, path: string) { + const { start, count, sort = '-createdAt' } = options + + return this.getRequestBody>({ + ...options, + + path, + query: { start, count, sort }, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } + +} diff --git a/shared/extra-utils/users/blocklist.ts b/shared/extra-utils/users/blocklist.ts deleted file mode 100644 index bdf7ee58a..000000000 --- a/shared/extra-utils/users/blocklist.ts +++ /dev/null @@ -1,238 +0,0 @@ -/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ - -import { makeGetRequest, makeDeleteRequest, makePostBodyRequest } from '../requests/requests' -import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' - -function getAccountBlocklistByAccount ( - url: string, - token: string, - start: number, - count: number, - sort = '-createdAt', - statusCodeExpected = HttpStatusCode.OK_200 -) { - const path = '/api/v1/users/me/blocklist/accounts' - - return makeGetRequest({ - url, - token, - query: { start, count, sort }, - path, - statusCodeExpected - }) -} - -function addAccountToAccountBlocklist ( - url: string, - token: string, - accountToBlock: string, - statusCodeExpected = HttpStatusCode.NO_CONTENT_204 -) { - const path = '/api/v1/users/me/blocklist/accounts' - - return makePostBodyRequest({ - url, - path, - token, - fields: { - accountName: accountToBlock - }, - statusCodeExpected - }) -} - -function removeAccountFromAccountBlocklist ( - url: string, - token: string, - accountToUnblock: string, - statusCodeExpected = HttpStatusCode.NO_CONTENT_204 -) { - const path = '/api/v1/users/me/blocklist/accounts/' + accountToUnblock - - return makeDeleteRequest({ - url, - path, - token, - statusCodeExpected - }) -} - -function getServerBlocklistByAccount ( - url: string, - token: string, - start: number, - count: number, - sort = '-createdAt', - statusCodeExpected = HttpStatusCode.OK_200 -) { - const path = '/api/v1/users/me/blocklist/servers' - - return makeGetRequest({ - url, - token, - query: { start, count, sort }, - path, - statusCodeExpected - }) -} - -function addServerToAccountBlocklist ( - url: string, - token: string, - serverToBlock: string, - statusCodeExpected = HttpStatusCode.NO_CONTENT_204 -) { - const path = '/api/v1/users/me/blocklist/servers' - - return makePostBodyRequest({ - url, - path, - token, - fields: { - host: serverToBlock - }, - statusCodeExpected - }) -} - -function removeServerFromAccountBlocklist ( - url: string, - token: string, - serverToBlock: string, - statusCodeExpected = HttpStatusCode.NO_CONTENT_204 -) { - const path = '/api/v1/users/me/blocklist/servers/' + serverToBlock - - return makeDeleteRequest({ - url, - path, - token, - statusCodeExpected - }) -} - -function getAccountBlocklistByServer ( - url: string, - token: string, - start: number, - count: number, - sort = '-createdAt', - statusCodeExpected = HttpStatusCode.OK_200 -) { - const path = '/api/v1/server/blocklist/accounts' - - return makeGetRequest({ - url, - token, - query: { start, count, sort }, - path, - statusCodeExpected - }) -} - -function addAccountToServerBlocklist ( - url: string, - token: string, - accountToBlock: string, - statusCodeExpected = HttpStatusCode.NO_CONTENT_204 -) { - const path = '/api/v1/server/blocklist/accounts' - - return makePostBodyRequest({ - url, - path, - token, - fields: { - accountName: accountToBlock - }, - statusCodeExpected - }) -} - -function removeAccountFromServerBlocklist ( - url: string, - token: string, - accountToUnblock: string, - statusCodeExpected = HttpStatusCode.NO_CONTENT_204 -) { - const path = '/api/v1/server/blocklist/accounts/' + accountToUnblock - - return makeDeleteRequest({ - url, - path, - token, - statusCodeExpected - }) -} - -function getServerBlocklistByServer ( - url: string, - token: string, - start: number, - count: number, - sort = '-createdAt', - statusCodeExpected = HttpStatusCode.OK_200 -) { - const path = '/api/v1/server/blocklist/servers' - - return makeGetRequest({ - url, - token, - query: { start, count, sort }, - path, - statusCodeExpected - }) -} - -function addServerToServerBlocklist ( - url: string, - token: string, - serverToBlock: string, - statusCodeExpected = HttpStatusCode.NO_CONTENT_204 -) { - const path = '/api/v1/server/blocklist/servers' - - return makePostBodyRequest({ - url, - path, - token, - fields: { - host: serverToBlock - }, - statusCodeExpected - }) -} - -function removeServerFromServerBlocklist ( - url: string, - token: string, - serverToBlock: string, - statusCodeExpected = HttpStatusCode.NO_CONTENT_204 -) { - const path = '/api/v1/server/blocklist/servers/' + serverToBlock - - return makeDeleteRequest({ - url, - path, - token, - statusCodeExpected - }) -} - -// --------------------------------------------------------------------------- - -export { - getAccountBlocklistByAccount, - addAccountToAccountBlocklist, - removeAccountFromAccountBlocklist, - getServerBlocklistByAccount, - addServerToAccountBlocklist, - removeServerFromAccountBlocklist, - - getAccountBlocklistByServer, - addAccountToServerBlocklist, - removeAccountFromServerBlocklist, - getServerBlocklistByServer, - addServerToServerBlocklist, - removeServerFromServerBlocklist -} diff --git a/shared/extra-utils/users/index.ts b/shared/extra-utils/users/index.ts index b3387ed8a..ea5dbbf14 100644 --- a/shared/extra-utils/users/index.ts +++ b/shared/extra-utils/users/index.ts @@ -1,7 +1,7 @@ -export * from './accounts' export * from './accounts-command' +export * from './accounts' +export * from './blocklist-command' -export * from './blocklist' export * from './login' export * from './user-notifications' export * from './user-subscriptions' -- cgit v1.2.3 From 2c27e70471120c92e0bc8c8114141fbb31ff98ac Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Wed, 7 Jul 2021 16:40:49 +0200 Subject: Introduce subscriptions command --- .../tests/api/moderation/blocklist-notification.ts | 10 +- .../api/notifications/moderation-notifications.ts | 10 +- .../tests/api/notifications/notifications-api.ts | 19 +-- .../tests/api/notifications/user-notifications.ts | 42 +++--- server/tests/api/users/user-subscriptions.ts | 144 +++++++++------------ server/tests/feeds/feeds.ts | 24 ++-- shared/extra-utils/server/servers.ts | 4 +- shared/extra-utils/users/index.ts | 2 +- shared/extra-utils/users/subscriptions-command.ts | 94 ++++++++++++++ shared/extra-utils/users/user-subscriptions.ts | 93 ------------- 10 files changed, 208 insertions(+), 234 deletions(-) create mode 100644 shared/extra-utils/users/subscriptions-command.ts delete mode 100644 shared/extra-utils/users/user-subscriptions.ts diff --git a/server/tests/api/moderation/blocklist-notification.ts b/server/tests/api/moderation/blocklist-notification.ts index 99da64a2d..5b9699816 100644 --- a/server/tests/api/moderation/blocklist-notification.ts +++ b/server/tests/api/moderation/blocklist-notification.ts @@ -3,7 +3,6 @@ import 'mocha' import * as chai from 'chai' import { - addUserSubscription, addVideoCommentThread, cleanupTests, createUser, @@ -11,7 +10,6 @@ import { flushAndRunMultipleServers, getUserNotifications, markAsReadAllNotifications, - removeUserSubscription, ServerInfo, setAccessTokensToServers, uploadVideo, @@ -44,8 +42,8 @@ describe('Test blocklist', function () { async function resetState () { try { - await removeUserSubscription(servers[1].url, remoteUserToken, 'user1_channel@' + servers[0].host) - await removeUserSubscription(servers[1].url, remoteUserToken, 'user2_channel@' + servers[0].host) + await servers[1].subscriptionsCommand.remove({ token: remoteUserToken, uri: 'user1_channel@' + servers[0].host }) + await servers[1].subscriptionsCommand.remove({ token: remoteUserToken, uri: 'user2_channel@' + servers[0].host }) } catch {} await waitJobs(servers) @@ -66,8 +64,8 @@ describe('Test blocklist', function () { { - await addUserSubscription(servers[1].url, remoteUserToken, 'user1_channel@' + servers[0].host) - await addUserSubscription(servers[1].url, remoteUserToken, 'user2_channel@' + servers[0].host) + await servers[1].subscriptionsCommand.add({ token: remoteUserToken, targetUri: 'user1_channel@' + servers[0].host }) + await servers[1].subscriptionsCommand.add({ token: remoteUserToken, targetUri: 'user2_channel@' + servers[0].host }) } await waitJobs(servers) diff --git a/server/tests/api/notifications/moderation-notifications.ts b/server/tests/api/notifications/moderation-notifications.ts index e90640ad6..605b41947 100644 --- a/server/tests/api/notifications/moderation-notifications.ts +++ b/server/tests/api/notifications/moderation-notifications.ts @@ -3,7 +3,6 @@ import 'mocha' import { buildUUID } from '@server/helpers/uuid' import { - addUserSubscription, addVideoCommentThread, addVideoToBlacklist, checkAbuseStateChange, @@ -29,7 +28,6 @@ import { MockSmtpServer, prepareNotificationsTest, registerUser, - removeUserSubscription, removeVideoFromBlacklist, ServerInfo, uploadVideo, @@ -488,8 +486,8 @@ describe('Test moderation notifications', function () { autoBlacklistTestsCustomConfig.transcoding.enabled = true await servers[0].configCommand.updateCustomConfig({ newCustomConfig: autoBlacklistTestsCustomConfig }) - await addUserSubscription(servers[0].url, servers[0].accessToken, 'user_1_channel@localhost:' + servers[0].port) - await addUserSubscription(servers[1].url, servers[1].accessToken, 'user_1_channel@localhost:' + servers[0].port) + await servers[0].subscriptionsCommand.add({ targetUri: 'user_1_channel@localhost:' + servers[0].port }) + await servers[1].subscriptionsCommand.add({ targetUri: 'user_1_channel@localhost:' + servers[0].port }) }) @@ -611,8 +609,8 @@ describe('Test moderation notifications', function () { after(async () => { await servers[0].configCommand.updateCustomConfig({ newCustomConfig: currentCustomConfig }) - await removeUserSubscription(servers[0].url, servers[0].accessToken, 'user_1_channel@localhost:' + servers[0].port) - await removeUserSubscription(servers[1].url, servers[1].accessToken, 'user_1_channel@localhost:' + servers[0].port) + await servers[0].subscriptionsCommand.remove({ uri: 'user_1_channel@localhost:' + servers[0].port }) + await servers[1].subscriptionsCommand.remove({ uri: 'user_1_channel@localhost:' + servers[0].port }) }) }) diff --git a/server/tests/api/notifications/notifications-api.ts b/server/tests/api/notifications/notifications-api.ts index 19f9dbbab..1ed98ae7a 100644 --- a/server/tests/api/notifications/notifications-api.ts +++ b/server/tests/api/notifications/notifications-api.ts @@ -2,21 +2,24 @@ import 'mocha' import * as chai from 'chai' -import { addUserSubscription } from '@shared/extra-utils/users/user-subscriptions' -import { cleanupTests, getMyUserInformation, immutableAssign, uploadRandomVideo, waitJobs } from '../../../../shared/extra-utils' -import { ServerInfo } from '../../../../shared/extra-utils/index' -import { MockSmtpServer } from '../../../../shared/extra-utils/mock-servers/mock-email' import { CheckerBaseParams, checkNewVideoFromSubscription, + cleanupTests, getAllNotificationsSettings, + getMyUserInformation, getUserNotifications, + immutableAssign, markAsReadAllNotifications, markAsReadNotifications, + MockSmtpServer, prepareNotificationsTest, - updateMyNotificationSettings -} from '../../../../shared/extra-utils/users/user-notifications' -import { User, UserNotification, UserNotificationSettingValue } from '../../../../shared/models/users' + ServerInfo, + updateMyNotificationSettings, + uploadRandomVideo, + waitJobs +} from '@shared/extra-utils' +import { User, UserNotification, UserNotificationSettingValue } from '@shared/models' const expect = chai.expect @@ -35,7 +38,7 @@ describe('Test notifications API', function () { userNotifications = res.userNotifications server = res.servers[0] - await addUserSubscription(server.url, userAccessToken, 'root_channel@localhost:' + server.port) + await server.subscriptionsCommand.add({ token: userAccessToken, targetUri: 'root_channel@localhost:' + server.port }) for (let i = 0; i < 10; i++) { await uploadRandomVideo(server, false) diff --git a/server/tests/api/notifications/user-notifications.ts b/server/tests/api/notifications/user-notifications.ts index ace7e48c7..15be983f2 100644 --- a/server/tests/api/notifications/user-notifications.ts +++ b/server/tests/api/notifications/user-notifications.ts @@ -3,30 +3,26 @@ import 'mocha' import * as chai from 'chai' import { buildUUID } from '@server/helpers/uuid' -import { - cleanupTests, - updateMyUser, - updateVideo, - updateVideoChannel, - uploadRandomVideoOnServers, - wait -} from '../../../../shared/extra-utils' -import { ServerInfo } from '../../../../shared/extra-utils/index' -import { MockSmtpServer } from '../../../../shared/extra-utils/mock-servers/mock-email' -import { waitJobs } from '../../../../shared/extra-utils/server/jobs' import { CheckerBaseParams, checkMyVideoImportIsFinished, checkNewActorFollow, checkNewVideoFromSubscription, checkVideoIsPublished, + cleanupTests, getLastNotification, - prepareNotificationsTest -} from '../../../../shared/extra-utils/users/user-notifications' -import { addUserSubscription, removeUserSubscription } from '../../../../shared/extra-utils/users/user-subscriptions' -import { getBadVideoUrl, getGoodVideoUrl, importVideo } from '../../../../shared/extra-utils/videos/video-imports' -import { UserNotification, UserNotificationType } from '../../../../shared/models/users' -import { VideoPrivacy } from '../../../../shared/models/videos' + MockSmtpServer, + prepareNotificationsTest, + ServerInfo, + updateMyUser, + updateVideo, + updateVideoChannel, + uploadRandomVideoOnServers, + wait, + waitJobs +} from '@shared/extra-utils' +import { getBadVideoUrl, getGoodVideoUrl, importVideo } from '@shared/extra-utils/videos/video-imports' +import { UserNotification, UserNotificationType, VideoPrivacy } from '@shared/models' const expect = chai.expect @@ -79,7 +75,7 @@ describe('Test user notifications', function () { it('Should send a new video notification if the user follows the local video publisher', async function () { this.timeout(15000) - await addUserSubscription(servers[0].url, userAccessToken, 'root_channel@localhost:' + servers[0].port) + await servers[0].subscriptionsCommand.add({ token: userAccessToken, targetUri: 'root_channel@localhost:' + servers[0].port }) await waitJobs(servers) const { name, uuid } = await uploadRandomVideoOnServers(servers, 1) @@ -89,7 +85,7 @@ describe('Test user notifications', function () { it('Should send a new video notification from a remote account', async function () { this.timeout(150000) // Server 2 has transcoding enabled - await addUserSubscription(servers[0].url, userAccessToken, 'root_channel@localhost:' + servers[1].port) + await servers[0].subscriptionsCommand.add({ token: userAccessToken, targetUri: 'root_channel@localhost:' + servers[1].port }) await waitJobs(servers) const { name, uuid } = await uploadRandomVideoOnServers(servers, 2) @@ -418,23 +414,23 @@ describe('Test user notifications', function () { it('Should notify when a local channel is following one of our channel', async function () { this.timeout(50000) - await addUserSubscription(servers[0].url, servers[0].accessToken, 'user_1_channel@localhost:' + servers[0].port) + await servers[0].subscriptionsCommand.add({ targetUri: 'user_1_channel@localhost:' + servers[0].port }) await waitJobs(servers) await checkNewActorFollow(baseParams, 'channel', 'root', 'super root name', myChannelName, 'presence') - await removeUserSubscription(servers[0].url, servers[0].accessToken, 'user_1_channel@localhost:' + servers[0].port) + await servers[0].subscriptionsCommand.remove({ uri: 'user_1_channel@localhost:' + servers[0].port }) }) it('Should notify when a remote channel is following one of our channel', async function () { this.timeout(50000) - await addUserSubscription(servers[1].url, servers[1].accessToken, 'user_1_channel@localhost:' + servers[0].port) + await servers[1].subscriptionsCommand.add({ targetUri: 'user_1_channel@localhost:' + servers[0].port }) await waitJobs(servers) await checkNewActorFollow(baseParams, 'channel', 'root', 'super root 2 name', myChannelName, 'presence') - await removeUserSubscription(servers[1].url, servers[1].accessToken, 'user_1_channel@localhost:' + servers[0].port) + await servers[1].subscriptionsCommand.remove({ uri: 'user_1_channel@localhost:' + servers[0].port }) }) // PeerTube does not support accout -> account follows diff --git a/server/tests/api/users/user-subscriptions.ts b/server/tests/api/users/user-subscriptions.ts index 7e365d797..c119622ad 100644 --- a/server/tests/api/users/user-subscriptions.ts +++ b/server/tests/api/users/user-subscriptions.ts @@ -3,25 +3,19 @@ import 'mocha' import * as chai from 'chai' import { - addUserSubscription, - areSubscriptionsExist, cleanupTests, createUser, doubleFollow, flushAndRunMultipleServers, - getUserSubscription, getVideosList, - listUserSubscriptions, - listUserSubscriptionVideos, - removeUserSubscription, ServerInfo, setAccessTokensToServers, + SubscriptionsCommand, updateVideo, uploadVideo, userLogin, waitJobs } from '@shared/extra-utils' -import { Video, VideoChannel } from '@shared/models' const expect = chai.expect @@ -30,6 +24,8 @@ describe('Test users subscriptions', function () { const users: { accessToken: string }[] = [] let video3UUID: string + let command: SubscriptionsCommand + before(async function () { this.timeout(120000) @@ -58,6 +54,8 @@ describe('Test users subscriptions', function () { } await waitJobs(servers) + + command = servers[0].subscriptionsCommand }) it('Should display videos of server 2 on server 1', async function () { @@ -69,8 +67,8 @@ describe('Test users subscriptions', function () { it('User of server 1 should follow user of server 3 and root of server 1', async function () { this.timeout(60000) - await addUserSubscription(servers[0].url, users[0].accessToken, 'user3_channel@localhost:' + servers[2].port) - await addUserSubscription(servers[0].url, users[0].accessToken, 'root_channel@localhost:' + servers[0].port) + await command.add({ token: users[0].accessToken, targetUri: 'user3_channel@localhost:' + servers[2].port }) + await command.add({ token: users[0].accessToken, targetUri: 'root_channel@localhost:' + servers[0].port }) await waitJobs(servers) @@ -93,17 +91,17 @@ describe('Test users subscriptions', function () { it('Should list subscriptions', async function () { { - const res = await listUserSubscriptions({ url: servers[0].url, token: servers[0].accessToken }) - expect(res.body.total).to.equal(0) - expect(res.body.data).to.be.an('array') - expect(res.body.data).to.have.lengthOf(0) + const body = await command.list() + expect(body.total).to.equal(0) + expect(body.data).to.be.an('array') + expect(body.data).to.have.lengthOf(0) } { - const res = await listUserSubscriptions({ url: servers[0].url, token: users[0].accessToken, sort: 'createdAt' }) - expect(res.body.total).to.equal(2) + const body = await command.list({ token: users[0].accessToken, sort: 'createdAt' }) + expect(body.total).to.equal(2) - const subscriptions: VideoChannel[] = res.body.data + const subscriptions = body.data expect(subscriptions).to.be.an('array') expect(subscriptions).to.have.lengthOf(2) @@ -114,8 +112,7 @@ describe('Test users subscriptions', function () { it('Should get subscription', async function () { { - const res = await getUserSubscription(servers[0].url, users[0].accessToken, 'user3_channel@localhost:' + servers[2].port) - const videoChannel: VideoChannel = res.body + const videoChannel = await command.get({ token: users[0].accessToken, uri: 'user3_channel@localhost:' + servers[2].port }) expect(videoChannel.name).to.equal('user3_channel') expect(videoChannel.host).to.equal('localhost:' + servers[2].port) @@ -125,8 +122,7 @@ describe('Test users subscriptions', function () { } { - const res = await getUserSubscription(servers[0].url, users[0].accessToken, 'root_channel@localhost:' + servers[0].port) - const videoChannel: VideoChannel = res.body + const videoChannel = await command.get({ token: users[0].accessToken, uri: 'root_channel@localhost:' + servers[0].port }) expect(videoChannel.name).to.equal('root_channel') expect(videoChannel.host).to.equal('localhost:' + servers[0].port) @@ -144,8 +140,7 @@ describe('Test users subscriptions', function () { 'user3_channel@localhost:' + servers[0].port ] - const res = await areSubscriptionsExist(servers[0].url, users[0].accessToken, uris) - const body = res.body + const body = await command.exist({ token: users[0].accessToken, uris }) expect(body['user3_channel@localhost:' + servers[2].port]).to.be.true expect(body['root2_channel@localhost:' + servers[0].port]).to.be.false @@ -155,45 +150,31 @@ describe('Test users subscriptions', function () { it('Should search among subscriptions', async function () { { - const res = await listUserSubscriptions({ - url: servers[0].url, - token: users[0].accessToken, - sort: '-createdAt', - search: 'user3_channel' - }) - expect(res.body.total).to.equal(1) - - const subscriptions = res.body.data - expect(subscriptions).to.have.lengthOf(1) + const body = await command.list({ token: users[0].accessToken, sort: '-createdAt', search: 'user3_channel' }) + expect(body.total).to.equal(1) + expect(body.data).to.have.lengthOf(1) } { - const res = await listUserSubscriptions({ - url: servers[0].url, - token: users[0].accessToken, - sort: '-createdAt', - search: 'toto' - }) - expect(res.body.total).to.equal(0) - - const subscriptions = res.body.data - expect(subscriptions).to.have.lengthOf(0) + const body = await command.list({ token: users[0].accessToken, sort: '-createdAt', search: 'toto' }) + expect(body.total).to.equal(0) + expect(body.data).to.have.lengthOf(0) } }) it('Should list subscription videos', async function () { { - const res = await listUserSubscriptionVideos(servers[0].url, servers[0].accessToken) - expect(res.body.total).to.equal(0) - expect(res.body.data).to.be.an('array') - expect(res.body.data).to.have.lengthOf(0) + const body = await command.listVideos() + expect(body.total).to.equal(0) + expect(body.data).to.be.an('array') + expect(body.data).to.have.lengthOf(0) } { - const res = await listUserSubscriptionVideos(servers[0].url, users[0].accessToken, 'createdAt') - expect(res.body.total).to.equal(3) + const body = await command.listVideos({ token: users[0].accessToken, sort: 'createdAt' }) + expect(body.total).to.equal(3) - const videos: Video[] = res.body.data + const videos = body.data expect(videos).to.be.an('array') expect(videos).to.have.lengthOf(3) @@ -212,17 +193,17 @@ describe('Test users subscriptions', function () { await waitJobs(servers) { - const res = await listUserSubscriptionVideos(servers[0].url, servers[0].accessToken) - expect(res.body.total).to.equal(0) - expect(res.body.data).to.be.an('array') - expect(res.body.data).to.have.lengthOf(0) + const body = await command.listVideos() + expect(body.total).to.equal(0) + expect(body.data).to.be.an('array') + expect(body.data).to.have.lengthOf(0) } { - const res = await listUserSubscriptionVideos(servers[0].url, users[0].accessToken, 'createdAt') - expect(res.body.total).to.equal(4) + const body = await command.listVideos({ token: users[0].accessToken, sort: 'createdAt' }) + expect(body.total).to.equal(4) - const videos: Video[] = res.body.data + const videos = body.data expect(videos).to.be.an('array') expect(videos).to.have.lengthOf(4) @@ -281,17 +262,17 @@ describe('Test users subscriptions', function () { it('Should still list subscription videos', async function () { { - const res = await listUserSubscriptionVideos(servers[0].url, servers[0].accessToken) - expect(res.body.total).to.equal(0) - expect(res.body.data).to.be.an('array') - expect(res.body.data).to.have.lengthOf(0) + const body = await command.listVideos() + expect(body.total).to.equal(0) + expect(body.data).to.be.an('array') + expect(body.data).to.have.lengthOf(0) } { - const res = await listUserSubscriptionVideos(servers[0].url, users[0].accessToken, 'createdAt') - expect(res.body.total).to.equal(4) + const body = await command.listVideos({ token: users[0].accessToken, sort: 'createdAt' }) + expect(body.total).to.equal(4) - const videos: Video[] = res.body.data + const videos = body.data expect(videos).to.be.an('array') expect(videos).to.have.lengthOf(4) @@ -309,44 +290,41 @@ describe('Test users subscriptions', function () { await waitJobs(servers) - const res = await listUserSubscriptionVideos(servers[0].url, users[0].accessToken, 'createdAt') - const videos: Video[] = res.body.data - expect(videos[2].name).to.equal('video server 3 added after follow updated') + const body = await command.listVideos({ token: users[0].accessToken, sort: 'createdAt' }) + expect(body.data[2].name).to.equal('video server 3 added after follow updated') }) it('Should remove user of server 3 subscription', async function () { this.timeout(30000) - await removeUserSubscription(servers[0].url, users[0].accessToken, 'user3_channel@localhost:' + servers[2].port) + await command.remove({ token: users[0].accessToken, uri: 'user3_channel@localhost:' + servers[2].port }) await waitJobs(servers) }) it('Should not display its videos anymore', async function () { - { - const res = await listUserSubscriptionVideos(servers[0].url, users[0].accessToken, 'createdAt') - expect(res.body.total).to.equal(1) + const body = await command.listVideos({ token: users[0].accessToken, sort: 'createdAt' }) + expect(body.total).to.equal(1) - const videos: Video[] = res.body.data - expect(videos).to.be.an('array') - expect(videos).to.have.lengthOf(1) + const videos = body.data + expect(videos).to.be.an('array') + expect(videos).to.have.lengthOf(1) - expect(videos[0].name).to.equal('video server 1 added after follow') - } + expect(videos[0].name).to.equal('video server 1 added after follow') }) it('Should remove the root subscription and not display the videos anymore', async function () { this.timeout(30000) - await removeUserSubscription(servers[0].url, users[0].accessToken, 'root_channel@localhost:' + servers[0].port) + await command.remove({ token: users[0].accessToken, uri: 'root_channel@localhost:' + servers[0].port }) await waitJobs(servers) { - const res = await listUserSubscriptionVideos(servers[0].url, users[0].accessToken, 'createdAt') - expect(res.body.total).to.equal(0) + const body = await command.list({ token: users[0].accessToken, sort: 'createdAt' }) + expect(body.total).to.equal(0) - const videos: Video[] = res.body.data + const videos = body.data expect(videos).to.be.an('array') expect(videos).to.have.lengthOf(0) } @@ -366,15 +344,15 @@ describe('Test users subscriptions', function () { it('Should follow user of server 3 again', async function () { this.timeout(60000) - await addUserSubscription(servers[0].url, users[0].accessToken, 'user3_channel@localhost:' + servers[2].port) + await command.add({ token: users[0].accessToken, targetUri: 'user3_channel@localhost:' + servers[2].port }) await waitJobs(servers) { - const res = await listUserSubscriptionVideos(servers[0].url, users[0].accessToken, 'createdAt') - expect(res.body.total).to.equal(3) + const body = await command.listVideos({ token: users[0].accessToken, sort: 'createdAt' }) + expect(body.total).to.equal(3) - const videos: Video[] = res.body.data + const videos = body.data expect(videos).to.be.an('array') expect(videos).to.have.lengthOf(3) diff --git a/server/tests/feeds/feeds.ts b/server/tests/feeds/feeds.ts index 17efc666d..6ee22340b 100644 --- a/server/tests/feeds/feeds.ts +++ b/server/tests/feeds/feeds.ts @@ -5,7 +5,6 @@ import * as chai from 'chai' import * as xmlParser from 'fast-xml-parser' import { HttpStatusCode } from '@shared/core-utils' import { - addUserSubscription, addVideoCommentThread, cleanupTests, createUser, @@ -14,7 +13,6 @@ import { flushAndRunServer, getMyUserInformation, getUserScopedTokens, - listUserSubscriptionVideos, renewUserScopedTokens, ServerInfo, setAccessTokensToServers, @@ -319,8 +317,8 @@ describe('Test syndication feeds', () => { } { - const res = await listUserSubscriptionVideos(servers[0].url, feeduserAccessToken) - expect(res.body.total).to.equal(0) + const body = await servers[0].subscriptionsCommand.listVideos({ token: feeduserAccessToken }) + expect(body.total).to.equal(0) const query = { accountId: feeduserAccountId, token: feeduserFeedToken } const json = await servers[0].feedCommand.getJSON({ feed: 'subscriptions', query }) @@ -340,8 +338,8 @@ describe('Test syndication feeds', () => { }) it('Should list no videos for a user with videos but no subscriptions', async function () { - const res = await listUserSubscriptionVideos(servers[0].url, userAccessToken) - expect(res.body.total).to.equal(0) + const body = await servers[0].subscriptionsCommand.listVideos({ token: userAccessToken }) + expect(body.total).to.equal(0) const query = { accountId: userAccountId, token: userFeedToken } const json = await servers[0].feedCommand.getJSON({ feed: 'subscriptions', query }) @@ -352,13 +350,13 @@ describe('Test syndication feeds', () => { it('Should list self videos for a user with a subscription to themselves', async function () { this.timeout(30000) - await addUserSubscription(servers[0].url, userAccessToken, 'john_channel@localhost:' + servers[0].port) + await servers[0].subscriptionsCommand.add({ token: userAccessToken, targetUri: 'john_channel@localhost:' + servers[0].port }) await waitJobs(servers) { - const res = await listUserSubscriptionVideos(servers[0].url, userAccessToken) - expect(res.body.total).to.equal(1) - expect(res.body.data[0].name).to.equal('user video') + const body = await servers[0].subscriptionsCommand.listVideos({ token: userAccessToken }) + expect(body.total).to.equal(1) + expect(body.data[0].name).to.equal('user video') const query = { accountId: userAccountId, token: userFeedToken, version: 1 } const json = await servers[0].feedCommand.getJSON({ feed: 'subscriptions', query }) @@ -370,12 +368,12 @@ describe('Test syndication feeds', () => { it('Should list videos of a user\'s subscription', async function () { this.timeout(30000) - await addUserSubscription(servers[0].url, userAccessToken, 'root_channel@localhost:' + servers[0].port) + await servers[0].subscriptionsCommand.add({ token: userAccessToken, targetUri: 'root_channel@localhost:' + servers[0].port }) await waitJobs(servers) { - const res = await listUserSubscriptionVideos(servers[0].url, userAccessToken) - expect(res.body.total).to.equal(2, "there should be 2 videos part of the subscription") + const body = await servers[0].subscriptionsCommand.listVideos({ token: userAccessToken }) + expect(body.total).to.equal(2, "there should be 2 videos part of the subscription") const query = { accountId: userAccountId, token: userFeedToken, version: 2 } const json = await servers[0].feedCommand.getJSON({ feed: 'subscriptions', query }) diff --git a/shared/extra-utils/server/servers.ts b/shared/extra-utils/server/servers.ts index 3c709666d..57b37728a 100644 --- a/shared/extra-utils/server/servers.ts +++ b/shared/extra-utils/server/servers.ts @@ -17,7 +17,7 @@ import { OverviewsCommand } from '../overviews' import { makeGetRequest } from '../requests/requests' import { SearchCommand } from '../search' import { SocketIOCommand } from '../socket' -import { AccountsCommand, BlocklistCommand } from '../users' +import { AccountsCommand, BlocklistCommand, SubscriptionsCommand } from '../users' import { ConfigCommand } from './config-command' import { ContactFormCommand } from './contact-form-command' import { DebugCommand } from './debug-command' @@ -98,6 +98,7 @@ interface ServerInfo { socketIOCommand?: SocketIOCommand accountsCommand?: AccountsCommand blocklistCommand?: BlocklistCommand + subscriptionsCommand?: SubscriptionsCommand } function parallelTests () { @@ -322,6 +323,7 @@ async function runServer (server: ServerInfo, configOverrideArg?: any, args = [] server.socketIOCommand = new SocketIOCommand(server) server.accountsCommand = new AccountsCommand(server) server.blocklistCommand = new BlocklistCommand(server) + server.subscriptionsCommand = new SubscriptionsCommand(server) res(server) }) diff --git a/shared/extra-utils/users/index.ts b/shared/extra-utils/users/index.ts index ea5dbbf14..94ad37242 100644 --- a/shared/extra-utils/users/index.ts +++ b/shared/extra-utils/users/index.ts @@ -4,5 +4,5 @@ export * from './blocklist-command' export * from './login' export * from './user-notifications' -export * from './user-subscriptions' +export * from './subscriptions-command' export * from './users' diff --git a/shared/extra-utils/users/subscriptions-command.ts b/shared/extra-utils/users/subscriptions-command.ts new file mode 100644 index 000000000..94d2af67a --- /dev/null +++ b/shared/extra-utils/users/subscriptions-command.ts @@ -0,0 +1,94 @@ +import { ResultList, Video, VideoChannel } from '@shared/models' +import { HttpStatusCode } from '../../core-utils/miscs/http-error-codes' +import { AbstractCommand, OverrideCommandOptions } from '../shared' + +export class SubscriptionsCommand extends AbstractCommand { + + add (options: OverrideCommandOptions & { + targetUri: string + }) { + const path = '/api/v1/users/me/subscriptions' + + return this.postBodyRequest({ + ...options, + + path, + fields: { uri: options.targetUri }, + defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 + }) + } + + list (options: OverrideCommandOptions & { + sort?: string // default -createdAt + search?: string + } = {}) { + const { sort = '-createdAt', search } = options + const path = '/api/v1/users/me/subscriptions' + + return this.getRequestBody>({ + ...options, + + path, + query: { + sort, + search + }, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } + + listVideos (options: OverrideCommandOptions & { + sort?: string // default -createdAt + } = {}) { + const { sort = '-createdAt' } = options + const path = '/api/v1/users/me/subscriptions/videos' + + return this.getRequestBody>({ + ...options, + + path, + query: { sort }, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } + + get (options: OverrideCommandOptions & { + uri: string + }) { + const path = '/api/v1/users/me/subscriptions/' + options.uri + + return this.getRequestBody({ + ...options, + + path, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } + + remove (options: OverrideCommandOptions & { + uri: string + }) { + const path = '/api/v1/users/me/subscriptions/' + options.uri + + return this.deleteRequest({ + ...options, + + path, + defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 + }) + } + + exist (options: OverrideCommandOptions & { + uris: string[] + }) { + const path = '/api/v1/users/me/subscriptions/exist' + + return this.getRequestBody<{ [id: string ]: boolean }>({ + ...options, + + path, + query: { 'uris[]': options.uris }, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } +} diff --git a/shared/extra-utils/users/user-subscriptions.ts b/shared/extra-utils/users/user-subscriptions.ts deleted file mode 100644 index edc7a3562..000000000 --- a/shared/extra-utils/users/user-subscriptions.ts +++ /dev/null @@ -1,93 +0,0 @@ -import { makeDeleteRequest, makeGetRequest, makePostBodyRequest } from '../requests/requests' -import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' - -function addUserSubscription (url: string, token: string, targetUri: string, statusCodeExpected = HttpStatusCode.NO_CONTENT_204) { - const path = '/api/v1/users/me/subscriptions' - - return makePostBodyRequest({ - url, - path, - token, - statusCodeExpected, - fields: { uri: targetUri } - }) -} - -function listUserSubscriptions (parameters: { - url: string - token: string - sort?: string - search?: string - statusCodeExpected?: number -}) { - const { url, token, sort = '-createdAt', search, statusCodeExpected = HttpStatusCode.OK_200 } = parameters - const path = '/api/v1/users/me/subscriptions' - - return makeGetRequest({ - url, - path, - token, - statusCodeExpected, - query: { - sort, - search - } - }) -} - -function listUserSubscriptionVideos (url: string, token: string, sort = '-createdAt', statusCodeExpected = HttpStatusCode.OK_200) { - const path = '/api/v1/users/me/subscriptions/videos' - - return makeGetRequest({ - url, - path, - token, - statusCodeExpected, - query: { sort } - }) -} - -function getUserSubscription (url: string, token: string, uri: string, statusCodeExpected = HttpStatusCode.OK_200) { - const path = '/api/v1/users/me/subscriptions/' + uri - - return makeGetRequest({ - url, - path, - token, - statusCodeExpected - }) -} - -function removeUserSubscription (url: string, token: string, uri: string, statusCodeExpected = HttpStatusCode.NO_CONTENT_204) { - const path = '/api/v1/users/me/subscriptions/' + uri - - return makeDeleteRequest({ - url, - path, - token, - statusCodeExpected - }) -} - -function areSubscriptionsExist (url: string, token: string, uris: string[], statusCodeExpected = HttpStatusCode.OK_200) { - const path = '/api/v1/users/me/subscriptions/exist' - - return makeGetRequest({ - url, - path, - query: { 'uris[]': uris }, - token, - statusCodeExpected - }) -} - -// --------------------------------------------------------------------------- - -export { - areSubscriptionsExist, - addUserSubscription, - listUserSubscriptions, - getUserSubscription, - listUserSubscriptionVideos, - removeUserSubscription -} -- cgit v1.2.3 From 4f2199144e428c16460750305f737b890c1ac322 Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Thu, 8 Jul 2021 10:18:40 +0200 Subject: Introduce live command --- server/tests/api/check-params/live.ts | 72 +++++----- server/tests/api/live/live-constraints.ts | 21 ++- server/tests/api/live/live-permanent.ts | 43 +++--- server/tests/api/live/live-save-replay.ts | 29 ++-- server/tests/api/live/live-socket-messages.ts | 19 ++- server/tests/api/live/live-views.ts | 8 +- server/tests/api/live/live.ts | 90 ++++++------- server/tests/api/search/search-videos.ts | 22 ++- server/tests/api/videos/video-change-ownership.ts | 5 +- server/tests/plugins/action-hooks.ts | 3 +- server/tests/plugins/filter-hooks.ts | 3 +- server/tests/plugins/plugin-transcoding.ts | 28 ++-- shared/extra-utils/index.ts | 16 +-- shared/extra-utils/requests/index.ts | 3 + shared/extra-utils/server/servers.ts | 3 + shared/extra-utils/shared/abstract-command.ts | 32 ++++- shared/extra-utils/users/index.ts | 1 - shared/extra-utils/videos/index.ts | 13 ++ shared/extra-utils/videos/live-command.ts | 156 ++++++++++++++++++++++ shared/extra-utils/videos/live.ts | 139 +------------------ 20 files changed, 369 insertions(+), 337 deletions(-) create mode 100644 shared/extra-utils/requests/index.ts create mode 100644 shared/extra-utils/videos/index.ts create mode 100644 shared/extra-utils/videos/live-command.ts diff --git a/server/tests/api/check-params/live.ts b/server/tests/api/check-params/live.ts index 7a623c169..56116848f 100644 --- a/server/tests/api/check-params/live.ts +++ b/server/tests/api/check-params/live.ts @@ -2,27 +2,24 @@ import 'mocha' import { omit } from 'lodash' -import { LiveVideo, VideoCreateResult, VideoPrivacy } from '@shared/models' +import { VideoCreateResult, VideoPrivacy } from '@shared/models' import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' import { buildAbsoluteFixturePath, cleanupTests, createUser, flushAndRunServer, - getLive, getMyUserInformation, immutableAssign, + LiveCommand, makePostBodyRequest, makeUploadRequest, - runAndTestFfmpegStreamError, sendRTMPStream, ServerInfo, setAccessTokensToServers, stopFfmpeg, - updateLive, uploadVideoAndGetId, - userLogin, - waitUntilLivePublished + userLogin } from '../../../../shared/extra-utils' describe('Test video lives API validator', function () { @@ -32,6 +29,7 @@ describe('Test video lives API validator', function () { let channelId: number let video: VideoCreateResult let videoIdNotLive: number + let command: LiveCommand // --------------------------------------------------------------- @@ -66,6 +64,8 @@ describe('Test video lives API validator', function () { { videoIdNotLive = (await uploadVideoAndGetId({ server, videoName: 'not live' })).id } + + command = server.liveCommand }) describe('When creating a live', function () { @@ -337,70 +337,72 @@ describe('Test video lives API validator', function () { describe('When getting live information', function () { it('Should fail without access token', async function () { - await getLive(server.url, '', video.id, HttpStatusCode.UNAUTHORIZED_401) + await command.getLive({ token: '', videoId: video.id, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should fail with a bad access token', async function () { - await getLive(server.url, 'toto', video.id, HttpStatusCode.UNAUTHORIZED_401) + await command.getLive({ token: 'toto', videoId: video.id, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should fail with access token of another user', async function () { - await getLive(server.url, userAccessToken, video.id, HttpStatusCode.FORBIDDEN_403) + await command.getLive({ token: userAccessToken, videoId: video.id, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) it('Should fail with a bad video id', async function () { - await getLive(server.url, server.accessToken, 'toto', HttpStatusCode.BAD_REQUEST_400) + await command.getLive({ videoId: 'toto', expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) it('Should fail with an unknown video id', async function () { - await getLive(server.url, server.accessToken, 454555, HttpStatusCode.NOT_FOUND_404) + await command.getLive({ videoId: 454555, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) it('Should fail with a non live video', async function () { - await getLive(server.url, server.accessToken, videoIdNotLive, HttpStatusCode.NOT_FOUND_404) + await command.getLive({ videoId: videoIdNotLive, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) it('Should succeed with the correct params', async function () { - await getLive(server.url, server.accessToken, video.id) - await getLive(server.url, server.accessToken, video.shortUUID) + await command.getLive({ videoId: video.id }) + await command.getLive({ videoId: video.uuid }) + await command.getLive({ videoId: video.shortUUID }) }) }) describe('When updating live information', async function () { it('Should fail without access token', async function () { - await updateLive(server.url, '', video.id, {}, HttpStatusCode.UNAUTHORIZED_401) + await command.updateLive({ token: '', videoId: video.id, fields: {}, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should fail with a bad access token', async function () { - await updateLive(server.url, 'toto', video.id, {}, HttpStatusCode.UNAUTHORIZED_401) + await command.updateLive({ token: 'toto', videoId: video.id, fields: {}, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should fail with access token of another user', async function () { - await updateLive(server.url, userAccessToken, video.id, {}, HttpStatusCode.FORBIDDEN_403) + await command.updateLive({ token: userAccessToken, videoId: video.id, fields: {}, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) it('Should fail with a bad video id', async function () { - await updateLive(server.url, server.accessToken, 'toto', {}, HttpStatusCode.BAD_REQUEST_400) + await command.updateLive({ videoId: 'toto', fields: {}, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) it('Should fail with an unknown video id', async function () { - await updateLive(server.url, server.accessToken, 454555, {}, HttpStatusCode.NOT_FOUND_404) + await command.updateLive({ videoId: 454555, fields: {}, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) it('Should fail with a non live video', async function () { - await updateLive(server.url, server.accessToken, videoIdNotLive, {}, HttpStatusCode.NOT_FOUND_404) + await command.updateLive({ videoId: videoIdNotLive, fields: {}, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) it('Should fail with save replay and permanent live set to true', async function () { const fields = { saveReplay: true, permanentLive: true } - await updateLive(server.url, server.accessToken, video.id, fields, HttpStatusCode.BAD_REQUEST_400) + await command.updateLive({ videoId: video.id, fields, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) it('Should succeed with the correct params', async function () { - await updateLive(server.url, server.accessToken, video.id, { saveReplay: false }) - await updateLive(server.url, server.accessToken, video.shortUUID, { saveReplay: false }) + await command.updateLive({ videoId: video.id, fields: { saveReplay: false } }) + await command.updateLive({ videoId: video.uuid, fields: { saveReplay: false } }) + await command.updateLive({ videoId: video.shortUUID, fields: { saveReplay: false } }) }) it('Should fail to update replay status if replay is not allowed on the instance', async function () { @@ -413,36 +415,34 @@ describe('Test video lives API validator', function () { } }) - await updateLive(server.url, server.accessToken, video.id, { saveReplay: true }, HttpStatusCode.FORBIDDEN_403) + await command.updateLive({ videoId: video.id, fields: { saveReplay: true }, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) it('Should fail to update a live if it has already started', async function () { this.timeout(40000) - const resLive = await getLive(server.url, server.accessToken, video.id) - const live: LiveVideo = resLive.body + const live = await command.getLive({ videoId: video.id }) - const command = sendRTMPStream(live.rtmpUrl, live.streamKey) + const ffmpegCommand = sendRTMPStream(live.rtmpUrl, live.streamKey) - await waitUntilLivePublished(server.url, server.accessToken, video.id) - await updateLive(server.url, server.accessToken, video.id, {}, HttpStatusCode.BAD_REQUEST_400) + await command.waitUntilLivePublished({ videoId: video.id }) + await command.updateLive({ videoId: video.id, fields: {}, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) - await stopFfmpeg(command) + await stopFfmpeg(ffmpegCommand) }) it('Should fail to stream twice in the save live', async function () { this.timeout(40000) - const resLive = await getLive(server.url, server.accessToken, video.id) - const live: LiveVideo = resLive.body + const live = await command.getLive({ videoId: video.id }) - const command = sendRTMPStream(live.rtmpUrl, live.streamKey) + const ffmpegCommand = sendRTMPStream(live.rtmpUrl, live.streamKey) - await waitUntilLivePublished(server.url, server.accessToken, video.id) + await command.waitUntilLivePublished({ videoId: video.id }) - await runAndTestFfmpegStreamError(server.url, server.accessToken, video.id, true) + await command.runAndTestFfmpegStreamError({ videoId: video.id, shouldHaveError: true }) - await stopFfmpeg(command) + await stopFfmpeg(ffmpegCommand) }) }) diff --git a/server/tests/api/live/live-constraints.ts b/server/tests/api/live/live-constraints.ts index c64d10dcd..5c4817b40 100644 --- a/server/tests/api/live/live-constraints.ts +++ b/server/tests/api/live/live-constraints.ts @@ -7,19 +7,16 @@ import { checkLiveCleanup, cleanupTests, ConfigCommand, - createLive, doubleFollow, flushAndRunMultipleServers, generateUser, getVideo, - runAndTestFfmpegStreamError, ServerInfo, setAccessTokensToServers, setDefaultVideoChannel, updateUser, wait, - waitJobs, - waitUntilLivePublished + waitJobs } from '../../../../shared/extra-utils' const expect = chai.expect @@ -38,8 +35,8 @@ describe('Test live constraints', function () { saveReplay } - const res = await createLive(servers[0].url, userAccessToken, liveAttributes) - return res.body.video.uuid as string + const { uuid } = await servers[0].liveCommand.createLive({ token: userAccessToken, fields: liveAttributes }) + return uuid } async function checkSaveReplay (videoId: string, resolutions = [ 720 ]) { @@ -56,7 +53,7 @@ describe('Test live constraints', function () { async function waitUntilLivePublishedOnAllServers (videoId: string) { for (const server of servers) { - await waitUntilLivePublished(server.url, server.accessToken, videoId) + await server.liveCommand.waitUntilLivePublished({ videoId }) } } @@ -108,7 +105,7 @@ describe('Test live constraints', function () { this.timeout(60000) const userVideoLiveoId = await createLiveWrapper(false) - await runAndTestFfmpegStreamError(servers[0].url, userAccessToken, userVideoLiveoId, false) + await servers[0].liveCommand.runAndTestFfmpegStreamError({ token: userAccessToken, videoId: userVideoLiveoId, shouldHaveError: false }) }) it('Should have size limit depending on user global quota if save replay is enabled', async function () { @@ -118,7 +115,7 @@ describe('Test live constraints', function () { await wait(5000) const userVideoLiveoId = await createLiveWrapper(true) - await runAndTestFfmpegStreamError(servers[0].url, userAccessToken, userVideoLiveoId, true) + await servers[0].liveCommand.runAndTestFfmpegStreamError({ token: userAccessToken, videoId: userVideoLiveoId, shouldHaveError: true }) await waitUntilLivePublishedOnAllServers(userVideoLiveoId) await waitJobs(servers) @@ -135,7 +132,7 @@ describe('Test live constraints', function () { await updateQuota({ total: -1, daily: 1 }) const userVideoLiveoId = await createLiveWrapper(true) - await runAndTestFfmpegStreamError(servers[0].url, userAccessToken, userVideoLiveoId, true) + await servers[0].liveCommand.runAndTestFfmpegStreamError({ token: userAccessToken, videoId: userVideoLiveoId, shouldHaveError: true }) await waitUntilLivePublishedOnAllServers(userVideoLiveoId) await waitJobs(servers) @@ -152,7 +149,7 @@ describe('Test live constraints', function () { await updateQuota({ total: 10 * 1000 * 1000, daily: -1 }) const userVideoLiveoId = await createLiveWrapper(true) - await runAndTestFfmpegStreamError(servers[0].url, userAccessToken, userVideoLiveoId, false) + await servers[0].liveCommand.runAndTestFfmpegStreamError({ token: userAccessToken, videoId: userVideoLiveoId, shouldHaveError: false }) }) it('Should have max duration limit', async function () { @@ -173,7 +170,7 @@ describe('Test live constraints', function () { }) const userVideoLiveoId = await createLiveWrapper(true) - await runAndTestFfmpegStreamError(servers[0].url, userAccessToken, userVideoLiveoId, true) + await servers[0].liveCommand.runAndTestFfmpegStreamError({ token: userAccessToken, videoId: userVideoLiveoId, shouldHaveError: true }) await waitUntilLivePublishedOnAllServers(userVideoLiveoId) await waitJobs(servers) diff --git a/server/tests/api/live/live-permanent.ts b/server/tests/api/live/live-permanent.ts index b9e37c834..a0f70dfdb 100644 --- a/server/tests/api/live/live-permanent.ts +++ b/server/tests/api/live/live-permanent.ts @@ -6,22 +6,15 @@ import { LiveVideoCreate, VideoDetails, VideoPrivacy, VideoState } from '@shared import { cleanupTests, ConfigCommand, - createLive, doubleFollow, flushAndRunMultipleServers, - getLive, - getPlaylistsCount, getVideo, - sendRTMPStreamInVideo, ServerInfo, setAccessTokensToServers, setDefaultVideoChannel, stopFfmpeg, - updateLive, wait, - waitJobs, - waitUntilLivePublished, - waitUntilLiveWaiting + waitJobs } from '../../../../shared/extra-utils' const expect = chai.expect @@ -39,8 +32,8 @@ describe('Permanent live', function () { permanentLive } - const res = await createLive(servers[0].url, servers[0].accessToken, attributes) - return res.body.video.uuid + const { uuid } = await servers[0].liveCommand.createLive({ fields: attributes }) + return uuid } async function checkVideoState (videoId: string, state: VideoState) { @@ -83,15 +76,15 @@ describe('Permanent live', function () { const videoUUID = await createLiveWrapper(false) { - const res = await getLive(servers[0].url, servers[0].accessToken, videoUUID) - expect(res.body.permanentLive).to.be.false + const live = await servers[0].liveCommand.getLive({ videoId: videoUUID }) + expect(live.permanentLive).to.be.false } - await updateLive(servers[0].url, servers[0].accessToken, videoUUID, { permanentLive: true }) + await servers[0].liveCommand.updateLive({ videoId: videoUUID, fields: { permanentLive: true } }) { - const res = await getLive(servers[0].url, servers[0].accessToken, videoUUID) - expect(res.body.permanentLive).to.be.true + const live = await servers[0].liveCommand.getLive({ videoId: videoUUID }) + expect(live.permanentLive).to.be.true } }) @@ -100,8 +93,8 @@ describe('Permanent live', function () { videoUUID = await createLiveWrapper(true) - const res = await getLive(servers[0].url, servers[0].accessToken, videoUUID) - expect(res.body.permanentLive).to.be.true + const live = await servers[0].liveCommand.getLive({ videoId: videoUUID }) + expect(live.permanentLive).to.be.true await waitJobs(servers) }) @@ -109,16 +102,16 @@ describe('Permanent live', function () { it('Should stream into this permanent live', async function () { this.timeout(120000) - const command = await sendRTMPStreamInVideo(servers[0].url, servers[0].accessToken, videoUUID) + const ffmpegCommand = await servers[0].liveCommand.sendRTMPStreamInVideo({ videoId: videoUUID }) for (const server of servers) { - await waitUntilLivePublished(server.url, server.accessToken, videoUUID) + await server.liveCommand.waitUntilLivePublished({ videoId: videoUUID }) } await checkVideoState(videoUUID, VideoState.PUBLISHED) - await stopFfmpeg(command) - await waitUntilLiveWaiting(servers[0].url, servers[0].accessToken, videoUUID) + await stopFfmpeg(ffmpegCommand) + await servers[0].liveCommand.waitUntilLiveWaiting({ videoId: videoUUID }) await waitJobs(servers) }) @@ -160,19 +153,19 @@ describe('Permanent live', function () { } }) - const command = await sendRTMPStreamInVideo(servers[0].url, servers[0].accessToken, videoUUID) + const ffmpegCommand = await servers[0].liveCommand.sendRTMPStreamInVideo({ videoId: videoUUID }) for (const server of servers) { - await waitUntilLivePublished(server.url, server.accessToken, videoUUID) + await server.liveCommand.waitUntilLivePublished({ videoId: videoUUID }) } await checkVideoState(videoUUID, VideoState.PUBLISHED) - const count = await getPlaylistsCount(servers[0], videoUUID) + const count = await servers[0].liveCommand.getPlaylistsCount({ videoUUID }) // master playlist and 720p playlist expect(count).to.equal(2) - await stopFfmpeg(command) + await stopFfmpeg(ffmpegCommand) }) after(async function () { diff --git a/server/tests/api/live/live-save-replay.ts b/server/tests/api/live/live-save-replay.ts index e74bc3e8d..d3c252ffd 100644 --- a/server/tests/api/live/live-save-replay.ts +++ b/server/tests/api/live/live-save-replay.ts @@ -10,13 +10,11 @@ import { checkLiveCleanup, cleanupTests, ConfigCommand, - createLive, doubleFollow, flushAndRunMultipleServers, getVideo, getVideosList, removeVideo, - sendRTMPStreamInVideo, ServerInfo, setAccessTokensToServers, setDefaultVideoChannel, @@ -24,10 +22,7 @@ import { testFfmpegStreamError, updateVideo, wait, - waitJobs, - waitUntilLiveEnded, - waitUntilLivePublished, - waitUntilLiveSaved + waitJobs } from '../../../../shared/extra-utils' const expect = chai.expect @@ -52,8 +47,8 @@ describe('Save replay setting', function () { saveReplay } - const res = await createLive(servers[0].url, servers[0].accessToken, attributes) - return res.body.video.uuid + const { uuid } = await servers[0].liveCommand.createLive({ fields: attributes }) + return uuid } async function checkVideosExist (videoId: string, existsInList: boolean, getStatus?: number) { @@ -79,13 +74,13 @@ describe('Save replay setting', function () { async function waitUntilLivePublishedOnAllServers (videoId: string) { for (const server of servers) { - await waitUntilLivePublished(server.url, server.accessToken, videoId) + await server.liveCommand.waitUntilLivePublished({ videoId }) } } async function waitUntilLiveSavedOnAllServers (videoId: string) { for (const server of servers) { - await waitUntilLiveSaved(server.url, server.accessToken, videoId) + await server.liveCommand.waitUntilLiveSaved({ videoId }) } } @@ -136,7 +131,7 @@ describe('Save replay setting', function () { it('Should correctly have updated the live and federated it when streaming in the live', async function () { this.timeout(30000) - ffmpegCommand = await sendRTMPStreamInVideo(servers[0].url, servers[0].accessToken, liveVideoUUID) + ffmpegCommand = await servers[0].liveCommand.sendRTMPStreamInVideo({ videoId: liveVideoUUID }) await waitUntilLivePublishedOnAllServers(liveVideoUUID) @@ -152,7 +147,7 @@ describe('Save replay setting', function () { await stopFfmpeg(ffmpegCommand) for (const server of servers) { - await waitUntilLiveEnded(server.url, server.accessToken, liveVideoUUID) + await server.liveCommand.waitUntilLiveEnded({ videoId: liveVideoUUID }) } await waitJobs(servers) @@ -169,7 +164,7 @@ describe('Save replay setting', function () { liveVideoUUID = await createLiveWrapper(false) - ffmpegCommand = await sendRTMPStreamInVideo(servers[0].url, servers[0].accessToken, liveVideoUUID) + ffmpegCommand = await servers[0].liveCommand.sendRTMPStreamInVideo({ videoId: liveVideoUUID }) await waitUntilLivePublishedOnAllServers(liveVideoUUID) @@ -198,7 +193,7 @@ describe('Save replay setting', function () { liveVideoUUID = await createLiveWrapper(false) - ffmpegCommand = await sendRTMPStreamInVideo(servers[0].url, servers[0].accessToken, liveVideoUUID) + ffmpegCommand = await servers[0].liveCommand.sendRTMPStreamInVideo({ videoId: liveVideoUUID }) await waitUntilLivePublishedOnAllServers(liveVideoUUID) @@ -234,7 +229,7 @@ describe('Save replay setting', function () { it('Should correctly have updated the live and federated it when streaming in the live', async function () { this.timeout(20000) - ffmpegCommand = await sendRTMPStreamInVideo(servers[0].url, servers[0].accessToken, liveVideoUUID) + ffmpegCommand = await servers[0].liveCommand.sendRTMPStreamInVideo({ videoId: liveVideoUUID }) await waitUntilLivePublishedOnAllServers(liveVideoUUID) await waitJobs(servers) @@ -278,7 +273,7 @@ describe('Save replay setting', function () { liveVideoUUID = await createLiveWrapper(true) - ffmpegCommand = await sendRTMPStreamInVideo(servers[0].url, servers[0].accessToken, liveVideoUUID) + ffmpegCommand = await servers[0].liveCommand.sendRTMPStreamInVideo({ videoId: liveVideoUUID }) await waitUntilLivePublishedOnAllServers(liveVideoUUID) await waitJobs(servers) @@ -306,7 +301,7 @@ describe('Save replay setting', function () { liveVideoUUID = await createLiveWrapper(true) - ffmpegCommand = await sendRTMPStreamInVideo(servers[0].url, servers[0].accessToken, liveVideoUUID) + ffmpegCommand = await servers[0].liveCommand.sendRTMPStreamInVideo({ videoId: liveVideoUUID }) await waitUntilLivePublishedOnAllServers(liveVideoUUID) await waitJobs(servers) diff --git a/server/tests/api/live/live-socket-messages.ts b/server/tests/api/live/live-socket-messages.ts index 20fec16a9..73a300384 100644 --- a/server/tests/api/live/live-socket-messages.ts +++ b/server/tests/api/live/live-socket-messages.ts @@ -5,11 +5,9 @@ import * as chai from 'chai' import { VideoPrivacy, VideoState } from '@shared/models' import { cleanupTests, - createLive, doubleFollow, flushAndRunMultipleServers, getVideoIdFromUUID, - sendRTMPStreamInVideo, ServerInfo, setAccessTokensToServers, setDefaultVideoChannel, @@ -17,7 +15,6 @@ import { viewVideo, wait, waitJobs, - waitUntilLiveEnded, waitUntilLivePublishedOnAllServers } from '../../../../shared/extra-utils' @@ -60,8 +57,8 @@ describe('Test live', function () { privacy: VideoPrivacy.PUBLIC } - const res = await createLive(servers[0].url, servers[0].accessToken, liveAttributes) - return res.body.video.uuid + const { uuid } = await servers[0].liveCommand.createLive({ fields: liveAttributes }) + return uuid } it('Should correctly send a message when the live starts and ends', async function () { @@ -89,7 +86,7 @@ describe('Test live', function () { remoteSocket.emit('subscribe', { videoId }) } - const command = await sendRTMPStreamInVideo(servers[0].url, servers[0].accessToken, liveVideoUUID) + const ffmpegCommand = await servers[0].liveCommand.sendRTMPStreamInVideo({ videoId: liveVideoUUID }) await waitUntilLivePublishedOnAllServers(servers, liveVideoUUID) await waitJobs(servers) @@ -99,10 +96,10 @@ describe('Test live', function () { expect(stateChanges[stateChanges.length - 1]).to.equal(VideoState.PUBLISHED) } - await stopFfmpeg(command) + await stopFfmpeg(ffmpegCommand) for (const server of servers) { - await waitUntilLiveEnded(server.url, server.accessToken, liveVideoUUID) + await server.liveCommand.waitUntilLiveEnded({ videoId: liveVideoUUID }) } await waitJobs(servers) @@ -137,7 +134,7 @@ describe('Test live', function () { remoteSocket.emit('subscribe', { videoId }) } - const command = await sendRTMPStreamInVideo(servers[0].url, servers[0].accessToken, liveVideoUUID) + const ffmpegCommand = await servers[0].liveCommand.sendRTMPStreamInVideo({ videoId: liveVideoUUID }) await waitUntilLivePublishedOnAllServers(servers, liveVideoUUID) await waitJobs(servers) @@ -155,7 +152,7 @@ describe('Test live', function () { expect(localLastVideoViews).to.equal(2) expect(remoteLastVideoViews).to.equal(2) - await stopFfmpeg(command) + await stopFfmpeg(ffmpegCommand) }) it('Should not receive a notification after unsubscribe', async function () { @@ -172,7 +169,7 @@ describe('Test live', function () { socket.on('state-change', data => stateChanges.push(data.state)) socket.emit('subscribe', { videoId }) - const command = await sendRTMPStreamInVideo(servers[0].url, servers[0].accessToken, liveVideoUUID) + const command = await servers[0].liveCommand.sendRTMPStreamInVideo({ videoId: liveVideoUUID }) await waitUntilLivePublishedOnAllServers(servers, liveVideoUUID) await waitJobs(servers) diff --git a/server/tests/api/live/live-views.ts b/server/tests/api/live/live-views.ts index ca571c962..ae6af7cfd 100644 --- a/server/tests/api/live/live-views.ts +++ b/server/tests/api/live/live-views.ts @@ -6,11 +6,9 @@ import { FfmpegCommand } from 'fluent-ffmpeg' import { VideoDetails, VideoPrivacy } from '@shared/models' import { cleanupTests, - createLive, doubleFollow, flushAndRunMultipleServers, getVideo, - sendRTMPStreamInVideo, ServerInfo, setAccessTokensToServers, setDefaultVideoChannel, @@ -73,10 +71,10 @@ describe('Test live', function () { privacy: VideoPrivacy.PUBLIC } - const res = await createLive(servers[0].url, servers[0].accessToken, liveAttributes) - liveVideoId = res.body.video.uuid + const live = await servers[0].liveCommand.createLive({ fields: liveAttributes }) + liveVideoId = live.uuid - command = await sendRTMPStreamInVideo(servers[0].url, servers[0].accessToken, liveVideoId) + command = await servers[0].liveCommand.sendRTMPStreamInVideo({ videoId: liveVideoId }) await waitUntilLivePublishedOnAllServers(servers, liveVideoId) await waitJobs(servers) }) diff --git a/server/tests/api/live/live.ts b/server/tests/api/live/live.ts index 2c3102994..5b4e479b6 100644 --- a/server/tests/api/live/live.ts +++ b/server/tests/api/live/live.ts @@ -13,41 +13,36 @@ import { checkLiveSegmentHash, checkResolutionsInMasterPlaylist, cleanupTests, - createLive, doubleFollow, flushAndRunMultipleServers, - getLive, getMyVideosWithFilter, getPlaylist, getVideo, getVideosList, getVideosWithFilters, killallServers, + LiveCommand, makeRawRequest, removeVideo, reRunServer, sendRTMPStream, - sendRTMPStreamInVideo, ServerInfo, setAccessTokensToServers, setDefaultVideoChannel, stopFfmpeg, testFfmpegStreamError, testImage, - updateLive, uploadVideoAndGetId, wait, waitJobs, - waitUntilLiveEnded, - waitUntilLivePublished, - waitUntilLivePublishedOnAllServers, - waitUntilLiveSegmentGeneration + waitUntilLivePublishedOnAllServers } from '../../../../shared/extra-utils' const expect = chai.expect describe('Test live', function () { let servers: ServerInfo[] = [] + let commands: LiveCommand[] before(async function () { this.timeout(120000) @@ -72,6 +67,8 @@ describe('Test live', function () { // Server 1 and server 2 follow each other await doubleFollow(servers[0], servers[1]) + + commands = servers.map(s => s.liveCommand) }) describe('Live creation, update and delete', function () { @@ -99,8 +96,8 @@ describe('Test live', function () { thumbnailfile: 'video_short1.webm.jpg' } - const res = await createLive(servers[0].url, servers[0].accessToken, attributes) - liveVideoUUID = res.body.video.uuid + const live = await commands[0].createLive({ fields: attributes }) + liveVideoUUID = live.uuid await waitJobs(servers) @@ -130,8 +127,7 @@ describe('Test live', function () { await testImage(server.url, 'video_short1-preview.webm', video.previewPath) await testImage(server.url, 'video_short1.webm', video.thumbnailPath) - const resLive = await getLive(server.url, server.accessToken, liveVideoUUID) - const live: LiveVideo = resLive.body + const live = await server.liveCommand.getLive({ videoId: liveVideoUUID }) if (server.url === servers[0].url) { expect(live.rtmpUrl).to.equal('rtmp://' + server.hostname + ':' + servers[0].rtmpPort + '/live') @@ -155,8 +151,8 @@ describe('Test live', function () { nsfw: true } - const res = await createLive(servers[0].url, servers[0].accessToken, attributes) - const videoId = res.body.video.uuid + const live = await commands[0].createLive({ fields: attributes }) + const videoId = live.uuid await waitJobs(servers) @@ -182,20 +178,19 @@ describe('Test live', function () { }) it('Should not be able to update a live of another server', async function () { - await updateLive(servers[1].url, servers[1].accessToken, liveVideoUUID, { saveReplay: false }, HttpStatusCode.FORBIDDEN_403) + await commands[1].updateLive({ videoId: liveVideoUUID, fields: { saveReplay: false }, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) it('Should update the live', async function () { this.timeout(10000) - await updateLive(servers[0].url, servers[0].accessToken, liveVideoUUID, { saveReplay: false }) + await commands[0].updateLive({ videoId: liveVideoUUID, fields: { saveReplay: false } }) await waitJobs(servers) }) it('Have the live updated', async function () { for (const server of servers) { - const res = await getLive(server.url, server.accessToken, liveVideoUUID) - const live: LiveVideo = res.body + const live = await server.liveCommand.getLive({ videoId: liveVideoUUID }) if (server.url === servers[0].url) { expect(live.rtmpUrl).to.equal('rtmp://' + server.hostname + ':' + servers[0].rtmpPort + '/live') @@ -219,13 +214,13 @@ describe('Test live', function () { it('Should have the live deleted', async function () { for (const server of servers) { await getVideo(server.url, liveVideoUUID, HttpStatusCode.NOT_FOUND_404) - await getLive(server.url, server.accessToken, liveVideoUUID, HttpStatusCode.NOT_FOUND_404) + await server.liveCommand.getLive({ videoId: liveVideoUUID, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) } }) }) describe('Live filters', function () { - let command: any + let ffmpegCommand: any let liveVideoId: string let vodVideoId: string @@ -235,10 +230,10 @@ describe('Test live', function () { vodVideoId = (await uploadVideoAndGetId({ server: servers[0], videoName: 'vod video' })).uuid const liveOptions = { name: 'live', privacy: VideoPrivacy.PUBLIC, channelId: servers[0].videoChannel.id } - const resLive = await createLive(servers[0].url, servers[0].accessToken, liveOptions) - liveVideoId = resLive.body.video.uuid + const live = await commands[0].createLive({ fields: liveOptions }) + liveVideoId = live.uuid - command = await sendRTMPStreamInVideo(servers[0].url, servers[0].accessToken, liveVideoId) + ffmpegCommand = await servers[0].liveCommand.sendRTMPStreamInVideo({ videoId: liveVideoId }) await waitUntilLivePublishedOnAllServers(servers, liveVideoId) await waitJobs(servers) }) @@ -262,7 +257,7 @@ describe('Test live', function () { it('Should display my lives', async function () { this.timeout(60000) - await stopFfmpeg(command) + await stopFfmpeg(ffmpegCommand) await waitJobs(servers) const res = await getMyVideosWithFilter(servers[0].url, servers[0].accessToken, { isLive: true }) @@ -302,13 +297,12 @@ describe('Test live', function () { saveReplay: false } - const res = await createLive(servers[0].url, servers[0].accessToken, liveAttributes) - const uuid = res.body.video.uuid + const { uuid } = await commands[0].createLive({ fields: liveAttributes }) - const resLive = await getLive(servers[0].url, servers[0].accessToken, uuid) + const live = await commands[0].getLive({ videoId: uuid }) const resVideo = await getVideo(servers[0].url, uuid) - return Object.assign(resVideo.body, resLive.body) as LiveVideo & VideoDetails + return Object.assign(resVideo.body as VideoDetails, live) } it('Should not allow a stream without the appropriate path', async function () { @@ -382,8 +376,8 @@ describe('Test live', function () { saveReplay } - const res = await createLive(servers[0].url, servers[0].accessToken, liveAttributes) - return res.body.video.uuid + const { uuid } = await commands[0].createLive({ fields: liveAttributes }) + return uuid } async function testVideoResolutions (liveVideoId: string, resolutions: number[]) { @@ -409,7 +403,7 @@ describe('Test live', function () { for (let i = 0; i < resolutions.length; i++) { const segmentNum = 3 const segmentName = `${i}-00000${segmentNum}.ts` - await waitUntilLiveSegmentGeneration(servers[0], video.uuid, i, segmentNum) + await commands[0].waitUntilLiveSegmentGeneration({ videoUUID: video.uuid, resolution: i, segment: segmentNum }) const res = await getPlaylist(`${servers[0].url}/static/streaming-playlists/hls/${video.uuid}/${i}.m3u8`) const subPlaylist = res.text @@ -454,13 +448,13 @@ describe('Test live', function () { liveVideoId = await createLiveWrapper(false) - const command = await sendRTMPStreamInVideo(servers[0].url, servers[0].accessToken, liveVideoId) + const ffmpegCommand = await commands[0].sendRTMPStreamInVideo({ videoId: liveVideoId }) await waitUntilLivePublishedOnAllServers(servers, liveVideoId) await waitJobs(servers) await testVideoResolutions(liveVideoId, [ 720 ]) - await stopFfmpeg(command) + await stopFfmpeg(ffmpegCommand) }) it('Should enable transcoding with some resolutions', async function () { @@ -470,13 +464,13 @@ describe('Test live', function () { await updateConf(resolutions) liveVideoId = await createLiveWrapper(false) - const command = await sendRTMPStreamInVideo(servers[0].url, servers[0].accessToken, liveVideoId) + const ffmpegCommand = await commands[0].sendRTMPStreamInVideo({ videoId: liveVideoId }) await waitUntilLivePublishedOnAllServers(servers, liveVideoId) await waitJobs(servers) await testVideoResolutions(liveVideoId, resolutions) - await stopFfmpeg(command) + await stopFfmpeg(ffmpegCommand) }) it('Should enable transcoding with some resolutions and correctly save them', async function () { @@ -487,14 +481,14 @@ describe('Test live', function () { await updateConf(resolutions) liveVideoId = await createLiveWrapper(true) - const command = await sendRTMPStreamInVideo(servers[0].url, servers[0].accessToken, liveVideoId, 'video_short2.webm') + const ffmpegCommand = await commands[0].sendRTMPStreamInVideo({ videoId: liveVideoId, fixtureName: 'video_short2.webm' }) await waitUntilLivePublishedOnAllServers(servers, liveVideoId) await waitJobs(servers) await testVideoResolutions(liveVideoId, resolutions) - await stopFfmpeg(command) - await waitUntilLiveEnded(servers[0].url, servers[0].accessToken, liveVideoId) + await stopFfmpeg(ffmpegCommand) + await commands[0].waitUntilLiveEnded({ videoId: liveVideoId }) await waitJobs(servers) @@ -565,8 +559,8 @@ describe('Test live', function () { saveReplay } - const res = await createLive(servers[0].url, servers[0].accessToken, liveAttributes) - return res.body.video.uuid + const { uuid } = await commands[0].createLive({ fields: liveAttributes }) + return uuid } before(async function () { @@ -576,17 +570,17 @@ describe('Test live', function () { liveVideoReplayId = await createLiveWrapper(true) await Promise.all([ - sendRTMPStreamInVideo(servers[0].url, servers[0].accessToken, liveVideoId), - sendRTMPStreamInVideo(servers[0].url, servers[0].accessToken, liveVideoReplayId) + commands[0].sendRTMPStreamInVideo({ videoId: liveVideoId }), + commands[0].sendRTMPStreamInVideo({ videoId: liveVideoReplayId }) ]) await Promise.all([ - waitUntilLivePublished(servers[0].url, servers[0].accessToken, liveVideoId), - waitUntilLivePublished(servers[0].url, servers[0].accessToken, liveVideoReplayId) + commands[0].waitUntilLivePublished({ videoId: liveVideoId }), + commands[0].waitUntilLivePublished({ videoId: liveVideoReplayId }) ]) - await waitUntilLiveSegmentGeneration(servers[0], liveVideoId, 0, 2) - await waitUntilLiveSegmentGeneration(servers[0], liveVideoReplayId, 0, 2) + await commands[0].waitUntilLiveSegmentGeneration({ videoUUID: liveVideoId, resolution: 0, segment: 2 }) + await commands[0].waitUntilLiveSegmentGeneration({ videoUUID: liveVideoReplayId, resolution: 0, segment: 2 }) await killallServers([ servers[0] ]) await reRunServer(servers[0]) @@ -597,13 +591,13 @@ describe('Test live', function () { it('Should cleanup lives', async function () { this.timeout(60000) - await waitUntilLiveEnded(servers[0].url, servers[0].accessToken, liveVideoId) + await commands[0].waitUntilLiveEnded({ videoId: liveVideoId }) }) it('Should save a live replay', async function () { this.timeout(120000) - await waitUntilLivePublished(servers[0].url, servers[0].accessToken, liveVideoReplayId) + await commands[0].waitUntilLivePublished({ videoId: liveVideoReplayId }) }) }) diff --git a/server/tests/api/search/search-videos.ts b/server/tests/api/search/search-videos.ts index 7dc89c447..af74b26a7 100644 --- a/server/tests/api/search/search-videos.ts +++ b/server/tests/api/search/search-videos.ts @@ -2,23 +2,20 @@ import 'mocha' import * as chai from 'chai' -import { VideoPrivacy } from '@shared/models' import { cleanupTests, - createLive, + createVideoCaption, flushAndRunServer, immutableAssign, SearchCommand, - sendRTMPStreamInVideo, ServerInfo, setAccessTokensToServers, setDefaultVideoChannel, stopFfmpeg, uploadVideo, - wait, - waitUntilLivePublished -} from '../../../../shared/extra-utils' -import { createVideoCaption } from '../../../../shared/extra-utils/videos/video-captions' + wait +} from '@shared/extra-utils' +import { VideoPrivacy } from '@shared/models' const expect = chai.expect @@ -502,12 +499,13 @@ describe('Test videos search', function () { } { - const liveOptions = { name: 'live', privacy: VideoPrivacy.PUBLIC, channelId: server.videoChannel.id } - const resLive = await createLive(server.url, server.accessToken, liveOptions) - const liveVideoId = resLive.body.video.uuid + const liveCommand = server.liveCommand + + const liveAttributes = { name: 'live', privacy: VideoPrivacy.PUBLIC, channelId: server.videoChannel.id } + const live = await liveCommand.createLive({ fields: liveAttributes }) - const ffmpegCommand = await sendRTMPStreamInVideo(server.url, server.accessToken, liveVideoId) - await waitUntilLivePublished(server.url, server.accessToken, liveVideoId) + const ffmpegCommand = await liveCommand.sendRTMPStreamInVideo({ videoId: live.id }) + await liveCommand.waitUntilLivePublished({ videoId: live.id }) const body = await command.advancedVideoSearch({ search: { isLive: true } }) diff --git a/server/tests/api/videos/video-change-ownership.ts b/server/tests/api/videos/video-change-ownership.ts index 89dba14b1..88e4d51a2 100644 --- a/server/tests/api/videos/video-change-ownership.ts +++ b/server/tests/api/videos/video-change-ownership.ts @@ -7,7 +7,6 @@ import { acceptChangeOwnership, changeVideoOwnership, cleanupTests, - createLive, createUser, doubleFollow, flushAndRunMultipleServers, @@ -112,9 +111,9 @@ describe('Test video change ownership - nominal', function () { { const attributes = { name: 'live', channelId: firstUserChannelId, privacy: VideoPrivacy.PUBLIC } - const res = await createLive(servers[0].url, firstUserAccessToken, attributes) + const video = await servers[0].liveCommand.createLive({ token: firstUserAccessToken, fields: attributes }) - liveId = res.body.video.id + liveId = video.id } await doubleFollow(servers[0], servers[1]) diff --git a/server/tests/plugins/action-hooks.ts b/server/tests/plugins/action-hooks.ts index 0de5b523b..39266c62f 100644 --- a/server/tests/plugins/action-hooks.ts +++ b/server/tests/plugins/action-hooks.ts @@ -7,7 +7,6 @@ import { addVideoCommentThread, addVideoInPlaylist, blockUser, - createLive, createUser, createVideoPlaylist, deleteVideoComment, @@ -96,7 +95,7 @@ describe('Test plugin action hooks', function () { channelId: servers[0].videoChannel.id } - await createLive(servers[0].url, servers[0].accessToken, attributes) + await servers[0].liveCommand.createLive({ fields: attributes }) await checkHook('action:api.live-video.created') }) diff --git a/server/tests/plugins/filter-hooks.ts b/server/tests/plugins/filter-hooks.ts index e254046bf..e60bad38d 100644 --- a/server/tests/plugins/filter-hooks.ts +++ b/server/tests/plugins/filter-hooks.ts @@ -7,7 +7,6 @@ import { addVideoCommentReply, addVideoCommentThread, cleanupTests, - createLive, createVideoPlaylist, doubleFollow, flushAndRunMultipleServers, @@ -156,7 +155,7 @@ describe('Test plugin filter hooks', function () { channelId: servers[0].videoChannel.id } - await createLive(servers[0].url, servers[0].accessToken, attributes, HttpStatusCode.FORBIDDEN_403) + await servers[0].liveCommand.createLive({ fields: attributes, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) it('Should run filter:api.video.pre-import-url.accept.result', async function () { diff --git a/server/tests/plugins/plugin-transcoding.ts b/server/tests/plugins/plugin-transcoding.ts index 71c2adc72..65282419e 100644 --- a/server/tests/plugins/plugin-transcoding.ts +++ b/server/tests/plugins/plugin-transcoding.ts @@ -7,18 +7,15 @@ import { getAudioStream, getVideoFileFPS, getVideoStreamFromFile } from '@server import { buildServerDirectory, cleanupTests, - createLive, flushAndRunServer, getVideo, PluginsCommand, - sendRTMPStreamInVideo, ServerInfo, setAccessTokensToServers, setDefaultVideoChannel, testFfmpegStreamError, uploadVideoAndGetId, - waitJobs, - waitUntilLivePublished + waitJobs } from '@shared/extra-utils' import { VideoDetails, VideoPrivacy } from '@shared/models' @@ -29,8 +26,9 @@ async function createLiveWrapper (server: ServerInfo) { privacy: VideoPrivacy.PUBLIC } - const res = await createLive(server.url, server.accessToken, liveAttributes) - return res.body.video.uuid + const { uuid } = await server.liveCommand.createLive({ fields: liveAttributes }) + + return uuid } function updateConf (server: ServerInfo, vodProfile: string, liveProfile: string) { @@ -171,8 +169,8 @@ describe('Test transcoding plugins', function () { const liveVideoId = await createLiveWrapper(server) - await sendRTMPStreamInVideo(server.url, server.accessToken, liveVideoId, 'video_short2.webm') - await waitUntilLivePublished(server.url, server.accessToken, liveVideoId) + await server.liveCommand.sendRTMPStreamInVideo({ videoId: liveVideoId, fixtureName: 'video_short2.webm' }) + await server.liveCommand.waitUntilLivePublished({ videoId: liveVideoId }) await waitJobs([ server ]) await checkLiveFPS(liveVideoId, 'above', 20) @@ -185,8 +183,8 @@ describe('Test transcoding plugins', function () { const liveVideoId = await createLiveWrapper(server) - await sendRTMPStreamInVideo(server.url, server.accessToken, liveVideoId, 'video_short2.webm') - await waitUntilLivePublished(server.url, server.accessToken, liveVideoId) + await server.liveCommand.sendRTMPStreamInVideo({ videoId: liveVideoId, fixtureName: 'video_short2.webm' }) + await server.liveCommand.waitUntilLivePublished({ videoId: liveVideoId }) await waitJobs([ server ]) await checkLiveFPS(liveVideoId, 'below', 12) @@ -199,8 +197,8 @@ describe('Test transcoding plugins', function () { const liveVideoId = await createLiveWrapper(server) - await sendRTMPStreamInVideo(server.url, server.accessToken, liveVideoId, 'video_short2.webm') - await waitUntilLivePublished(server.url, server.accessToken, liveVideoId) + await server.liveCommand.sendRTMPStreamInVideo({ videoId: liveVideoId, fixtureName: 'video_short2.webm' }) + await server.liveCommand.waitUntilLivePublished({ videoId: liveVideoId }) await waitJobs([ server ]) await checkLiveFPS(liveVideoId, 'below', 6) @@ -213,7 +211,7 @@ describe('Test transcoding plugins', function () { const liveVideoId = await createLiveWrapper(server) - const command = await sendRTMPStreamInVideo(server.url, server.accessToken, liveVideoId, 'video_short2.webm') + const command = await server.liveCommand.sendRTMPStreamInVideo({ videoId: liveVideoId, fixtureName: 'video_short2.webm' }) await testFfmpegStreamError(command, true) }) @@ -262,8 +260,8 @@ describe('Test transcoding plugins', function () { const liveVideoId = await createLiveWrapper(server) - await sendRTMPStreamInVideo(server.url, server.accessToken, liveVideoId, 'video_short2.webm') - await waitUntilLivePublished(server.url, server.accessToken, liveVideoId) + await server.liveCommand.sendRTMPStreamInVideo({ videoId: liveVideoId, fixtureName: 'video_short2.webm' }) + await server.liveCommand.waitUntilLivePublished({ videoId: liveVideoId }) await waitJobs([ server ]) const playlistUrl = `${server.url}/static/streaming-playlists/hls/${liveVideoId}/0.m3u8` diff --git a/shared/extra-utils/index.ts b/shared/extra-utils/index.ts index 68900af26..4b3636d06 100644 --- a/shared/extra-utils/index.ts +++ b/shared/extra-utils/index.ts @@ -7,21 +7,9 @@ export * from './miscs' export * from './mock-servers' export * from './moderation' export * from './overviews' +export * from './requests' export * from './search' export * from './server' export * from './socket' export * from './users' - -export * from './requests/check-api-params' -export * from './requests/requests' - -export * from './videos/live' -export * from './videos/services' -export * from './videos/video-blacklist' -export * from './videos/video-captions' -export * from './videos/video-change-ownership' -export * from './videos/video-channels' -export * from './videos/video-comments' -export * from './videos/video-playlists' -export * from './videos/video-streaming-playlists' -export * from './videos/videos' +export * from './videos' diff --git a/shared/extra-utils/requests/index.ts b/shared/extra-utils/requests/index.ts new file mode 100644 index 000000000..501163f92 --- /dev/null +++ b/shared/extra-utils/requests/index.ts @@ -0,0 +1,3 @@ +// Don't include activitypub that import stuff from server +export * from './check-api-params' +export * from './requests' diff --git a/shared/extra-utils/server/servers.ts b/shared/extra-utils/server/servers.ts index 57b37728a..eca0689aa 100644 --- a/shared/extra-utils/server/servers.ts +++ b/shared/extra-utils/server/servers.ts @@ -18,6 +18,7 @@ import { makeGetRequest } from '../requests/requests' import { SearchCommand } from '../search' import { SocketIOCommand } from '../socket' import { AccountsCommand, BlocklistCommand, SubscriptionsCommand } from '../users' +import { LiveCommand } from '../videos' import { ConfigCommand } from './config-command' import { ContactFormCommand } from './contact-form-command' import { DebugCommand } from './debug-command' @@ -99,6 +100,7 @@ interface ServerInfo { accountsCommand?: AccountsCommand blocklistCommand?: BlocklistCommand subscriptionsCommand?: SubscriptionsCommand + liveCommand?: LiveCommand } function parallelTests () { @@ -324,6 +326,7 @@ async function runServer (server: ServerInfo, configOverrideArg?: any, args = [] server.accountsCommand = new AccountsCommand(server) server.blocklistCommand = new BlocklistCommand(server) server.subscriptionsCommand = new SubscriptionsCommand(server) + server.liveCommand = new LiveCommand(server) res(server) }) diff --git a/shared/extra-utils/shared/abstract-command.ts b/shared/extra-utils/shared/abstract-command.ts index dd4598a91..38129d559 100644 --- a/shared/extra-utils/shared/abstract-command.ts +++ b/shared/extra-utils/shared/abstract-command.ts @@ -1,5 +1,5 @@ import { HttpStatusCode } from '@shared/core-utils' -import { makeDeleteRequest, makeGetRequest, makePostBodyRequest, makePutBodyRequest, unwrapBody, unwrapText } from '../requests/requests' +import { makeDeleteRequest, makeGetRequest, makePostBodyRequest, makePutBodyRequest, makeUploadRequest, unwrapBody, unwrapText } from '../requests/requests' import { ServerInfo } from '../server/servers' export interface OverrideCommandOptions { @@ -86,6 +86,36 @@ abstract class AbstractCommand { }) } + protected postUploadRequest (options: CommonCommandOptions & { + fields?: { [ fieldName: string ]: any } + attaches?: any + }) { + const { fields, attaches } = options + + return makeUploadRequest({ + ...this.buildCommonRequestOptions(options), + + method: 'POST', + fields, + attaches + }) + } + + protected putUploadRequest (options: CommonCommandOptions & { + fields?: { [ fieldName: string ]: any } + attaches?: any + }) { + const { fields, attaches } = options + + return makeUploadRequest({ + ...this.buildCommonRequestOptions(options), + + method: 'PUT', + fields, + attaches + }) + } + private buildCommonRequestOptions (options: CommonCommandOptions) { const { token, expectedStatus, defaultExpectedStatus, path } = options diff --git a/shared/extra-utils/users/index.ts b/shared/extra-utils/users/index.ts index 94ad37242..9f760d7fd 100644 --- a/shared/extra-utils/users/index.ts +++ b/shared/extra-utils/users/index.ts @@ -1,7 +1,6 @@ export * from './accounts-command' export * from './accounts' export * from './blocklist-command' - export * from './login' export * from './user-notifications' export * from './subscriptions-command' diff --git a/shared/extra-utils/videos/index.ts b/shared/extra-utils/videos/index.ts new file mode 100644 index 000000000..c9c884285 --- /dev/null +++ b/shared/extra-utils/videos/index.ts @@ -0,0 +1,13 @@ +export * from './live-command' +export * from './live' +export * from './services' +export * from './video-blacklist' +export * from './video-captions' +export * from './video-change-ownership' +export * from './video-channels' +export * from './video-comments' +export * from './video-history' +export * from './video-imports' +export * from './video-playlists' +export * from './video-streaming-playlists' +export * from './videos' diff --git a/shared/extra-utils/videos/live-command.ts b/shared/extra-utils/videos/live-command.ts new file mode 100644 index 000000000..55811b8ba --- /dev/null +++ b/shared/extra-utils/videos/live-command.ts @@ -0,0 +1,156 @@ +/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ + +import { readdir } from 'fs-extra' +import { omit } from 'lodash' +import { join } from 'path' +import { LiveVideo, LiveVideoCreate, LiveVideoUpdate, VideoCreateResult, VideoDetails, VideoState } from '@shared/models' +import { HttpStatusCode } from '../../core-utils/miscs/http-error-codes' +import { buildServerDirectory, wait } from '../miscs/miscs' +import { unwrapBody } from '../requests' +import { waitUntilLog } from '../server/servers' +import { AbstractCommand, OverrideCommandOptions } from '../shared' +import { sendRTMPStream, testFfmpegStreamError } from './live' +import { getVideoWithToken } from './videos' + +export class LiveCommand extends AbstractCommand { + + getLive (options: OverrideCommandOptions & { + videoId: number | string + }) { + const path = '/api/v1/videos/live' + + return this.getRequestBody({ + ...options, + + path: path + '/' + options.videoId, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } + + updateLive (options: OverrideCommandOptions & { + videoId: number | string + fields: LiveVideoUpdate + }) { + const { videoId, fields } = options + const path = '/api/v1/videos/live' + + return this.putBodyRequest({ + ...options, + + path: path + '/' + videoId, + fields, + defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 + }) + } + + async createLive (options: OverrideCommandOptions & { + fields: LiveVideoCreate + }) { + const { fields } = options + const path = '/api/v1/videos/live' + + const attaches: any = {} + if (fields.thumbnailfile) attaches.thumbnailfile = fields.thumbnailfile + if (fields.previewfile) attaches.previewfile = fields.previewfile + + const body = await unwrapBody<{ video: VideoCreateResult }>(this.postUploadRequest({ + ...options, + + path, + attaches, + fields: omit(fields, 'thumbnailfile', 'previewfile'), + defaultExpectedStatus: HttpStatusCode.OK_200 + })) + + return body.video + } + + async sendRTMPStreamInVideo (options: OverrideCommandOptions & { + videoId: number | string + fixtureName?: string + }) { + const { videoId, fixtureName } = options + const videoLive = await this.getLive({ videoId }) + + return sendRTMPStream(videoLive.rtmpUrl, videoLive.streamKey, fixtureName) + } + + async runAndTestFfmpegStreamError (options: OverrideCommandOptions & { + videoId: number | string + shouldHaveError: boolean + }) { + const command = await this.sendRTMPStreamInVideo(options) + + return testFfmpegStreamError(command, options.shouldHaveError) + } + + waitUntilLivePublished (options: OverrideCommandOptions & { + videoId: number | string + }) { + const { videoId } = options + return this.waitUntilLiveState({ videoId, state: VideoState.PUBLISHED }) + } + + waitUntilLiveWaiting (options: OverrideCommandOptions & { + videoId: number | string + }) { + const { videoId } = options + return this.waitUntilLiveState({ videoId, state: VideoState.WAITING_FOR_LIVE }) + } + + waitUntilLiveEnded (options: OverrideCommandOptions & { + videoId: number | string + }) { + const { videoId } = options + return this.waitUntilLiveState({ videoId, state: VideoState.LIVE_ENDED }) + } + + waitUntilLiveSegmentGeneration (options: OverrideCommandOptions & { + videoUUID: string + resolution: number + segment: number + }) { + const { resolution, segment, videoUUID } = options + const segmentName = `${resolution}-00000${segment}.ts` + + return waitUntilLog(this.server, `${videoUUID}/${segmentName}`, 2, false) + } + + async waitUntilLiveSaved (options: OverrideCommandOptions & { + videoId: number | string + }) { + let video: VideoDetails + + do { + const res = await getVideoWithToken(this.server.url, options.token ?? this.server.accessToken, options.videoId) + video = res.body + + await wait(500) + } while (video.isLive === true && video.state.id !== VideoState.PUBLISHED) + } + + async getPlaylistsCount (options: OverrideCommandOptions & { + videoUUID: string + }) { + const basePath = buildServerDirectory(this.server, 'streaming-playlists') + const hlsPath = join(basePath, 'hls', options.videoUUID) + + const files = await readdir(hlsPath) + + return files.filter(f => f.endsWith('.m3u8')).length + } + + private async waitUntilLiveState (options: OverrideCommandOptions & { + videoId: number | string + state: VideoState + }) { + let video: VideoDetails + + do { + const res = await getVideoWithToken(this.server.url, options.token ?? this.server.accessToken, options.videoId) + video = res.body + + await wait(500) + } while (video.state.id !== options.state) + } +} diff --git a/shared/extra-utils/videos/live.ts b/shared/extra-utils/videos/live.ts index c0384769b..285a39c7e 100644 --- a/shared/extra-utils/videos/live.ts +++ b/shared/extra-utils/videos/live.ts @@ -3,69 +3,9 @@ import { expect } from 'chai' import * as ffmpeg from 'fluent-ffmpeg' import { pathExists, readdir } from 'fs-extra' -import { omit } from 'lodash' import { join } from 'path' -import { LiveVideo, LiveVideoCreate, LiveVideoUpdate, VideoDetails, VideoState } from '@shared/models' -import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' import { buildAbsoluteFixturePath, buildServerDirectory, wait } from '../miscs/miscs' -import { makeGetRequest, makePutBodyRequest, makeUploadRequest } from '../requests/requests' -import { ServerInfo, waitUntilLog } from '../server/servers' -import { getVideoWithToken } from './videos' - -function getLive (url: string, token: string, videoId: number | string, statusCodeExpected = HttpStatusCode.OK_200) { - const path = '/api/v1/videos/live' - - return makeGetRequest({ - url, - token, - path: path + '/' + videoId, - statusCodeExpected - }) -} - -function updateLive ( - url: string, - token: string, - videoId: number | string, - fields: LiveVideoUpdate, - statusCodeExpected = HttpStatusCode.NO_CONTENT_204 -) { - const path = '/api/v1/videos/live' - - return makePutBodyRequest({ - url, - token, - path: path + '/' + videoId, - fields, - statusCodeExpected - }) -} - -function createLive (url: string, token: string, fields: LiveVideoCreate, statusCodeExpected = HttpStatusCode.OK_200) { - const path = '/api/v1/videos/live' - - const attaches: any = {} - if (fields.thumbnailfile) attaches.thumbnailfile = fields.thumbnailfile - if (fields.previewfile) attaches.previewfile = fields.previewfile - - const updatedFields = omit(fields, 'thumbnailfile', 'previewfile') - - return makeUploadRequest({ - url, - path, - token, - attaches, - fields: updatedFields, - statusCodeExpected - }) -} - -async function sendRTMPStreamInVideo (url: string, token: string, videoId: number | string, fixtureName?: string) { - const res = await getLive(url, token, videoId) - const videoLive = res.body as LiveVideo - - return sendRTMPStream(videoLive.rtmpUrl, videoLive.streamKey, fixtureName) -} +import { ServerInfo } from '../server/servers' function sendRTMPStream (rtmpBaseUrl: string, streamKey: string, fixtureName = 'video_short.mp4') { const fixture = buildAbsoluteFixturePath(fixtureName) @@ -109,12 +49,6 @@ function waitFfmpegUntilError (command: ffmpeg.FfmpegCommand, successAfterMS = 1 }) } -async function runAndTestFfmpegStreamError (url: string, token: string, videoId: number | string, shouldHaveError: boolean) { - const command = await sendRTMPStreamInVideo(url, token, videoId) - - return testFfmpegStreamError(command, shouldHaveError) -} - async function testFfmpegStreamError (command: ffmpeg.FfmpegCommand, shouldHaveError: boolean) { let error: Error @@ -136,48 +70,9 @@ async function stopFfmpeg (command: ffmpeg.FfmpegCommand) { await wait(500) } -function waitUntilLivePublished (url: string, token: string, videoId: number | string) { - return waitUntilLiveState(url, token, videoId, VideoState.PUBLISHED) -} - -function waitUntilLiveWaiting (url: string, token: string, videoId: number | string) { - return waitUntilLiveState(url, token, videoId, VideoState.WAITING_FOR_LIVE) -} - -function waitUntilLiveEnded (url: string, token: string, videoId: number | string) { - return waitUntilLiveState(url, token, videoId, VideoState.LIVE_ENDED) -} - -function waitUntilLiveSegmentGeneration (server: ServerInfo, videoUUID: string, resolutionNum: number, segmentNum: number) { - const segmentName = `${resolutionNum}-00000${segmentNum}.ts` - return waitUntilLog(server, `${videoUUID}/${segmentName}`, 2, false) -} - -async function waitUntilLiveState (url: string, token: string, videoId: number | string, state: VideoState) { - let video: VideoDetails - - do { - const res = await getVideoWithToken(url, token, videoId) - video = res.body - - await wait(500) - } while (video.state.id !== state) -} - -async function waitUntilLiveSaved (url: string, token: string, videoId: number | string) { - let video: VideoDetails - - do { - const res = await getVideoWithToken(url, token, videoId) - video = res.body - - await wait(500) - } while (video.isLive === true && video.state.id !== VideoState.PUBLISHED) -} - async function waitUntilLivePublishedOnAllServers (servers: ServerInfo[], videoId: string) { for (const server of servers) { - await waitUntilLivePublished(server.url, server.accessToken, videoId) + await server.liveCommand.waitUntilLivePublished({ videoId }) } } @@ -206,33 +101,11 @@ async function checkLiveCleanup (server: ServerInfo, videoUUID: string, resoluti expect(files).to.contain('segments-sha256.json') } -async function getPlaylistsCount (server: ServerInfo, videoUUID: string) { - const basePath = buildServerDirectory(server, 'streaming-playlists') - const hlsPath = join(basePath, 'hls', videoUUID) - - const files = await readdir(hlsPath) - - return files.filter(f => f.endsWith('.m3u8')).length -} - -// --------------------------------------------------------------------------- - export { - getLive, - getPlaylistsCount, - waitUntilLiveSaved, - waitUntilLivePublished, - updateLive, - createLive, - runAndTestFfmpegStreamError, - checkLiveCleanup, - waitUntilLiveSegmentGeneration, - stopFfmpeg, - waitUntilLiveWaiting, - sendRTMPStreamInVideo, - waitUntilLiveEnded, + sendRTMPStream, waitFfmpegUntilError, + testFfmpegStreamError, + stopFfmpeg, waitUntilLivePublishedOnAllServers, - sendRTMPStream, - testFfmpegStreamError + checkLiveCleanup } -- cgit v1.2.3 From d897210c2db1ca2acc1e7b28a13127647ab2222c Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Thu, 8 Jul 2021 10:23:21 +0200 Subject: Introduce services command --- server/tests/api/server/services.ts | 7 +++---- shared/extra-utils/server/servers.ts | 4 +++- shared/extra-utils/videos/index.ts | 2 +- shared/extra-utils/videos/services-command.ts | 28 +++++++++++++++++++++++++++ shared/extra-utils/videos/services.ts | 24 ----------------------- 5 files changed, 35 insertions(+), 30 deletions(-) create mode 100644 shared/extra-utils/videos/services-command.ts delete mode 100644 shared/extra-utils/videos/services.ts diff --git a/server/tests/api/server/services.ts b/server/tests/api/server/services.ts index ea64e4040..0adf6b667 100644 --- a/server/tests/api/server/services.ts +++ b/server/tests/api/server/services.ts @@ -6,7 +6,6 @@ import { Video, VideoPlaylistPrivacy } from '@shared/models' import { addVideoInPlaylist, createVideoPlaylist, - getOEmbed, getVideosList, ServerInfo, setAccessTokensToServers, @@ -70,7 +69,7 @@ describe('Test services', function () { for (const basePath of [ '/videos/watch/', '/w/' ]) { const oembedUrl = 'http://localhost:' + server.port + basePath + video.uuid - const res = await getOEmbed(server.url, oembedUrl) + const res = await server.servicesCommand.getOEmbed({ oembedUrl }) const expectedHtml = '' @@ -91,7 +90,7 @@ describe('Test services', function () { for (const basePath of [ '/videos/watch/playlist/', '/w/p/' ]) { const oembedUrl = 'http://localhost:' + server.port + basePath + playlistUUID - const res = await getOEmbed(server.url, oembedUrl) + const res = await server.servicesCommand.getOEmbed({ oembedUrl }) const expectedHtml = '' @@ -114,7 +113,7 @@ describe('Test services', function () { const maxHeight = 50 const maxWidth = 50 - const res = await getOEmbed(server.url, oembedUrl, format, maxHeight, maxWidth) + const res = await server.servicesCommand.getOEmbed({ oembedUrl, format, maxHeight, maxWidth }) const expectedHtml = '' diff --git a/shared/extra-utils/server/servers.ts b/shared/extra-utils/server/servers.ts index eca0689aa..cb2a8814b 100644 --- a/shared/extra-utils/server/servers.ts +++ b/shared/extra-utils/server/servers.ts @@ -18,7 +18,7 @@ import { makeGetRequest } from '../requests/requests' import { SearchCommand } from '../search' import { SocketIOCommand } from '../socket' import { AccountsCommand, BlocklistCommand, SubscriptionsCommand } from '../users' -import { LiveCommand } from '../videos' +import { LiveCommand, ServicesCommand } from '../videos' import { ConfigCommand } from './config-command' import { ContactFormCommand } from './contact-form-command' import { DebugCommand } from './debug-command' @@ -101,6 +101,7 @@ interface ServerInfo { blocklistCommand?: BlocklistCommand subscriptionsCommand?: SubscriptionsCommand liveCommand?: LiveCommand + servicesCommand?: ServicesCommand } function parallelTests () { @@ -327,6 +328,7 @@ async function runServer (server: ServerInfo, configOverrideArg?: any, args = [] server.blocklistCommand = new BlocklistCommand(server) server.subscriptionsCommand = new SubscriptionsCommand(server) server.liveCommand = new LiveCommand(server) + server.servicesCommand = new ServicesCommand(server) res(server) }) diff --git a/shared/extra-utils/videos/index.ts b/shared/extra-utils/videos/index.ts index c9c884285..fe5dc6655 100644 --- a/shared/extra-utils/videos/index.ts +++ b/shared/extra-utils/videos/index.ts @@ -1,6 +1,6 @@ export * from './live-command' export * from './live' -export * from './services' +export * from './services-command' export * from './video-blacklist' export * from './video-captions' export * from './video-change-ownership' diff --git a/shared/extra-utils/videos/services-command.ts b/shared/extra-utils/videos/services-command.ts new file mode 100644 index 000000000..3b618ef66 --- /dev/null +++ b/shared/extra-utils/videos/services-command.ts @@ -0,0 +1,28 @@ +import { HttpStatusCode } from '../../core-utils/miscs/http-error-codes' +import { AbstractCommand, OverrideCommandOptions } from '../shared' + +export class ServicesCommand extends AbstractCommand { + + getOEmbed (options: OverrideCommandOptions & { + oembedUrl: string + format?: string + maxHeight?: number + maxWidth?: number + }) { + const path = '/services/oembed' + const query = { + url: options.oembedUrl, + format: options.format, + maxheight: options.maxHeight, + maxwidth: options.maxWidth + } + + return this.getRequest({ + ...options, + + path, + query, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } +} diff --git a/shared/extra-utils/videos/services.ts b/shared/extra-utils/videos/services.ts deleted file mode 100644 index e13a788bd..000000000 --- a/shared/extra-utils/videos/services.ts +++ /dev/null @@ -1,24 +0,0 @@ -import * as request from 'supertest' -import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' - -function getOEmbed (url: string, oembedUrl: string, format?: string, maxHeight?: number, maxWidth?: number) { - const path = '/services/oembed' - const query = { - url: oembedUrl, - format, - maxheight: maxHeight, - maxwidth: maxWidth - } - - return request(url) - .get(path) - .query(query) - .set('Accept', 'application/json') - .expect(HttpStatusCode.OK_200) -} - -// --------------------------------------------------------------------------- - -export { - getOEmbed -} -- cgit v1.2.3 From 04aed76711909507e74905bde3a7fa024d3585c9 Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Thu, 8 Jul 2021 10:25:50 +0200 Subject: Shorter live methods --- server/tests/api/check-params/live.ts | 52 +++++++++++------------ server/tests/api/live/live-constraints.ts | 14 +++--- server/tests/api/live/live-permanent.ts | 18 ++++---- server/tests/api/live/live-save-replay.ts | 8 ++-- server/tests/api/live/live-socket-messages.ts | 4 +- server/tests/api/live/live-views.ts | 2 +- server/tests/api/live/live.ts | 42 +++++++++--------- server/tests/api/search/search-videos.ts | 4 +- server/tests/api/videos/video-change-ownership.ts | 2 +- server/tests/plugins/action-hooks.ts | 2 +- server/tests/plugins/filter-hooks.ts | 2 +- server/tests/plugins/plugin-transcoding.ts | 10 ++--- shared/extra-utils/videos/live-command.ts | 30 ++++++------- shared/extra-utils/videos/live.ts | 2 +- 14 files changed, 96 insertions(+), 96 deletions(-) diff --git a/server/tests/api/check-params/live.ts b/server/tests/api/check-params/live.ts index 56116848f..d851d258d 100644 --- a/server/tests/api/check-params/live.ts +++ b/server/tests/api/check-params/live.ts @@ -337,72 +337,72 @@ describe('Test video lives API validator', function () { describe('When getting live information', function () { it('Should fail without access token', async function () { - await command.getLive({ token: '', videoId: video.id, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) + await command.get({ token: '', videoId: video.id, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should fail with a bad access token', async function () { - await command.getLive({ token: 'toto', videoId: video.id, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) + await command.get({ token: 'toto', videoId: video.id, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should fail with access token of another user', async function () { - await command.getLive({ token: userAccessToken, videoId: video.id, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) + await command.get({ token: userAccessToken, videoId: video.id, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) it('Should fail with a bad video id', async function () { - await command.getLive({ videoId: 'toto', expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) + await command.get({ videoId: 'toto', expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) it('Should fail with an unknown video id', async function () { - await command.getLive({ videoId: 454555, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) + await command.get({ videoId: 454555, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) it('Should fail with a non live video', async function () { - await command.getLive({ videoId: videoIdNotLive, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) + await command.get({ videoId: videoIdNotLive, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) it('Should succeed with the correct params', async function () { - await command.getLive({ videoId: video.id }) - await command.getLive({ videoId: video.uuid }) - await command.getLive({ videoId: video.shortUUID }) + await command.get({ videoId: video.id }) + await command.get({ videoId: video.uuid }) + await command.get({ videoId: video.shortUUID }) }) }) describe('When updating live information', async function () { it('Should fail without access token', async function () { - await command.updateLive({ token: '', videoId: video.id, fields: {}, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) + await command.update({ token: '', videoId: video.id, fields: {}, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should fail with a bad access token', async function () { - await command.updateLive({ token: 'toto', videoId: video.id, fields: {}, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) + await command.update({ token: 'toto', videoId: video.id, fields: {}, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should fail with access token of another user', async function () { - await command.updateLive({ token: userAccessToken, videoId: video.id, fields: {}, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) + await command.update({ token: userAccessToken, videoId: video.id, fields: {}, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) it('Should fail with a bad video id', async function () { - await command.updateLive({ videoId: 'toto', fields: {}, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) + await command.update({ videoId: 'toto', fields: {}, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) it('Should fail with an unknown video id', async function () { - await command.updateLive({ videoId: 454555, fields: {}, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) + await command.update({ videoId: 454555, fields: {}, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) it('Should fail with a non live video', async function () { - await command.updateLive({ videoId: videoIdNotLive, fields: {}, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) + await command.update({ videoId: videoIdNotLive, fields: {}, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) it('Should fail with save replay and permanent live set to true', async function () { const fields = { saveReplay: true, permanentLive: true } - await command.updateLive({ videoId: video.id, fields, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) + await command.update({ videoId: video.id, fields, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) it('Should succeed with the correct params', async function () { - await command.updateLive({ videoId: video.id, fields: { saveReplay: false } }) - await command.updateLive({ videoId: video.uuid, fields: { saveReplay: false } }) - await command.updateLive({ videoId: video.shortUUID, fields: { saveReplay: false } }) + await command.update({ videoId: video.id, fields: { saveReplay: false } }) + await command.update({ videoId: video.uuid, fields: { saveReplay: false } }) + await command.update({ videoId: video.shortUUID, fields: { saveReplay: false } }) }) it('Should fail to update replay status if replay is not allowed on the instance', async function () { @@ -415,18 +415,18 @@ describe('Test video lives API validator', function () { } }) - await command.updateLive({ videoId: video.id, fields: { saveReplay: true }, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) + await command.update({ videoId: video.id, fields: { saveReplay: true }, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) it('Should fail to update a live if it has already started', async function () { this.timeout(40000) - const live = await command.getLive({ videoId: video.id }) + const live = await command.get({ videoId: video.id }) const ffmpegCommand = sendRTMPStream(live.rtmpUrl, live.streamKey) - await command.waitUntilLivePublished({ videoId: video.id }) - await command.updateLive({ videoId: video.id, fields: {}, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) + await command.waitUntilPublished({ videoId: video.id }) + await command.update({ videoId: video.id, fields: {}, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) await stopFfmpeg(ffmpegCommand) }) @@ -434,13 +434,13 @@ describe('Test video lives API validator', function () { it('Should fail to stream twice in the save live', async function () { this.timeout(40000) - const live = await command.getLive({ videoId: video.id }) + const live = await command.get({ videoId: video.id }) const ffmpegCommand = sendRTMPStream(live.rtmpUrl, live.streamKey) - await command.waitUntilLivePublished({ videoId: video.id }) + await command.waitUntilPublished({ videoId: video.id }) - await command.runAndTestFfmpegStreamError({ videoId: video.id, shouldHaveError: true }) + await command.runAndTestStreamError({ videoId: video.id, shouldHaveError: true }) await stopFfmpeg(ffmpegCommand) }) diff --git a/server/tests/api/live/live-constraints.ts b/server/tests/api/live/live-constraints.ts index 5c4817b40..46153f7b1 100644 --- a/server/tests/api/live/live-constraints.ts +++ b/server/tests/api/live/live-constraints.ts @@ -35,7 +35,7 @@ describe('Test live constraints', function () { saveReplay } - const { uuid } = await servers[0].liveCommand.createLive({ token: userAccessToken, fields: liveAttributes }) + const { uuid } = await servers[0].liveCommand.create({ token: userAccessToken, fields: liveAttributes }) return uuid } @@ -53,7 +53,7 @@ describe('Test live constraints', function () { async function waitUntilLivePublishedOnAllServers (videoId: string) { for (const server of servers) { - await server.liveCommand.waitUntilLivePublished({ videoId }) + await server.liveCommand.waitUntilPublished({ videoId }) } } @@ -105,7 +105,7 @@ describe('Test live constraints', function () { this.timeout(60000) const userVideoLiveoId = await createLiveWrapper(false) - await servers[0].liveCommand.runAndTestFfmpegStreamError({ token: userAccessToken, videoId: userVideoLiveoId, shouldHaveError: false }) + await servers[0].liveCommand.runAndTestStreamError({ token: userAccessToken, videoId: userVideoLiveoId, shouldHaveError: false }) }) it('Should have size limit depending on user global quota if save replay is enabled', async function () { @@ -115,7 +115,7 @@ describe('Test live constraints', function () { await wait(5000) const userVideoLiveoId = await createLiveWrapper(true) - await servers[0].liveCommand.runAndTestFfmpegStreamError({ token: userAccessToken, videoId: userVideoLiveoId, shouldHaveError: true }) + await servers[0].liveCommand.runAndTestStreamError({ token: userAccessToken, videoId: userVideoLiveoId, shouldHaveError: true }) await waitUntilLivePublishedOnAllServers(userVideoLiveoId) await waitJobs(servers) @@ -132,7 +132,7 @@ describe('Test live constraints', function () { await updateQuota({ total: -1, daily: 1 }) const userVideoLiveoId = await createLiveWrapper(true) - await servers[0].liveCommand.runAndTestFfmpegStreamError({ token: userAccessToken, videoId: userVideoLiveoId, shouldHaveError: true }) + await servers[0].liveCommand.runAndTestStreamError({ token: userAccessToken, videoId: userVideoLiveoId, shouldHaveError: true }) await waitUntilLivePublishedOnAllServers(userVideoLiveoId) await waitJobs(servers) @@ -149,7 +149,7 @@ describe('Test live constraints', function () { await updateQuota({ total: 10 * 1000 * 1000, daily: -1 }) const userVideoLiveoId = await createLiveWrapper(true) - await servers[0].liveCommand.runAndTestFfmpegStreamError({ token: userAccessToken, videoId: userVideoLiveoId, shouldHaveError: false }) + await servers[0].liveCommand.runAndTestStreamError({ token: userAccessToken, videoId: userVideoLiveoId, shouldHaveError: false }) }) it('Should have max duration limit', async function () { @@ -170,7 +170,7 @@ describe('Test live constraints', function () { }) const userVideoLiveoId = await createLiveWrapper(true) - await servers[0].liveCommand.runAndTestFfmpegStreamError({ token: userAccessToken, videoId: userVideoLiveoId, shouldHaveError: true }) + await servers[0].liveCommand.runAndTestStreamError({ token: userAccessToken, videoId: userVideoLiveoId, shouldHaveError: true }) await waitUntilLivePublishedOnAllServers(userVideoLiveoId) await waitJobs(servers) diff --git a/server/tests/api/live/live-permanent.ts b/server/tests/api/live/live-permanent.ts index a0f70dfdb..6f4915a6b 100644 --- a/server/tests/api/live/live-permanent.ts +++ b/server/tests/api/live/live-permanent.ts @@ -32,7 +32,7 @@ describe('Permanent live', function () { permanentLive } - const { uuid } = await servers[0].liveCommand.createLive({ fields: attributes }) + const { uuid } = await servers[0].liveCommand.create({ fields: attributes }) return uuid } @@ -76,14 +76,14 @@ describe('Permanent live', function () { const videoUUID = await createLiveWrapper(false) { - const live = await servers[0].liveCommand.getLive({ videoId: videoUUID }) + const live = await servers[0].liveCommand.get({ videoId: videoUUID }) expect(live.permanentLive).to.be.false } - await servers[0].liveCommand.updateLive({ videoId: videoUUID, fields: { permanentLive: true } }) + await servers[0].liveCommand.update({ videoId: videoUUID, fields: { permanentLive: true } }) { - const live = await servers[0].liveCommand.getLive({ videoId: videoUUID }) + const live = await servers[0].liveCommand.get({ videoId: videoUUID }) expect(live.permanentLive).to.be.true } }) @@ -93,7 +93,7 @@ describe('Permanent live', function () { videoUUID = await createLiveWrapper(true) - const live = await servers[0].liveCommand.getLive({ videoId: videoUUID }) + const live = await servers[0].liveCommand.get({ videoId: videoUUID }) expect(live.permanentLive).to.be.true await waitJobs(servers) @@ -105,13 +105,13 @@ describe('Permanent live', function () { const ffmpegCommand = await servers[0].liveCommand.sendRTMPStreamInVideo({ videoId: videoUUID }) for (const server of servers) { - await server.liveCommand.waitUntilLivePublished({ videoId: videoUUID }) + await server.liveCommand.waitUntilPublished({ videoId: videoUUID }) } await checkVideoState(videoUUID, VideoState.PUBLISHED) await stopFfmpeg(ffmpegCommand) - await servers[0].liveCommand.waitUntilLiveWaiting({ videoId: videoUUID }) + await servers[0].liveCommand.waitUntilWaiting({ videoId: videoUUID }) await waitJobs(servers) }) @@ -156,12 +156,12 @@ describe('Permanent live', function () { const ffmpegCommand = await servers[0].liveCommand.sendRTMPStreamInVideo({ videoId: videoUUID }) for (const server of servers) { - await server.liveCommand.waitUntilLivePublished({ videoId: videoUUID }) + await server.liveCommand.waitUntilPublished({ videoId: videoUUID }) } await checkVideoState(videoUUID, VideoState.PUBLISHED) - const count = await servers[0].liveCommand.getPlaylistsCount({ videoUUID }) + const count = await servers[0].liveCommand.countPlaylists({ videoUUID }) // master playlist and 720p playlist expect(count).to.equal(2) diff --git a/server/tests/api/live/live-save-replay.ts b/server/tests/api/live/live-save-replay.ts index d3c252ffd..9acd5601d 100644 --- a/server/tests/api/live/live-save-replay.ts +++ b/server/tests/api/live/live-save-replay.ts @@ -47,7 +47,7 @@ describe('Save replay setting', function () { saveReplay } - const { uuid } = await servers[0].liveCommand.createLive({ fields: attributes }) + const { uuid } = await servers[0].liveCommand.create({ fields: attributes }) return uuid } @@ -74,13 +74,13 @@ describe('Save replay setting', function () { async function waitUntilLivePublishedOnAllServers (videoId: string) { for (const server of servers) { - await server.liveCommand.waitUntilLivePublished({ videoId }) + await server.liveCommand.waitUntilPublished({ videoId }) } } async function waitUntilLiveSavedOnAllServers (videoId: string) { for (const server of servers) { - await server.liveCommand.waitUntilLiveSaved({ videoId }) + await server.liveCommand.waitUntilSaved({ videoId }) } } @@ -147,7 +147,7 @@ describe('Save replay setting', function () { await stopFfmpeg(ffmpegCommand) for (const server of servers) { - await server.liveCommand.waitUntilLiveEnded({ videoId: liveVideoUUID }) + await server.liveCommand.waitUntilEnded({ videoId: liveVideoUUID }) } await waitJobs(servers) diff --git a/server/tests/api/live/live-socket-messages.ts b/server/tests/api/live/live-socket-messages.ts index 73a300384..4a6677c0a 100644 --- a/server/tests/api/live/live-socket-messages.ts +++ b/server/tests/api/live/live-socket-messages.ts @@ -57,7 +57,7 @@ describe('Test live', function () { privacy: VideoPrivacy.PUBLIC } - const { uuid } = await servers[0].liveCommand.createLive({ fields: liveAttributes }) + const { uuid } = await servers[0].liveCommand.create({ fields: liveAttributes }) return uuid } @@ -99,7 +99,7 @@ describe('Test live', function () { await stopFfmpeg(ffmpegCommand) for (const server of servers) { - await server.liveCommand.waitUntilLiveEnded({ videoId: liveVideoUUID }) + await server.liveCommand.waitUntilEnded({ videoId: liveVideoUUID }) } await waitJobs(servers) diff --git a/server/tests/api/live/live-views.ts b/server/tests/api/live/live-views.ts index ae6af7cfd..75f95b167 100644 --- a/server/tests/api/live/live-views.ts +++ b/server/tests/api/live/live-views.ts @@ -71,7 +71,7 @@ describe('Test live', function () { privacy: VideoPrivacy.PUBLIC } - const live = await servers[0].liveCommand.createLive({ fields: liveAttributes }) + const live = await servers[0].liveCommand.create({ fields: liveAttributes }) liveVideoId = live.uuid command = await servers[0].liveCommand.sendRTMPStreamInVideo({ videoId: liveVideoId }) diff --git a/server/tests/api/live/live.ts b/server/tests/api/live/live.ts index 5b4e479b6..5d70d8513 100644 --- a/server/tests/api/live/live.ts +++ b/server/tests/api/live/live.ts @@ -96,7 +96,7 @@ describe('Test live', function () { thumbnailfile: 'video_short1.webm.jpg' } - const live = await commands[0].createLive({ fields: attributes }) + const live = await commands[0].create({ fields: attributes }) liveVideoUUID = live.uuid await waitJobs(servers) @@ -127,7 +127,7 @@ describe('Test live', function () { await testImage(server.url, 'video_short1-preview.webm', video.previewPath) await testImage(server.url, 'video_short1.webm', video.thumbnailPath) - const live = await server.liveCommand.getLive({ videoId: liveVideoUUID }) + const live = await server.liveCommand.get({ videoId: liveVideoUUID }) if (server.url === servers[0].url) { expect(live.rtmpUrl).to.equal('rtmp://' + server.hostname + ':' + servers[0].rtmpPort + '/live') @@ -151,7 +151,7 @@ describe('Test live', function () { nsfw: true } - const live = await commands[0].createLive({ fields: attributes }) + const live = await commands[0].create({ fields: attributes }) const videoId = live.uuid await waitJobs(servers) @@ -178,19 +178,19 @@ describe('Test live', function () { }) it('Should not be able to update a live of another server', async function () { - await commands[1].updateLive({ videoId: liveVideoUUID, fields: { saveReplay: false }, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) + await commands[1].update({ videoId: liveVideoUUID, fields: { saveReplay: false }, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) it('Should update the live', async function () { this.timeout(10000) - await commands[0].updateLive({ videoId: liveVideoUUID, fields: { saveReplay: false } }) + await commands[0].update({ videoId: liveVideoUUID, fields: { saveReplay: false } }) await waitJobs(servers) }) it('Have the live updated', async function () { for (const server of servers) { - const live = await server.liveCommand.getLive({ videoId: liveVideoUUID }) + const live = await server.liveCommand.get({ videoId: liveVideoUUID }) if (server.url === servers[0].url) { expect(live.rtmpUrl).to.equal('rtmp://' + server.hostname + ':' + servers[0].rtmpPort + '/live') @@ -214,7 +214,7 @@ describe('Test live', function () { it('Should have the live deleted', async function () { for (const server of servers) { await getVideo(server.url, liveVideoUUID, HttpStatusCode.NOT_FOUND_404) - await server.liveCommand.getLive({ videoId: liveVideoUUID, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) + await server.liveCommand.get({ videoId: liveVideoUUID, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) } }) }) @@ -230,7 +230,7 @@ describe('Test live', function () { vodVideoId = (await uploadVideoAndGetId({ server: servers[0], videoName: 'vod video' })).uuid const liveOptions = { name: 'live', privacy: VideoPrivacy.PUBLIC, channelId: servers[0].videoChannel.id } - const live = await commands[0].createLive({ fields: liveOptions }) + const live = await commands[0].create({ fields: liveOptions }) liveVideoId = live.uuid ffmpegCommand = await servers[0].liveCommand.sendRTMPStreamInVideo({ videoId: liveVideoId }) @@ -297,9 +297,9 @@ describe('Test live', function () { saveReplay: false } - const { uuid } = await commands[0].createLive({ fields: liveAttributes }) + const { uuid } = await commands[0].create({ fields: liveAttributes }) - const live = await commands[0].getLive({ videoId: uuid }) + const live = await commands[0].get({ videoId: uuid }) const resVideo = await getVideo(servers[0].url, uuid) return Object.assign(resVideo.body as VideoDetails, live) @@ -376,7 +376,7 @@ describe('Test live', function () { saveReplay } - const { uuid } = await commands[0].createLive({ fields: liveAttributes }) + const { uuid } = await commands[0].create({ fields: liveAttributes }) return uuid } @@ -403,7 +403,7 @@ describe('Test live', function () { for (let i = 0; i < resolutions.length; i++) { const segmentNum = 3 const segmentName = `${i}-00000${segmentNum}.ts` - await commands[0].waitUntilLiveSegmentGeneration({ videoUUID: video.uuid, resolution: i, segment: segmentNum }) + await commands[0].waitUntilSegmentGeneration({ videoUUID: video.uuid, resolution: i, segment: segmentNum }) const res = await getPlaylist(`${servers[0].url}/static/streaming-playlists/hls/${video.uuid}/${i}.m3u8`) const subPlaylist = res.text @@ -488,7 +488,7 @@ describe('Test live', function () { await testVideoResolutions(liveVideoId, resolutions) await stopFfmpeg(ffmpegCommand) - await commands[0].waitUntilLiveEnded({ videoId: liveVideoId }) + await commands[0].waitUntilEnded({ videoId: liveVideoId }) await waitJobs(servers) @@ -559,7 +559,7 @@ describe('Test live', function () { saveReplay } - const { uuid } = await commands[0].createLive({ fields: liveAttributes }) + const { uuid } = await commands[0].create({ fields: liveAttributes }) return uuid } @@ -575,14 +575,14 @@ describe('Test live', function () { ]) await Promise.all([ - commands[0].waitUntilLivePublished({ videoId: liveVideoId }), - commands[0].waitUntilLivePublished({ videoId: liveVideoReplayId }) + commands[0].waitUntilPublished({ videoId: liveVideoId }), + commands[0].waitUntilPublished({ videoId: liveVideoReplayId }) ]) - await commands[0].waitUntilLiveSegmentGeneration({ videoUUID: liveVideoId, resolution: 0, segment: 2 }) - await commands[0].waitUntilLiveSegmentGeneration({ videoUUID: liveVideoReplayId, resolution: 0, segment: 2 }) + await commands[0].waitUntilSegmentGeneration({ videoUUID: liveVideoId, resolution: 0, segment: 2 }) + await commands[0].waitUntilSegmentGeneration({ videoUUID: liveVideoReplayId, resolution: 0, segment: 2 }) - await killallServers([ servers[0] ]) + killallServers([ servers[0] ]) await reRunServer(servers[0]) await wait(5000) @@ -591,13 +591,13 @@ describe('Test live', function () { it('Should cleanup lives', async function () { this.timeout(60000) - await commands[0].waitUntilLiveEnded({ videoId: liveVideoId }) + await commands[0].waitUntilEnded({ videoId: liveVideoId }) }) it('Should save a live replay', async function () { this.timeout(120000) - await commands[0].waitUntilLivePublished({ videoId: liveVideoReplayId }) + await commands[0].waitUntilPublished({ videoId: liveVideoReplayId }) }) }) diff --git a/server/tests/api/search/search-videos.ts b/server/tests/api/search/search-videos.ts index af74b26a7..a0375fbf0 100644 --- a/server/tests/api/search/search-videos.ts +++ b/server/tests/api/search/search-videos.ts @@ -502,10 +502,10 @@ describe('Test videos search', function () { const liveCommand = server.liveCommand const liveAttributes = { name: 'live', privacy: VideoPrivacy.PUBLIC, channelId: server.videoChannel.id } - const live = await liveCommand.createLive({ fields: liveAttributes }) + const live = await liveCommand.create({ fields: liveAttributes }) const ffmpegCommand = await liveCommand.sendRTMPStreamInVideo({ videoId: live.id }) - await liveCommand.waitUntilLivePublished({ videoId: live.id }) + await liveCommand.waitUntilPublished({ videoId: live.id }) const body = await command.advancedVideoSearch({ search: { isLive: true } }) diff --git a/server/tests/api/videos/video-change-ownership.ts b/server/tests/api/videos/video-change-ownership.ts index 88e4d51a2..3c33cf015 100644 --- a/server/tests/api/videos/video-change-ownership.ts +++ b/server/tests/api/videos/video-change-ownership.ts @@ -111,7 +111,7 @@ describe('Test video change ownership - nominal', function () { { const attributes = { name: 'live', channelId: firstUserChannelId, privacy: VideoPrivacy.PUBLIC } - const video = await servers[0].liveCommand.createLive({ token: firstUserAccessToken, fields: attributes }) + const video = await servers[0].liveCommand.create({ token: firstUserAccessToken, fields: attributes }) liveId = video.id } diff --git a/server/tests/plugins/action-hooks.ts b/server/tests/plugins/action-hooks.ts index 39266c62f..5e9dc3515 100644 --- a/server/tests/plugins/action-hooks.ts +++ b/server/tests/plugins/action-hooks.ts @@ -95,7 +95,7 @@ describe('Test plugin action hooks', function () { channelId: servers[0].videoChannel.id } - await servers[0].liveCommand.createLive({ fields: attributes }) + await servers[0].liveCommand.create({ fields: attributes }) await checkHook('action:api.live-video.created') }) diff --git a/server/tests/plugins/filter-hooks.ts b/server/tests/plugins/filter-hooks.ts index e60bad38d..e938663da 100644 --- a/server/tests/plugins/filter-hooks.ts +++ b/server/tests/plugins/filter-hooks.ts @@ -155,7 +155,7 @@ describe('Test plugin filter hooks', function () { channelId: servers[0].videoChannel.id } - await servers[0].liveCommand.createLive({ fields: attributes, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) + await servers[0].liveCommand.create({ fields: attributes, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) it('Should run filter:api.video.pre-import-url.accept.result', async function () { diff --git a/server/tests/plugins/plugin-transcoding.ts b/server/tests/plugins/plugin-transcoding.ts index 65282419e..ca4d9f962 100644 --- a/server/tests/plugins/plugin-transcoding.ts +++ b/server/tests/plugins/plugin-transcoding.ts @@ -26,7 +26,7 @@ async function createLiveWrapper (server: ServerInfo) { privacy: VideoPrivacy.PUBLIC } - const { uuid } = await server.liveCommand.createLive({ fields: liveAttributes }) + const { uuid } = await server.liveCommand.create({ fields: liveAttributes }) return uuid } @@ -170,7 +170,7 @@ describe('Test transcoding plugins', function () { const liveVideoId = await createLiveWrapper(server) await server.liveCommand.sendRTMPStreamInVideo({ videoId: liveVideoId, fixtureName: 'video_short2.webm' }) - await server.liveCommand.waitUntilLivePublished({ videoId: liveVideoId }) + await server.liveCommand.waitUntilPublished({ videoId: liveVideoId }) await waitJobs([ server ]) await checkLiveFPS(liveVideoId, 'above', 20) @@ -184,7 +184,7 @@ describe('Test transcoding plugins', function () { const liveVideoId = await createLiveWrapper(server) await server.liveCommand.sendRTMPStreamInVideo({ videoId: liveVideoId, fixtureName: 'video_short2.webm' }) - await server.liveCommand.waitUntilLivePublished({ videoId: liveVideoId }) + await server.liveCommand.waitUntilPublished({ videoId: liveVideoId }) await waitJobs([ server ]) await checkLiveFPS(liveVideoId, 'below', 12) @@ -198,7 +198,7 @@ describe('Test transcoding plugins', function () { const liveVideoId = await createLiveWrapper(server) await server.liveCommand.sendRTMPStreamInVideo({ videoId: liveVideoId, fixtureName: 'video_short2.webm' }) - await server.liveCommand.waitUntilLivePublished({ videoId: liveVideoId }) + await server.liveCommand.waitUntilPublished({ videoId: liveVideoId }) await waitJobs([ server ]) await checkLiveFPS(liveVideoId, 'below', 6) @@ -261,7 +261,7 @@ describe('Test transcoding plugins', function () { const liveVideoId = await createLiveWrapper(server) await server.liveCommand.sendRTMPStreamInVideo({ videoId: liveVideoId, fixtureName: 'video_short2.webm' }) - await server.liveCommand.waitUntilLivePublished({ videoId: liveVideoId }) + await server.liveCommand.waitUntilPublished({ videoId: liveVideoId }) await waitJobs([ server ]) const playlistUrl = `${server.url}/static/streaming-playlists/hls/${liveVideoId}/0.m3u8` diff --git a/shared/extra-utils/videos/live-command.ts b/shared/extra-utils/videos/live-command.ts index 55811b8ba..e36c632ee 100644 --- a/shared/extra-utils/videos/live-command.ts +++ b/shared/extra-utils/videos/live-command.ts @@ -14,7 +14,7 @@ import { getVideoWithToken } from './videos' export class LiveCommand extends AbstractCommand { - getLive (options: OverrideCommandOptions & { + get (options: OverrideCommandOptions & { videoId: number | string }) { const path = '/api/v1/videos/live' @@ -27,7 +27,7 @@ export class LiveCommand extends AbstractCommand { }) } - updateLive (options: OverrideCommandOptions & { + update (options: OverrideCommandOptions & { videoId: number | string fields: LiveVideoUpdate }) { @@ -43,7 +43,7 @@ export class LiveCommand extends AbstractCommand { }) } - async createLive (options: OverrideCommandOptions & { + async create (options: OverrideCommandOptions & { fields: LiveVideoCreate }) { const { fields } = options @@ -70,12 +70,12 @@ export class LiveCommand extends AbstractCommand { fixtureName?: string }) { const { videoId, fixtureName } = options - const videoLive = await this.getLive({ videoId }) + const videoLive = await this.get({ videoId }) return sendRTMPStream(videoLive.rtmpUrl, videoLive.streamKey, fixtureName) } - async runAndTestFfmpegStreamError (options: OverrideCommandOptions & { + async runAndTestStreamError (options: OverrideCommandOptions & { videoId: number | string shouldHaveError: boolean }) { @@ -84,28 +84,28 @@ export class LiveCommand extends AbstractCommand { return testFfmpegStreamError(command, options.shouldHaveError) } - waitUntilLivePublished (options: OverrideCommandOptions & { + waitUntilPublished (options: OverrideCommandOptions & { videoId: number | string }) { const { videoId } = options - return this.waitUntilLiveState({ videoId, state: VideoState.PUBLISHED }) + return this.waitUntilState({ videoId, state: VideoState.PUBLISHED }) } - waitUntilLiveWaiting (options: OverrideCommandOptions & { + waitUntilWaiting (options: OverrideCommandOptions & { videoId: number | string }) { const { videoId } = options - return this.waitUntilLiveState({ videoId, state: VideoState.WAITING_FOR_LIVE }) + return this.waitUntilState({ videoId, state: VideoState.WAITING_FOR_LIVE }) } - waitUntilLiveEnded (options: OverrideCommandOptions & { + waitUntilEnded (options: OverrideCommandOptions & { videoId: number | string }) { const { videoId } = options - return this.waitUntilLiveState({ videoId, state: VideoState.LIVE_ENDED }) + return this.waitUntilState({ videoId, state: VideoState.LIVE_ENDED }) } - waitUntilLiveSegmentGeneration (options: OverrideCommandOptions & { + waitUntilSegmentGeneration (options: OverrideCommandOptions & { videoUUID: string resolution: number segment: number @@ -116,7 +116,7 @@ export class LiveCommand extends AbstractCommand { return waitUntilLog(this.server, `${videoUUID}/${segmentName}`, 2, false) } - async waitUntilLiveSaved (options: OverrideCommandOptions & { + async waitUntilSaved (options: OverrideCommandOptions & { videoId: number | string }) { let video: VideoDetails @@ -129,7 +129,7 @@ export class LiveCommand extends AbstractCommand { } while (video.isLive === true && video.state.id !== VideoState.PUBLISHED) } - async getPlaylistsCount (options: OverrideCommandOptions & { + async countPlaylists (options: OverrideCommandOptions & { videoUUID: string }) { const basePath = buildServerDirectory(this.server, 'streaming-playlists') @@ -140,7 +140,7 @@ export class LiveCommand extends AbstractCommand { return files.filter(f => f.endsWith('.m3u8')).length } - private async waitUntilLiveState (options: OverrideCommandOptions & { + private async waitUntilState (options: OverrideCommandOptions & { videoId: number | string state: VideoState }) { diff --git a/shared/extra-utils/videos/live.ts b/shared/extra-utils/videos/live.ts index 285a39c7e..92cb9104c 100644 --- a/shared/extra-utils/videos/live.ts +++ b/shared/extra-utils/videos/live.ts @@ -72,7 +72,7 @@ async function stopFfmpeg (command: ffmpeg.FfmpegCommand) { async function waitUntilLivePublishedOnAllServers (servers: ServerInfo[], videoId: string) { for (const server of servers) { - await server.liveCommand.waitUntilLivePublished({ videoId }) + await server.liveCommand.waitUntilPublished({ videoId }) } } -- cgit v1.2.3 From a1637fa1e25b60a88f7cfe50aac8953f50d55761 Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Thu, 8 Jul 2021 10:55:16 +0200 Subject: Specify if we want to fallback to the server token --- shared/extra-utils/bulk/bulk-command.ts | 2 ++ .../custom-pages/custom-pages-command.ts | 4 +++ shared/extra-utils/feeds/feeds-command.ts | 2 ++ shared/extra-utils/logs/logs-command.ts | 2 ++ shared/extra-utils/moderation/abuses-command.ts | 29 +++++++++++++-- shared/extra-utils/overviews/overviews-command.ts | 4 +-- shared/extra-utils/search/search-command.ts | 15 ++++---- shared/extra-utils/server/config-command.ts | 7 ++-- shared/extra-utils/server/contact-form-command.ts | 2 +- shared/extra-utils/server/debug-command.ts | 2 ++ shared/extra-utils/server/follows-command.ts | 11 +++--- shared/extra-utils/server/jobs-command.ts | 1 + shared/extra-utils/server/plugins-command.ts | 12 +++++++ shared/extra-utils/server/redundancy-command.ts | 4 +++ shared/extra-utils/server/stats-command.ts | 1 + shared/extra-utils/shared/abstract-command.ts | 41 ++++++++++++++-------- shared/extra-utils/users/accounts-command.ts | 3 ++ shared/extra-utils/users/blocklist-command.ts | 5 +++ shared/extra-utils/users/subscriptions-command.ts | 6 ++++ shared/extra-utils/videos/live-command.ts | 3 ++ shared/extra-utils/videos/services-command.ts | 1 + 21 files changed, 122 insertions(+), 35 deletions(-) diff --git a/shared/extra-utils/bulk/bulk-command.ts b/shared/extra-utils/bulk/bulk-command.ts index fcbf04164..6dac6034f 100644 --- a/shared/extra-utils/bulk/bulk-command.ts +++ b/shared/extra-utils/bulk/bulk-command.ts @@ -12,8 +12,10 @@ export class BulkCommand extends AbstractCommand { return this.postBodyRequest({ ...options, + path: '/api/v1/bulk/remove-comments-of', fields: attributes, + implicitToken: true, defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 }) } diff --git a/shared/extra-utils/custom-pages/custom-pages-command.ts b/shared/extra-utils/custom-pages/custom-pages-command.ts index a062c9774..0dd77503e 100644 --- a/shared/extra-utils/custom-pages/custom-pages-command.ts +++ b/shared/extra-utils/custom-pages/custom-pages-command.ts @@ -9,7 +9,9 @@ export class CustomPagesCommand extends AbstractCommand { return this.getRequestBody({ ...options, + path, + implicitToken: false, defaultExpectedStatus: HttpStatusCode.OK_200 }) } @@ -22,8 +24,10 @@ export class CustomPagesCommand extends AbstractCommand { return this.putBodyRequest({ ...options, + path, fields: { content }, + implicitToken: true, defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 }) } diff --git a/shared/extra-utils/feeds/feeds-command.ts b/shared/extra-utils/feeds/feeds-command.ts index 8031adf92..2da4110a7 100644 --- a/shared/extra-utils/feeds/feeds-command.ts +++ b/shared/extra-utils/feeds/feeds-command.ts @@ -19,6 +19,7 @@ export class FeedCommand extends AbstractCommand { path, query: format ? { format } : undefined, accept: 'application/xml', + implicitToken: false, defaultExpectedStatus: HttpStatusCode.OK_200 }) } @@ -36,6 +37,7 @@ export class FeedCommand extends AbstractCommand { path, query, accept: 'application/json', + implicitToken: false, defaultExpectedStatus: HttpStatusCode.OK_200 }) } diff --git a/shared/extra-utils/logs/logs-command.ts b/shared/extra-utils/logs/logs-command.ts index f7594734d..f34c58c47 100644 --- a/shared/extra-utils/logs/logs-command.ts +++ b/shared/extra-utils/logs/logs-command.ts @@ -17,6 +17,7 @@ export class LogsCommand extends AbstractCommand { path, query: { startDate, endDate, level }, + implicitToken: true, defaultExpectedStatus: HttpStatusCode.OK_200 }) } @@ -34,6 +35,7 @@ export class LogsCommand extends AbstractCommand { path, query: { startDate, endDate }, + implicitToken: true, defaultExpectedStatus: HttpStatusCode.OK_200 }) } diff --git a/shared/extra-utils/moderation/abuses-command.ts b/shared/extra-utils/moderation/abuses-command.ts index 59126d0a9..03da0c85a 100644 --- a/shared/extra-utils/moderation/abuses-command.ts +++ b/shared/extra-utils/moderation/abuses-command.ts @@ -60,6 +60,7 @@ export class AbusesCommand extends AbstractCommand { path, fields: body, + implicitToken: true, defaultExpectedStatus: HttpStatusCode.OK_200 })) } @@ -106,6 +107,7 @@ export class AbusesCommand extends AbstractCommand { path, query, + implicitToken: true, defaultExpectedStatus: HttpStatusCode.OK_200 }) } @@ -138,6 +140,7 @@ export class AbusesCommand extends AbstractCommand { path, query, + implicitToken: true, defaultExpectedStatus: HttpStatusCode.OK_200 }) } @@ -154,6 +157,7 @@ export class AbusesCommand extends AbstractCommand { path, fields: body, + implicitToken: true, defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 }) } @@ -164,7 +168,13 @@ export class AbusesCommand extends AbstractCommand { const { abuseId } = options const path = '/api/v1/abuses/' + abuseId - return this.deleteRequest({ ...options, path, defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 }) + return this.deleteRequest({ + ...options, + + path, + implicitToken: true, + defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 + }) } listMessages (options: OverrideCommandOptions & { @@ -173,7 +183,13 @@ export class AbusesCommand extends AbstractCommand { const { abuseId } = options const path = '/api/v1/abuses/' + abuseId + '/messages' - return this.getRequestBody>({ ...options, path, defaultExpectedStatus: HttpStatusCode.OK_200 }) + return this.getRequestBody>({ + ...options, + + path, + implicitToken: true, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) } deleteMessage (options: OverrideCommandOptions & { @@ -183,7 +199,13 @@ export class AbusesCommand extends AbstractCommand { const { abuseId, messageId } = options const path = '/api/v1/abuses/' + abuseId + '/messages/' + messageId - return this.deleteRequest({ ...options, path, defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 }) + return this.deleteRequest({ + ...options, + + path, + implicitToken: true, + defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 + }) } addMessage (options: OverrideCommandOptions & { @@ -198,6 +220,7 @@ export class AbusesCommand extends AbstractCommand { path, fields: { message }, + implicitToken: true, defaultExpectedStatus: HttpStatusCode.OK_200 }) } diff --git a/shared/extra-utils/overviews/overviews-command.ts b/shared/extra-utils/overviews/overviews-command.ts index 6f56b0ce4..e15644d94 100644 --- a/shared/extra-utils/overviews/overviews-command.ts +++ b/shared/extra-utils/overviews/overviews-command.ts @@ -7,7 +7,7 @@ export class OverviewsCommand extends AbstractCommand { getVideos (options: OverrideCommandOptions & { page: number }) { - const { token, page } = options + const { page } = options const path = '/api/v1/overviews/videos' const query = { page } @@ -15,9 +15,9 @@ export class OverviewsCommand extends AbstractCommand { return this.getRequestBody({ ...options, - token: token || null, path, query, + implicitToken: false, defaultExpectedStatus: HttpStatusCode.OK_200 }) } diff --git a/shared/extra-utils/search/search-command.ts b/shared/extra-utils/search/search-command.ts index d4cfab32b..7539a21ec 100644 --- a/shared/extra-utils/search/search-command.ts +++ b/shared/extra-utils/search/search-command.ts @@ -25,16 +25,15 @@ export class SearchCommand extends AbstractCommand { advancedChannelSearch (options: OverrideCommandOptions & { search: VideoChannelsSearchQuery }) { - const { search, token } = options + const { search } = options const path = '/api/v1/search/video-channels' return this.getRequestBody>({ ...options, - token: token || null, - path, query: search, + implicitToken: false, defaultExpectedStatus: HttpStatusCode.OK_200 }) } @@ -52,16 +51,15 @@ export class SearchCommand extends AbstractCommand { advancedPlaylistSearch (options: OverrideCommandOptions & { search: VideoPlaylistsSearchQuery }) { - const { search, token } = options + const { search } = options const path = '/api/v1/search/video-playlists' return this.getRequestBody>({ ...options, - token: token || null, - path, query: search, + implicitToken: false, defaultExpectedStatus: HttpStatusCode.OK_200 }) } @@ -85,16 +83,15 @@ export class SearchCommand extends AbstractCommand { advancedVideoSearch (options: OverrideCommandOptions & { search: VideosSearchQuery }) { - const { search, token } = options + const { search } = options const path = '/api/v1/search/videos' return this.getRequestBody>({ ...options, - token: token || null, - path, query: search, + implicitToken: false, defaultExpectedStatus: HttpStatusCode.OK_200 }) } diff --git a/shared/extra-utils/server/config-command.ts b/shared/extra-utils/server/config-command.ts index 959848706..f5d7fc5e3 100644 --- a/shared/extra-utils/server/config-command.ts +++ b/shared/extra-utils/server/config-command.ts @@ -24,8 +24,8 @@ export class ConfigCommand extends AbstractCommand { return this.getRequestBody({ ...options, - token: null, path, + implicitToken: false, defaultExpectedStatus: HttpStatusCode.OK_200 }) } @@ -36,8 +36,8 @@ export class ConfigCommand extends AbstractCommand { return this.getRequestBody({ ...options, - token: null, path, + implicitToken: false, defaultExpectedStatus: HttpStatusCode.OK_200 }) } @@ -49,6 +49,7 @@ export class ConfigCommand extends AbstractCommand { ...options, path, + implicitToken: true, defaultExpectedStatus: HttpStatusCode.OK_200 }) } @@ -63,6 +64,7 @@ export class ConfigCommand extends AbstractCommand { path, fields: options.newCustomConfig, + implicitToken: true, defaultExpectedStatus: HttpStatusCode.OK_200 }) } @@ -74,6 +76,7 @@ export class ConfigCommand extends AbstractCommand { ...options, path, + implicitToken: true, defaultExpectedStatus: HttpStatusCode.OK_200 }) } diff --git a/shared/extra-utils/server/contact-form-command.ts b/shared/extra-utils/server/contact-form-command.ts index 943e5ccbb..8d034552b 100644 --- a/shared/extra-utils/server/contact-form-command.ts +++ b/shared/extra-utils/server/contact-form-command.ts @@ -23,8 +23,8 @@ export class ContactFormCommand extends AbstractCommand { ...options, path, - token: null, fields: body, + implicitToken: false, defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 }) } diff --git a/shared/extra-utils/server/debug-command.ts b/shared/extra-utils/server/debug-command.ts index eecbb1711..8b24b3067 100644 --- a/shared/extra-utils/server/debug-command.ts +++ b/shared/extra-utils/server/debug-command.ts @@ -11,6 +11,7 @@ export class DebugCommand extends AbstractCommand { ...options, path, + implicitToken: true, defaultExpectedStatus: HttpStatusCode.OK_200 }) } @@ -26,6 +27,7 @@ export class DebugCommand extends AbstractCommand { path, fields: body, + implicitToken: true, defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 }) } diff --git a/shared/extra-utils/server/follows-command.ts b/shared/extra-utils/server/follows-command.ts index aba7bce82..4e1e56d7a 100644 --- a/shared/extra-utils/server/follows-command.ts +++ b/shared/extra-utils/server/follows-command.ts @@ -22,10 +22,9 @@ export class FollowsCommand extends AbstractCommand { return this.getRequestBody>({ ...options, - token: null, - path, query, + implicitToken: false, defaultExpectedStatus: HttpStatusCode.OK_200 }) } @@ -46,10 +45,9 @@ export class FollowsCommand extends AbstractCommand { return this.getRequestBody>({ ...options, - token: null, - path, query, + implicitToken: false, defaultExpectedStatus: HttpStatusCode.OK_200 }) } @@ -66,6 +64,7 @@ export class FollowsCommand extends AbstractCommand { path, fields: { hosts }, + implicitToken: true, defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 }) } @@ -79,6 +78,7 @@ export class FollowsCommand extends AbstractCommand { ...options, path, + implicitToken: true, defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 }) } @@ -92,6 +92,7 @@ export class FollowsCommand extends AbstractCommand { ...options, path, + implicitToken: true, defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 }) } @@ -105,6 +106,7 @@ export class FollowsCommand extends AbstractCommand { ...options, path, + implicitToken: true, defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 }) } @@ -118,6 +120,7 @@ export class FollowsCommand extends AbstractCommand { ...options, path, + implicitToken: true, defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 }) } diff --git a/shared/extra-utils/server/jobs-command.ts b/shared/extra-utils/server/jobs-command.ts index 758b4a4af..392b868c1 100644 --- a/shared/extra-utils/server/jobs-command.ts +++ b/shared/extra-utils/server/jobs-command.ts @@ -21,6 +21,7 @@ export class JobsCommand extends AbstractCommand { path, query, + implicitToken: true, defaultExpectedStatus: HttpStatusCode.OK_200 }) } diff --git a/shared/extra-utils/server/plugins-command.ts b/shared/extra-utils/server/plugins-command.ts index f06e58a22..ff49d58c4 100644 --- a/shared/extra-utils/server/plugins-command.ts +++ b/shared/extra-utils/server/plugins-command.ts @@ -45,6 +45,7 @@ export class PluginsCommand extends AbstractCommand { pluginType, uninstalled }, + implicitToken: true, defaultExpectedStatus: HttpStatusCode.OK_200 }) } @@ -75,6 +76,7 @@ export class PluginsCommand extends AbstractCommand { path, query, + implicitToken: true, defaultExpectedStatus: HttpStatusCode.OK_200 }) } @@ -88,6 +90,7 @@ export class PluginsCommand extends AbstractCommand { ...options, path, + implicitToken: true, defaultExpectedStatus: HttpStatusCode.OK_200 }) } @@ -104,6 +107,7 @@ export class PluginsCommand extends AbstractCommand { path, fields: { settings }, + implicitToken: true, defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 }) } @@ -117,6 +121,7 @@ export class PluginsCommand extends AbstractCommand { ...options, path, + implicitToken: true, defaultExpectedStatus: HttpStatusCode.OK_200 }) } @@ -131,6 +136,7 @@ export class PluginsCommand extends AbstractCommand { ...options, path, + implicitToken: false, defaultExpectedStatus: HttpStatusCode.OK_200 }) } @@ -145,6 +151,7 @@ export class PluginsCommand extends AbstractCommand { ...options, path, + implicitToken: false, defaultExpectedStatus: HttpStatusCode.OK_200 }) } @@ -161,6 +168,7 @@ export class PluginsCommand extends AbstractCommand { path: apiPath, fields: { npmName, path }, + implicitToken: true, defaultExpectedStatus: HttpStatusCode.OK_200 }) } @@ -177,6 +185,7 @@ export class PluginsCommand extends AbstractCommand { path: apiPath, fields: { npmName, path }, + implicitToken: true, defaultExpectedStatus: HttpStatusCode.OK_200 }) } @@ -192,6 +201,7 @@ export class PluginsCommand extends AbstractCommand { path: apiPath, fields: { npmName }, + implicitToken: true, defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 }) } @@ -203,6 +213,7 @@ export class PluginsCommand extends AbstractCommand { ...options, path, + implicitToken: false, defaultExpectedStatus: HttpStatusCode.OK_200 }) } @@ -222,6 +233,7 @@ export class PluginsCommand extends AbstractCommand { path, query, + implicitToken: false, defaultExpectedStatus: HttpStatusCode.OK_200, redirects: 0 }) diff --git a/shared/extra-utils/server/redundancy-command.ts b/shared/extra-utils/server/redundancy-command.ts index d717d35f8..728332fdd 100644 --- a/shared/extra-utils/server/redundancy-command.ts +++ b/shared/extra-utils/server/redundancy-command.ts @@ -16,6 +16,7 @@ export class RedundancyCommand extends AbstractCommand { path, fields: { redundancyAllowed }, + implicitToken: true, defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 }) } @@ -42,6 +43,7 @@ export class RedundancyCommand extends AbstractCommand { target }, + implicitToken: true, defaultExpectedStatus: HttpStatusCode.OK_200 }) } @@ -57,6 +59,7 @@ export class RedundancyCommand extends AbstractCommand { path, fields: { videoId }, + implicitToken: true, defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 }) } @@ -71,6 +74,7 @@ export class RedundancyCommand extends AbstractCommand { ...options, path, + implicitToken: true, defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 }) } diff --git a/shared/extra-utils/server/stats-command.ts b/shared/extra-utils/server/stats-command.ts index b51d9ceef..f0f02ca08 100644 --- a/shared/extra-utils/server/stats-command.ts +++ b/shared/extra-utils/server/stats-command.ts @@ -19,6 +19,7 @@ export class StatsCommand extends AbstractCommand { path, query, + implicitToken: false, defaultExpectedStatus: HttpStatusCode.OK_200 }) } diff --git a/shared/extra-utils/shared/abstract-command.ts b/shared/extra-utils/shared/abstract-command.ts index 38129d559..1e07e9469 100644 --- a/shared/extra-utils/shared/abstract-command.ts +++ b/shared/extra-utils/shared/abstract-command.ts @@ -1,5 +1,13 @@ import { HttpStatusCode } from '@shared/core-utils' -import { makeDeleteRequest, makeGetRequest, makePostBodyRequest, makePutBodyRequest, makeUploadRequest, unwrapBody, unwrapText } from '../requests/requests' +import { + makeDeleteRequest, + makeGetRequest, + makePostBodyRequest, + makePutBodyRequest, + makeUploadRequest, + unwrapBody, + unwrapText +} from '../requests/requests' import { ServerInfo } from '../server/servers' export interface OverrideCommandOptions { @@ -7,12 +15,14 @@ export interface OverrideCommandOptions { expectedStatus?: number } -interface CommonCommandOptions extends OverrideCommandOptions { +interface InternalCommonCommandOptions extends OverrideCommandOptions { path: string + // If we automatically send the server token if the token is not provided + implicitToken: boolean defaultExpectedStatus: number } -interface GetCommandOptions extends CommonCommandOptions { +interface InternalGetCommandOptions extends InternalCommonCommandOptions { query?: { [ id: string ]: any } contentType?: string accept?: string @@ -37,15 +47,15 @@ abstract class AbstractCommand { this.expectedStatus = status } - protected getRequestBody (options: GetCommandOptions) { + protected getRequestBody (options: InternalGetCommandOptions) { return unwrapBody(this.getRequest(options)) } - protected getRequestText (options: GetCommandOptions) { + protected getRequestText (options: InternalGetCommandOptions) { return unwrapText(this.getRequest(options)) } - protected getRequest (options: GetCommandOptions) { + protected getRequest (options: InternalGetCommandOptions) { const { redirects, query, contentType, accept } = options return makeGetRequest({ @@ -58,11 +68,11 @@ abstract class AbstractCommand { }) } - protected deleteRequest (options: CommonCommandOptions) { + protected deleteRequest (options: InternalCommonCommandOptions) { return makeDeleteRequest(this.buildCommonRequestOptions(options)) } - protected putBodyRequest (options: CommonCommandOptions & { + protected putBodyRequest (options: InternalCommonCommandOptions & { fields?: { [ fieldName: string ]: any } }) { const { fields } = options @@ -74,7 +84,7 @@ abstract class AbstractCommand { }) } - protected postBodyRequest (options: CommonCommandOptions & { + protected postBodyRequest (options: InternalCommonCommandOptions & { fields?: { [ fieldName: string ]: any } }) { const { fields } = options @@ -86,7 +96,7 @@ abstract class AbstractCommand { }) } - protected postUploadRequest (options: CommonCommandOptions & { + protected postUploadRequest (options: InternalCommonCommandOptions & { fields?: { [ fieldName: string ]: any } attaches?: any }) { @@ -101,7 +111,7 @@ abstract class AbstractCommand { }) } - protected putUploadRequest (options: CommonCommandOptions & { + protected putUploadRequest (options: InternalCommonCommandOptions & { fields?: { [ fieldName: string ]: any } attaches?: any }) { @@ -116,15 +126,18 @@ abstract class AbstractCommand { }) } - private buildCommonRequestOptions (options: CommonCommandOptions) { + private buildCommonRequestOptions (options: InternalCommonCommandOptions) { const { token, expectedStatus, defaultExpectedStatus, path } = options + const fallbackToken = options.implicitToken + ? this.server.accessToken + : undefined + return { url: this.server.url, path, - // Token can be null if we don't want to add it - token: token !== undefined ? token : this.server.accessToken, + token: token !== undefined ? token : fallbackToken, statusCodeExpected: expectedStatus ?? this.expectedStatus ?? defaultExpectedStatus } diff --git a/shared/extra-utils/users/accounts-command.ts b/shared/extra-utils/users/accounts-command.ts index 89c080e93..4cd1d2158 100644 --- a/shared/extra-utils/users/accounts-command.ts +++ b/shared/extra-utils/users/accounts-command.ts @@ -17,6 +17,7 @@ export class AccountsCommand extends AbstractCommand { path, query: { sort }, + implicitToken: false, defaultExpectedStatus: HttpStatusCode.OK_200 }) } @@ -30,6 +31,7 @@ export class AccountsCommand extends AbstractCommand { ...options, path, + implicitToken: false, defaultExpectedStatus: HttpStatusCode.OK_200 }) } @@ -48,6 +50,7 @@ export class AccountsCommand extends AbstractCommand { path, query, + implicitToken: true, defaultExpectedStatus: HttpStatusCode.OK_200 }) } diff --git a/shared/extra-utils/users/blocklist-command.ts b/shared/extra-utils/users/blocklist-command.ts index 96afdc3fd..089b5a579 100644 --- a/shared/extra-utils/users/blocklist-command.ts +++ b/shared/extra-utils/users/blocklist-command.ts @@ -56,6 +56,7 @@ export class BlocklistCommand extends AbstractCommand { accountName: account, host: server }, + implicitToken: true, defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 }) } @@ -78,6 +79,7 @@ export class BlocklistCommand extends AbstractCommand { accountName: account, host: server }, + implicitToken: true, defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 }) } @@ -98,6 +100,7 @@ export class BlocklistCommand extends AbstractCommand { ...options, path, + implicitToken: true, defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 }) } @@ -116,6 +119,7 @@ export class BlocklistCommand extends AbstractCommand { ...options, path, + implicitToken: true, defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 }) } @@ -128,6 +132,7 @@ export class BlocklistCommand extends AbstractCommand { path, query: { start, count, sort }, + implicitToken: true, defaultExpectedStatus: HttpStatusCode.OK_200 }) } diff --git a/shared/extra-utils/users/subscriptions-command.ts b/shared/extra-utils/users/subscriptions-command.ts index 94d2af67a..e998eb426 100644 --- a/shared/extra-utils/users/subscriptions-command.ts +++ b/shared/extra-utils/users/subscriptions-command.ts @@ -14,6 +14,7 @@ export class SubscriptionsCommand extends AbstractCommand { path, fields: { uri: options.targetUri }, + implicitToken: true, defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 }) } @@ -33,6 +34,7 @@ export class SubscriptionsCommand extends AbstractCommand { sort, search }, + implicitToken: true, defaultExpectedStatus: HttpStatusCode.OK_200 }) } @@ -48,6 +50,7 @@ export class SubscriptionsCommand extends AbstractCommand { path, query: { sort }, + implicitToken: true, defaultExpectedStatus: HttpStatusCode.OK_200 }) } @@ -61,6 +64,7 @@ export class SubscriptionsCommand extends AbstractCommand { ...options, path, + implicitToken: true, defaultExpectedStatus: HttpStatusCode.OK_200 }) } @@ -74,6 +78,7 @@ export class SubscriptionsCommand extends AbstractCommand { ...options, path, + implicitToken: true, defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 }) } @@ -88,6 +93,7 @@ export class SubscriptionsCommand extends AbstractCommand { path, query: { 'uris[]': options.uris }, + implicitToken: true, defaultExpectedStatus: HttpStatusCode.OK_200 }) } diff --git a/shared/extra-utils/videos/live-command.ts b/shared/extra-utils/videos/live-command.ts index e36c632ee..4f03c9127 100644 --- a/shared/extra-utils/videos/live-command.ts +++ b/shared/extra-utils/videos/live-command.ts @@ -23,6 +23,7 @@ export class LiveCommand extends AbstractCommand { ...options, path: path + '/' + options.videoId, + implicitToken: true, defaultExpectedStatus: HttpStatusCode.OK_200 }) } @@ -39,6 +40,7 @@ export class LiveCommand extends AbstractCommand { path: path + '/' + videoId, fields, + implicitToken: true, defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 }) } @@ -59,6 +61,7 @@ export class LiveCommand extends AbstractCommand { path, attaches, fields: omit(fields, 'thumbnailfile', 'previewfile'), + implicitToken: true, defaultExpectedStatus: HttpStatusCode.OK_200 })) diff --git a/shared/extra-utils/videos/services-command.ts b/shared/extra-utils/videos/services-command.ts index 3b618ef66..313b7878c 100644 --- a/shared/extra-utils/videos/services-command.ts +++ b/shared/extra-utils/videos/services-command.ts @@ -22,6 +22,7 @@ export class ServicesCommand extends AbstractCommand { path, query, + implicitToken: false, defaultExpectedStatus: HttpStatusCode.OK_200 }) } -- cgit v1.2.3 From e3d15a6a9aed97a004d9dac1b7a6499d794e080a Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Thu, 8 Jul 2021 11:17:55 +0200 Subject: Introduce blacklist command --- server/tests/api/check-params/video-blacklist.ts | 47 +++---- server/tests/api/live/live-save-replay.ts | 5 +- server/tests/api/live/live.ts | 3 +- server/tests/api/moderation/video-blacklist.ts | 144 ++++++++------------- .../api/notifications/moderation-notifications.ts | 12 +- server/tests/api/server/email.ts | 6 +- server/tests/api/users/users.ts | 3 +- server/tests/api/videos/video-playlists.ts | 6 +- server/tests/external-plugins/auto-block-videos.ts | 11 +- shared/extra-utils/server/servers.ts | 4 +- shared/extra-utils/videos/blacklist-command.ts | 77 +++++++++++ shared/extra-utils/videos/index.ts | 2 +- shared/extra-utils/videos/video-blacklist.ts | 79 ----------- 13 files changed, 173 insertions(+), 226 deletions(-) create mode 100644 shared/extra-utils/videos/blacklist-command.ts delete mode 100644 shared/extra-utils/videos/video-blacklist.ts diff --git a/server/tests/api/check-params/video-blacklist.ts b/server/tests/api/check-params/video-blacklist.ts index ce7f5fa17..98cf2e11a 100644 --- a/server/tests/api/check-params/video-blacklist.ts +++ b/server/tests/api/check-params/video-blacklist.ts @@ -1,32 +1,28 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ import 'mocha' - +import { expect } from 'chai' +import { HttpStatusCode } from '@shared/core-utils' import { + BlacklistCommand, + checkBadCountPagination, + checkBadSortPagination, + checkBadStartPagination, cleanupTests, createUser, doubleFollow, flushAndRunMultipleServers, - getBlacklistedVideosList, getVideo, getVideoWithToken, makePostBodyRequest, makePutBodyRequest, - removeVideoFromBlacklist, ServerInfo, setAccessTokensToServers, uploadVideo, userLogin, waitJobs -} from '../../../../shared/extra-utils' -import { - checkBadCountPagination, - checkBadSortPagination, - checkBadStartPagination -} from '../../../../shared/extra-utils/requests/check-api-params' -import { VideoBlacklistType, VideoDetails } from '../../../../shared/models/videos' -import { expect } from 'chai' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' +} from '@shared/extra-utils' +import { VideoBlacklistType, VideoDetails } from '@shared/models' describe('Test video blacklist API validators', function () { let servers: ServerInfo[] @@ -34,6 +30,7 @@ describe('Test video blacklist API validators', function () { let remoteVideoUUID: string let userAccessToken1 = '' let userAccessToken2 = '' + let command: BlacklistCommand // --------------------------------------------------------------- @@ -75,6 +72,8 @@ describe('Test video blacklist API validators', function () { } await waitJobs(servers) + + command = servers[0].blacklistCommand }) describe('When adding a video in blacklist', function () { @@ -234,25 +233,26 @@ describe('Test video blacklist API validators', function () { }) describe('When removing a video in blacklist', function () { + it('Should fail with a non authenticated user', async function () { - await removeVideoFromBlacklist(servers[0].url, 'fake token', servers[0].video.uuid, HttpStatusCode.UNAUTHORIZED_401) + await command.remove({ token: 'fake token', videoId: servers[0].video.uuid, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should fail with a non admin user', async function () { - await removeVideoFromBlacklist(servers[0].url, userAccessToken2, servers[0].video.uuid, HttpStatusCode.FORBIDDEN_403) + await command.remove({ token: userAccessToken2, videoId: servers[0].video.uuid, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) it('Should fail with an incorrect id', async function () { - await removeVideoFromBlacklist(servers[0].url, servers[0].accessToken, 'hello', HttpStatusCode.BAD_REQUEST_400) + await command.remove({ videoId: 'hello', expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) it('Should fail with a not blacklisted video', async function () { // The video was not added to the blacklist so it should fail - await removeVideoFromBlacklist(servers[0].url, servers[0].accessToken, notBlacklistedVideoId, HttpStatusCode.NOT_FOUND_404) + await command.remove({ videoId: notBlacklistedVideoId, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) it('Should succeed with the correct params', async function () { - await removeVideoFromBlacklist(servers[0].url, servers[0].accessToken, servers[0].video.uuid, HttpStatusCode.NO_CONTENT_204) + await command.remove({ videoId: servers[0].video.uuid, expectedStatus: HttpStatusCode.NO_CONTENT_204 }) }) }) @@ -260,11 +260,11 @@ describe('Test video blacklist API validators', function () { const basePath = '/api/v1/videos/blacklist/' it('Should fail with a non authenticated user', async function () { - await getBlacklistedVideosList({ url: servers[0].url, token: 'fake token', specialStatus: HttpStatusCode.UNAUTHORIZED_401 }) + await servers[0].blacklistCommand.list({ token: 'fake token', expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should fail with a non admin user', async function () { - await getBlacklistedVideosList({ url: servers[0].url, token: userAccessToken2, specialStatus: HttpStatusCode.FORBIDDEN_403 }) + await servers[0].blacklistCommand.list({ token: userAccessToken2, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) it('Should fail with a bad start pagination', async function () { @@ -280,16 +280,11 @@ describe('Test video blacklist API validators', function () { }) it('Should fail with an invalid type', async function () { - await getBlacklistedVideosList({ - url: servers[0].url, - token: servers[0].accessToken, - type: 0, - specialStatus: HttpStatusCode.BAD_REQUEST_400 - }) + await servers[0].blacklistCommand.list({ type: 0, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) it('Should succeed with the correct parameters', async function () { - await getBlacklistedVideosList({ url: servers[0].url, token: servers[0].accessToken, type: VideoBlacklistType.MANUAL }) + await servers[0].blacklistCommand.list({ type: VideoBlacklistType.MANUAL }) }) }) diff --git a/server/tests/api/live/live-save-replay.ts b/server/tests/api/live/live-save-replay.ts index 9acd5601d..363fb561c 100644 --- a/server/tests/api/live/live-save-replay.ts +++ b/server/tests/api/live/live-save-replay.ts @@ -6,7 +6,6 @@ import { FfmpegCommand } from 'fluent-ffmpeg' import { LiveVideoCreate, VideoDetails, VideoPrivacy, VideoState } from '@shared/models' import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' import { - addVideoToBlacklist, checkLiveCleanup, cleanupTests, ConfigCommand, @@ -172,7 +171,7 @@ describe('Save replay setting', function () { await checkVideosExist(liveVideoUUID, true, HttpStatusCode.OK_200) await Promise.all([ - addVideoToBlacklist(servers[0].url, servers[0].accessToken, liveVideoUUID, 'bad live', true), + servers[0].blacklistCommand.add({ videoId: liveVideoUUID, reason: 'bad live', unfederate: true }), testFfmpegStreamError(ffmpegCommand, true) ]) @@ -280,7 +279,7 @@ describe('Save replay setting', function () { await checkVideosExist(liveVideoUUID, true, HttpStatusCode.OK_200) await Promise.all([ - addVideoToBlacklist(servers[0].url, servers[0].accessToken, liveVideoUUID, 'bad live', true), + servers[0].blacklistCommand.add({ videoId: liveVideoUUID, reason: 'bad live', unfederate: true }), testFfmpegStreamError(ffmpegCommand, true) ]) diff --git a/server/tests/api/live/live.ts b/server/tests/api/live/live.ts index 5d70d8513..cb52e4431 100644 --- a/server/tests/api/live/live.ts +++ b/server/tests/api/live/live.ts @@ -7,7 +7,6 @@ import { ffprobePromise, getVideoStreamFromFile } from '@server/helpers/ffprobe- import { LiveVideo, LiveVideoCreate, Video, VideoDetails, VideoPrivacy, VideoState, VideoStreamingPlaylistType } from '@shared/models' import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' import { - addVideoToBlacklist, buildServerDirectory, checkLiveCleanup, checkLiveSegmentHash, @@ -347,7 +346,7 @@ describe('Test live', function () { liveVideo = await createLiveWrapper() - await addVideoToBlacklist(servers[0].url, servers[0].accessToken, liveVideo.uuid) + await servers[0].blacklistCommand.add({ videoId: liveVideo.uuid }) const command = sendRTMPStream(rtmpUrl + '/live', liveVideo.streamKey) await testFfmpegStreamError(command, true) diff --git a/server/tests/api/moderation/video-blacklist.ts b/server/tests/api/moderation/video-blacklist.ts index 4a4930c98..17a68e4a6 100644 --- a/server/tests/api/moderation/video-blacklist.ts +++ b/server/tests/api/moderation/video-blacklist.ts @@ -4,22 +4,19 @@ import 'mocha' import * as chai from 'chai' import { orderBy } from 'lodash' import { - addVideoToBlacklist, + BlacklistCommand, cleanupTests, createUser, doubleFollow, flushAndRunMultipleServers, - getBlacklistedVideosList, getMyUserInformation, getMyVideos, getVideosList, killallServers, - removeVideoFromBlacklist, reRunServer, ServerInfo, setAccessTokensToServers, updateVideo, - updateVideoBlacklist, uploadVideo, userLogin, waitJobs @@ -32,13 +29,14 @@ const expect = chai.expect describe('Test video blacklist', function () { let servers: ServerInfo[] = [] let videoId: number + let command: BlacklistCommand async function blacklistVideosOnServer (server: ServerInfo) { const res = await getVideosList(server.url) const videos = res.body.data for (const video of videos) { - await addVideoToBlacklist(server.url, server.accessToken, video.id, 'super reason') + await server.blacklistCommand.add({ videoId: video.id, reason: 'super reason' }) } } @@ -61,6 +59,8 @@ describe('Test video blacklist', function () { // Wait videos propagation, server 2 has transcoding enabled await waitJobs(servers) + command = servers[0].blacklistCommand + // Blacklist the two videos on server 1 await blacklistVideosOnServer(servers[0]) }) @@ -77,7 +77,7 @@ describe('Test video blacklist', function () { } { - const body = await servers[0].searchCommand.searchVideos({ search: 'name' }) + const body = await servers[0].searchCommand.searchVideos({ search: 'video' }) expect(body.total).to.equal(0) expect(body.data).to.be.an('array') @@ -95,7 +95,7 @@ describe('Test video blacklist', function () { } { - const body = await servers[1].searchCommand.searchVideos({ search: 'name' }) + const body = await servers[1].searchCommand.searchVideos({ search: 'video' }) expect(body.total).to.equal(2) expect(body.data).to.be.an('array') @@ -106,11 +106,10 @@ describe('Test video blacklist', function () { describe('When listing manually blacklisted videos', function () { it('Should display all the blacklisted videos', async function () { - const res = await getBlacklistedVideosList({ url: servers[0].url, token: servers[0].accessToken }) - - expect(res.body.total).to.equal(2) + const body = await command.list() + expect(body.total).to.equal(2) - const blacklistedVideos = res.body.data + const blacklistedVideos = body.data expect(blacklistedVideos).to.be.an('array') expect(blacklistedVideos.length).to.equal(2) @@ -121,79 +120,66 @@ describe('Test video blacklist', function () { }) it('Should display all the blacklisted videos when applying manual type filter', async function () { - const res = await getBlacklistedVideosList({ - url: servers[0].url, - token: servers[0].accessToken, - type: VideoBlacklistType.MANUAL - }) + const body = await command.list({ type: VideoBlacklistType.MANUAL }) + expect(body.total).to.equal(2) - expect(res.body.total).to.equal(2) - - const blacklistedVideos = res.body.data + const blacklistedVideos = body.data expect(blacklistedVideos).to.be.an('array') expect(blacklistedVideos.length).to.equal(2) }) it('Should display nothing when applying automatic type filter', async function () { - const res = await getBlacklistedVideosList({ - url: servers[0].url, - token: servers[0].accessToken, - type: VideoBlacklistType.AUTO_BEFORE_PUBLISHED - }) + const body = await command.list({ type: VideoBlacklistType.AUTO_BEFORE_PUBLISHED }) + expect(body.total).to.equal(0) - expect(res.body.total).to.equal(0) - - const blacklistedVideos = res.body.data + const blacklistedVideos = body.data expect(blacklistedVideos).to.be.an('array') expect(blacklistedVideos.length).to.equal(0) }) it('Should get the correct sort when sorting by descending id', async function () { - const res = await getBlacklistedVideosList({ url: servers[0].url, token: servers[0].accessToken, sort: '-id' }) - expect(res.body.total).to.equal(2) + const body = await command.list({ sort: '-id' }) + expect(body.total).to.equal(2) - const blacklistedVideos = res.body.data + const blacklistedVideos = body.data expect(blacklistedVideos).to.be.an('array') expect(blacklistedVideos.length).to.equal(2) - const result = orderBy(res.body.data, [ 'id' ], [ 'desc' ]) - + const result = orderBy(body.data, [ 'id' ], [ 'desc' ]) expect(blacklistedVideos).to.deep.equal(result) }) it('Should get the correct sort when sorting by descending video name', async function () { - const res = await getBlacklistedVideosList({ url: servers[0].url, token: servers[0].accessToken, sort: '-name' }) - expect(res.body.total).to.equal(2) + const body = await command.list({ sort: '-name' }) + expect(body.total).to.equal(2) - const blacklistedVideos = res.body.data + const blacklistedVideos = body.data expect(blacklistedVideos).to.be.an('array') expect(blacklistedVideos.length).to.equal(2) - const result = orderBy(res.body.data, [ 'name' ], [ 'desc' ]) - + const result = orderBy(body.data, [ 'name' ], [ 'desc' ]) expect(blacklistedVideos).to.deep.equal(result) }) it('Should get the correct sort when sorting by ascending creation date', async function () { - const res = await getBlacklistedVideosList({ url: servers[0].url, token: servers[0].accessToken, sort: 'createdAt' }) - expect(res.body.total).to.equal(2) + const body = await command.list({ sort: 'createdAt' }) + expect(body.total).to.equal(2) - const blacklistedVideos = res.body.data + const blacklistedVideos = body.data expect(blacklistedVideos).to.be.an('array') expect(blacklistedVideos.length).to.equal(2) - const result = orderBy(res.body.data, [ 'createdAt' ]) - + const result = orderBy(body.data, [ 'createdAt' ]) expect(blacklistedVideos).to.deep.equal(result) }) }) describe('When updating blacklisted videos', function () { it('Should change the reason', async function () { - await updateVideoBlacklist(servers[0].url, servers[0].accessToken, videoId, 'my super reason updated') + await command.update({ videoId, reason: 'my super reason updated' }) - const res = await getBlacklistedVideosList({ url: servers[0].url, token: servers[0].accessToken, sort: '-name' }) - const video = res.body.data.find(b => b.video.id === videoId) + const body = await command.list({ sort: '-name' }) + const video = body.data.find(b => b.video.id === videoId) expect(video.reason).to.equal('my super reason updated') }) @@ -228,12 +214,12 @@ describe('Test video blacklist', function () { it('Should remove a video from the blacklist on server 1', async function () { // Get one video in the blacklist - const res = await getBlacklistedVideosList({ url: servers[0].url, token: servers[0].accessToken, sort: '-name' }) - videoToRemove = res.body.data[0] - blacklist = res.body.data.slice(1) + const body = await command.list({ sort: '-name' }) + videoToRemove = body.data[0] + blacklist = body.data.slice(1) // Remove it - await removeVideoFromBlacklist(servers[0].url, servers[0].accessToken, videoToRemove.video.id) + await command.remove({ videoId: videoToRemove.video.id }) }) it('Should have the ex-blacklisted video in videos list on server 1', async function () { @@ -249,10 +235,10 @@ describe('Test video blacklist', function () { }) it('Should not have the ex-blacklisted video in videos blacklist list on server 1', async function () { - const res = await getBlacklistedVideosList({ url: servers[0].url, token: servers[0].accessToken, sort: '-name' }) - expect(res.body.total).to.equal(1) + const body = await command.list({ sort: '-name' }) + expect(body.total).to.equal(1) - const videos = res.body.data + const videos = body.data expect(videos).to.be.an('array') expect(videos.length).to.equal(1) expect(videos).to.deep.equal(blacklist) @@ -281,7 +267,7 @@ describe('Test video blacklist', function () { it('Should blacklist video 3 and keep it federated', async function () { this.timeout(10000) - await addVideoToBlacklist(servers[0].url, servers[0].accessToken, video3UUID, 'super reason', false) + await command.add({ videoId: video3UUID, reason: 'super reason', unfederate: false }) await waitJobs(servers) @@ -299,7 +285,7 @@ describe('Test video blacklist', function () { it('Should unfederate the video', async function () { this.timeout(10000) - await addVideoToBlacklist(servers[0].url, servers[0].accessToken, video4UUID, 'super reason', true) + await command.add({ videoId: video4UUID, reason: 'super reason', unfederate: true }) await waitJobs(servers) @@ -323,9 +309,9 @@ describe('Test video blacklist', function () { }) it('Should have the correct video blacklist unfederate attribute', async function () { - const res = await getBlacklistedVideosList({ url: servers[0].url, token: servers[0].accessToken, sort: 'createdAt' }) + const body = await command.list({ sort: 'createdAt' }) - const blacklistedVideos: VideoBlacklist[] = res.body.data + const blacklistedVideos = body.data const video3Blacklisted = blacklistedVideos.find(b => b.video.uuid === video3UUID) const video4Blacklisted = blacklistedVideos.find(b => b.video.uuid === video4UUID) @@ -336,7 +322,7 @@ describe('Test video blacklist', function () { it('Should remove the video from blacklist and refederate the video', async function () { this.timeout(10000) - await removeVideoFromBlacklist(servers[0].url, servers[0].accessToken, video4UUID) + await command.remove({ videoId: video4UUID }) await waitJobs(servers) @@ -407,14 +393,9 @@ describe('Test video blacklist', function () { it('Should auto blacklist a video on upload', async function () { await uploadVideo(servers[0].url, userWithoutFlag, { name: 'blacklisted' }) - const res = await getBlacklistedVideosList({ - url: servers[0].url, - token: servers[0].accessToken, - type: VideoBlacklistType.AUTO_BEFORE_PUBLISHED - }) - - expect(res.body.total).to.equal(1) - expect(res.body.data[0].video.name).to.equal('blacklisted') + const body = await command.list({ type: VideoBlacklistType.AUTO_BEFORE_PUBLISHED }) + expect(body.total).to.equal(1) + expect(body.data[0].video.name).to.equal('blacklisted') }) it('Should auto blacklist a video on URL import', async function () { @@ -427,15 +408,9 @@ describe('Test video blacklist', function () { } await importVideo(servers[0].url, userWithoutFlag, attributes) - const res = await getBlacklistedVideosList({ - url: servers[0].url, - token: servers[0].accessToken, - sort: 'createdAt', - type: VideoBlacklistType.AUTO_BEFORE_PUBLISHED - }) - - expect(res.body.total).to.equal(2) - expect(res.body.data[1].video.name).to.equal('URL import') + const body = await command.list({ sort: 'createdAt', type: VideoBlacklistType.AUTO_BEFORE_PUBLISHED }) + expect(body.total).to.equal(2) + expect(body.data[1].video.name).to.equal('URL import') }) it('Should auto blacklist a video on torrent import', async function () { @@ -446,27 +421,16 @@ describe('Test video blacklist', function () { } await importVideo(servers[0].url, userWithoutFlag, attributes) - const res = await getBlacklistedVideosList({ - url: servers[0].url, - token: servers[0].accessToken, - sort: 'createdAt', - type: VideoBlacklistType.AUTO_BEFORE_PUBLISHED - }) - - expect(res.body.total).to.equal(3) - expect(res.body.data[2].video.name).to.equal('Torrent import') + const body = await command.list({ sort: 'createdAt', type: VideoBlacklistType.AUTO_BEFORE_PUBLISHED }) + expect(body.total).to.equal(3) + expect(body.data[2].video.name).to.equal('Torrent import') }) it('Should not auto blacklist a video on upload if the user has the bypass blacklist flag', async function () { await uploadVideo(servers[0].url, userWithFlag, { name: 'not blacklisted' }) - const res = await getBlacklistedVideosList({ - url: servers[0].url, - token: servers[0].accessToken, - type: VideoBlacklistType.AUTO_BEFORE_PUBLISHED - }) - - expect(res.body.total).to.equal(3) + const body = await command.list({ type: VideoBlacklistType.AUTO_BEFORE_PUBLISHED }) + expect(body.total).to.equal(3) }) }) diff --git a/server/tests/api/notifications/moderation-notifications.ts b/server/tests/api/notifications/moderation-notifications.ts index 605b41947..52ade0548 100644 --- a/server/tests/api/notifications/moderation-notifications.ts +++ b/server/tests/api/notifications/moderation-notifications.ts @@ -4,7 +4,6 @@ import 'mocha' import { buildUUID } from '@server/helpers/uuid' import { addVideoCommentThread, - addVideoToBlacklist, checkAbuseStateChange, checkAutoInstanceFollowing, CheckerBaseParams, @@ -28,7 +27,6 @@ import { MockSmtpServer, prepareNotificationsTest, registerUser, - removeVideoFromBlacklist, ServerInfo, uploadVideo, wait, @@ -297,7 +295,7 @@ describe('Test moderation notifications', function () { const resVideo = await uploadVideo(servers[0].url, userAccessToken, { name }) const uuid = resVideo.body.video.uuid - await addVideoToBlacklist(servers[0].url, servers[0].accessToken, uuid) + await servers[0].blacklistCommand.add({ videoId: uuid }) await waitJobs(servers) await checkNewBlacklistOnMyVideo(baseParams, uuid, name, 'blacklist') @@ -310,10 +308,10 @@ describe('Test moderation notifications', function () { const resVideo = await uploadVideo(servers[0].url, userAccessToken, { name }) const uuid = resVideo.body.video.uuid - await addVideoToBlacklist(servers[0].url, servers[0].accessToken, uuid) + await servers[0].blacklistCommand.add({ videoId: uuid }) await waitJobs(servers) - await removeVideoFromBlacklist(servers[0].url, servers[0].accessToken, uuid) + await servers[0].blacklistCommand.remove({ videoId: uuid }) await waitJobs(servers) await wait(500) @@ -517,7 +515,7 @@ describe('Test moderation notifications', function () { it('Should send video published and unblacklist after video unblacklisted', async function () { this.timeout(40000) - await removeVideoFromBlacklist(servers[0].url, servers[0].accessToken, videoUUID) + await servers[0].blacklistCommand.remove({ videoId: videoUUID }) await waitJobs(servers) @@ -554,7 +552,7 @@ describe('Test moderation notifications', function () { const resVideo = await uploadVideo(servers[0].url, userAccessToken, data) const uuid = resVideo.body.video.uuid - await removeVideoFromBlacklist(servers[0].url, servers[0].accessToken, uuid) + await servers[0].blacklistCommand.remove({ videoId: uuid }) await waitJobs(servers) await checkNewBlacklistOnMyVideo(userBaseParams, uuid, name, 'unblacklist') diff --git a/server/tests/api/server/email.ts b/server/tests/api/server/email.ts index 85844ae9d..5d997713b 100644 --- a/server/tests/api/server/email.ts +++ b/server/tests/api/server/email.ts @@ -4,14 +4,12 @@ import 'mocha' import * as chai from 'chai' import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' import { - addVideoToBlacklist, askResetPassword, askSendVerifyEmail, blockUser, cleanupTests, createUser, flushAndRunServer, - removeVideoFromBlacklist, resetPassword, ServerInfo, setAccessTokensToServers, @@ -248,7 +246,7 @@ describe('Test emails', function () { this.timeout(10000) const reason = 'my super reason' - await addVideoToBlacklist(server.url, server.accessToken, videoUserUUID, reason) + await server.blacklistCommand.add({ videoId: videoUserUUID, reason }) await waitJobs(server) expect(emails).to.have.lengthOf(6) @@ -266,7 +264,7 @@ describe('Test emails', function () { it('Should send the notification email', async function () { this.timeout(10000) - await removeVideoFromBlacklist(server.url, server.accessToken, videoUserUUID) + await server.blacklistCommand.remove({ videoId: videoUserUUID }) await waitJobs(server) expect(emails).to.have.lengthOf(7) diff --git a/server/tests/api/users/users.ts b/server/tests/api/users/users.ts index 3beea5d50..4b9056306 100644 --- a/server/tests/api/users/users.ts +++ b/server/tests/api/users/users.ts @@ -11,7 +11,6 @@ import { createUser, deleteMe, flushAndRunServer, - getBlacklistedVideosList, getMyUserInformation, getMyUserVideoQuotaUsed, getMyUserVideoRating, @@ -808,7 +807,7 @@ describe('Test users', function () { describe('Video blacklists', function () { it('Should be able to list video blacklist by a moderator', async function () { - await getBlacklistedVideosList({ url: server.url, token: accessTokenUser }) + await server.blacklistCommand.list({ token: accessTokenUser }) }) }) diff --git a/server/tests/api/videos/video-playlists.ts b/server/tests/api/videos/video-playlists.ts index 90189721a..069450453 100644 --- a/server/tests/api/videos/video-playlists.ts +++ b/server/tests/api/videos/video-playlists.ts @@ -6,7 +6,6 @@ import { HttpStatusCode } from '@shared/core-utils' import { addVideoChannel, addVideoInPlaylist, - addVideoToBlacklist, checkPlaylistFilesWereRemoved, cleanupTests, createUser, @@ -28,7 +27,6 @@ import { getVideoPlaylistsList, getVideoPlaylistWithToken, removeUser, - removeVideoFromBlacklist, removeVideoFromPlaylist, reorderVideosPlaylist, ServerInfo, @@ -728,7 +726,7 @@ describe('Test video playlists', function () { const position = 1 { - await addVideoToBlacklist(servers[0].url, servers[0].accessToken, video1, 'reason', true) + await servers[0].blacklistCommand.add({ videoId: video1, reason: 'reason', unfederate: true }) await waitJobs(servers) await checkPlaylistElementType(groupUser1, playlistServer1UUID2, VideoPlaylistElementType.REGULAR, position, name, 3) @@ -738,7 +736,7 @@ describe('Test video playlists', function () { } { - await removeVideoFromBlacklist(servers[0].url, servers[0].accessToken, video1) + await servers[0].blacklistCommand.remove({ videoId: video1 }) await waitJobs(servers) await checkPlaylistElementType(groupUser1, playlistServer1UUID2, VideoPlaylistElementType.REGULAR, position, name, 3) diff --git a/server/tests/external-plugins/auto-block-videos.ts b/server/tests/external-plugins/auto-block-videos.ts index 6baf37566..6659b6f39 100644 --- a/server/tests/external-plugins/auto-block-videos.ts +++ b/server/tests/external-plugins/auto-block-videos.ts @@ -2,13 +2,11 @@ import 'mocha' import { expect } from 'chai' -import { Video, VideoBlacklist } from '@shared/models' +import { Video } from '@shared/models' import { doubleFollow, - getBlacklistedVideosList, getVideosList, MockBlocklist, - removeVideoFromBlacklist, setAccessTokensToServers, uploadVideoAndGetId, wait @@ -97,10 +95,9 @@ describe('Official plugin auto-block videos', function () { }) it('Should have video in blacklists', async function () { - const res = await getBlacklistedVideosList({ url: servers[0].url, token: servers[0].accessToken }) - - const videoBlacklists = res.body.data as VideoBlacklist[] + const body = await servers[0].blacklistCommand.list() + const videoBlacklists = body.data expect(videoBlacklists).to.have.lengthOf(1) expect(videoBlacklists[0].reason).to.contains('Automatically blocked from auto block plugin') expect(videoBlacklists[0].video.name).to.equal(server2Videos[0].name) @@ -163,7 +160,7 @@ describe('Official plugin auto-block videos', function () { await check(servers[0], video.uuid, false) - await removeVideoFromBlacklist(servers[0].url, servers[0].accessToken, video.uuid) + await servers[0].blacklistCommand.remove({ videoId: video.uuid }) await check(servers[0], video.uuid, true) diff --git a/shared/extra-utils/server/servers.ts b/shared/extra-utils/server/servers.ts index cb2a8814b..a4432902f 100644 --- a/shared/extra-utils/server/servers.ts +++ b/shared/extra-utils/server/servers.ts @@ -18,7 +18,7 @@ import { makeGetRequest } from '../requests/requests' import { SearchCommand } from '../search' import { SocketIOCommand } from '../socket' import { AccountsCommand, BlocklistCommand, SubscriptionsCommand } from '../users' -import { LiveCommand, ServicesCommand } from '../videos' +import { LiveCommand, ServicesCommand, BlacklistCommand } from '../videos' import { ConfigCommand } from './config-command' import { ContactFormCommand } from './contact-form-command' import { DebugCommand } from './debug-command' @@ -102,6 +102,7 @@ interface ServerInfo { subscriptionsCommand?: SubscriptionsCommand liveCommand?: LiveCommand servicesCommand?: ServicesCommand + blacklistCommand?: BlacklistCommand } function parallelTests () { @@ -329,6 +330,7 @@ async function runServer (server: ServerInfo, configOverrideArg?: any, args = [] server.subscriptionsCommand = new SubscriptionsCommand(server) server.liveCommand = new LiveCommand(server) server.servicesCommand = new ServicesCommand(server) + server.blacklistCommand = new BlacklistCommand(server) res(server) }) diff --git a/shared/extra-utils/videos/blacklist-command.ts b/shared/extra-utils/videos/blacklist-command.ts new file mode 100644 index 000000000..fdae6b469 --- /dev/null +++ b/shared/extra-utils/videos/blacklist-command.ts @@ -0,0 +1,77 @@ + +import { ResultList } from '@shared/models' +import { HttpStatusCode } from '../../core-utils/miscs/http-error-codes' +import { VideoBlacklist, VideoBlacklistType } from '../../models/videos' +import { AbstractCommand, OverrideCommandOptions } from '../shared' + +export class BlacklistCommand extends AbstractCommand { + + add (options: OverrideCommandOptions & { + videoId: number | string + reason?: string + unfederate?: boolean + }) { + const { videoId, reason, unfederate } = options + const path = '/api/v1/videos/' + videoId + '/blacklist' + + return this.postBodyRequest({ + ...options, + + path, + fields: { reason, unfederate }, + implicitToken: true, + defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 + }) + } + + update (options: OverrideCommandOptions & { + videoId: number | string + reason?: string + }) { + const { videoId, reason } = options + const path = '/api/v1/videos/' + videoId + '/blacklist' + + return this.putBodyRequest({ + ...options, + + path, + fields: { reason }, + implicitToken: true, + defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 + }) + } + + remove (options: OverrideCommandOptions & { + videoId: number | string + }) { + const { videoId } = options + const path = '/api/v1/videos/' + videoId + '/blacklist' + + return this.deleteRequest({ + ...options, + + path, + implicitToken: true, + defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 + }) + } + + list (options: OverrideCommandOptions & { + sort?: string + type?: VideoBlacklistType + } = {}) { + const { sort, type } = options + const path = '/api/v1/videos/blacklist/' + + const query = { sort, type } + + return this.getRequestBody>({ + ...options, + + path, + query, + implicitToken: true, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } +} diff --git a/shared/extra-utils/videos/index.ts b/shared/extra-utils/videos/index.ts index fe5dc6655..67f5faf54 100644 --- a/shared/extra-utils/videos/index.ts +++ b/shared/extra-utils/videos/index.ts @@ -1,7 +1,7 @@ +export * from './blacklist-command' export * from './live-command' export * from './live' export * from './services-command' -export * from './video-blacklist' export * from './video-captions' export * from './video-change-ownership' export * from './video-channels' diff --git a/shared/extra-utils/videos/video-blacklist.ts b/shared/extra-utils/videos/video-blacklist.ts deleted file mode 100644 index aa1548537..000000000 --- a/shared/extra-utils/videos/video-blacklist.ts +++ /dev/null @@ -1,79 +0,0 @@ -import * as request from 'supertest' -import { VideoBlacklistType } from '../../models/videos' -import { makeGetRequest } from '..' -import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' - -function addVideoToBlacklist ( - url: string, - token: string, - videoId: number | string, - reason?: string, - unfederate?: boolean, - specialStatus = HttpStatusCode.NO_CONTENT_204 -) { - const path = '/api/v1/videos/' + videoId + '/blacklist' - - return request(url) - .post(path) - .send({ reason, unfederate }) - .set('Accept', 'application/json') - .set('Authorization', 'Bearer ' + token) - .expect(specialStatus) -} - -function updateVideoBlacklist ( - url: string, - token: string, - videoId: number, - reason?: string, - specialStatus = HttpStatusCode.NO_CONTENT_204 -) { - const path = '/api/v1/videos/' + videoId + '/blacklist' - - return request(url) - .put(path) - .send({ reason }) - .set('Accept', 'application/json') - .set('Authorization', 'Bearer ' + token) - .expect(specialStatus) -} - -function removeVideoFromBlacklist (url: string, token: string, videoId: number | string, specialStatus = HttpStatusCode.NO_CONTENT_204) { - const path = '/api/v1/videos/' + videoId + '/blacklist' - - return request(url) - .delete(path) - .set('Accept', 'application/json') - .set('Authorization', 'Bearer ' + token) - .expect(specialStatus) -} - -function getBlacklistedVideosList (parameters: { - url: string - token: string - sort?: string - type?: VideoBlacklistType - specialStatus?: HttpStatusCode -}) { - const { url, token, sort, type, specialStatus = HttpStatusCode.OK_200 } = parameters - const path = '/api/v1/videos/blacklist/' - - const query = { sort, type } - - return makeGetRequest({ - url, - path, - query, - token, - statusCodeExpected: specialStatus - }) -} - -// --------------------------------------------------------------------------- - -export { - addVideoToBlacklist, - removeVideoFromBlacklist, - getBlacklistedVideosList, - updateVideoBlacklist -} -- cgit v1.2.3 From a2470c9f4bfc7f49f4b94de935bacdd53fd54f29 Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Thu, 8 Jul 2021 11:49:38 +0200 Subject: Introduce captions command --- scripts/benchmark.ts | 5 +- server/tests/api/check-params/video-captions.ts | 11 ++-- server/tests/api/search/search-videos.ts | 9 +-- server/tests/api/server/follows.ts | 16 ++--- server/tests/api/videos/video-captions.ts | 77 ++++++++++--------------- server/tests/api/videos/video-imports.ts | 33 +++++------ shared/extra-utils/server/servers.ts | 4 +- shared/extra-utils/videos/captions-command.ts | 66 +++++++++++++++++++++ shared/extra-utils/videos/captions.ts | 17 ++++++ shared/extra-utils/videos/index.ts | 3 +- shared/extra-utils/videos/video-captions.ts | 72 ----------------------- 11 files changed, 149 insertions(+), 164 deletions(-) create mode 100644 shared/extra-utils/videos/captions-command.ts create mode 100644 shared/extra-utils/videos/captions.ts delete mode 100644 shared/extra-utils/videos/video-captions.ts diff --git a/scripts/benchmark.ts b/scripts/benchmark.ts index 0cadb36d9..fcfc67bf7 100644 --- a/scripts/benchmark.ts +++ b/scripts/benchmark.ts @@ -5,7 +5,6 @@ import * as autocannon from 'autocannon' import { addVideoCommentReply, addVideoCommentThread, - createVideoCaption, flushAndRunServer, getVideosList, killallServers, @@ -244,9 +243,7 @@ async function prepare () { } for (const caption of [ 'ar', 'fr', 'en', 'zh' ]) { - await createVideoCaption({ - url: server.url, - accessToken: server.accessToken, + await server.captionsCommand.createVideoCaption({ language: caption, videoId: video.id, fixture: 'subtitle-good2.vtt' diff --git a/server/tests/api/check-params/video-captions.ts b/server/tests/api/check-params/video-captions.ts index c0595c04d..baab0f276 100644 --- a/server/tests/api/check-params/video-captions.ts +++ b/server/tests/api/check-params/video-captions.ts @@ -1,8 +1,7 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ import 'mocha' -import { VideoCreateResult } from '@shared/models' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '@shared/core-utils' import { buildAbsoluteFixturePath, cleanupTests, @@ -15,8 +14,8 @@ import { setAccessTokensToServers, uploadVideo, userLogin -} from '../../../../shared/extra-utils' -import { createVideoCaption } from '../../../../shared/extra-utils/videos/video-captions' +} from '@shared/extra-utils' +import { VideoCreateResult } from '@shared/models' describe('Test video captions API validator', function () { const path = '/api/v1/videos/' @@ -159,9 +158,7 @@ describe('Test video captions API validator', function () { // }) it('Should succeed with a valid captionfile extension and octet-stream mime type', async function () { - await createVideoCaption({ - url: server.url, - accessToken: server.accessToken, + await server.captionsCommand.createVideoCaption({ language: 'zh', videoId: video.uuid, fixture: 'subtitle-good.srt', diff --git a/server/tests/api/search/search-videos.ts b/server/tests/api/search/search-videos.ts index a0375fbf0..513538917 100644 --- a/server/tests/api/search/search-videos.ts +++ b/server/tests/api/search/search-videos.ts @@ -4,7 +4,6 @@ import 'mocha' import * as chai from 'chai' import { cleanupTests, - createVideoCaption, flushAndRunServer, immutableAssign, SearchCommand, @@ -54,18 +53,14 @@ describe('Test videos search', function () { const videoId = res.body.video.id videoUUID = res.body.video.uuid - await createVideoCaption({ - url: server.url, - accessToken: server.accessToken, + await server.captionsCommand.createVideoCaption({ language: 'en', videoId, fixture: 'subtitle-good2.vtt', mimeType: 'application/octet-stream' }) - await createVideoCaption({ - url: server.url, - accessToken: server.accessToken, + await server.captionsCommand.createVideoCaption({ language: 'aa', videoId, fixture: 'subtitle-good2.vtt', diff --git a/server/tests/api/server/follows.ts b/server/tests/api/server/follows.ts index 466932d63..520442c6e 100644 --- a/server/tests/api/server/follows.ts +++ b/server/tests/api/server/follows.ts @@ -8,7 +8,6 @@ import { cleanupTests, completeVideoCheck, createUser, - createVideoCaption, dateIsValid, deleteVideoComment, expectAccountFollows, @@ -17,7 +16,6 @@ import { getVideoCommentThreads, getVideosList, getVideoThreadComments, - listVideoCaptions, rateVideo, ServerInfo, setAccessTokensToServers, @@ -26,7 +24,7 @@ import { userLogin, waitJobs } from '@shared/extra-utils' -import { Video, VideoCaption, VideoComment, VideoCommentThreadTree, VideoPrivacy } from '@shared/models' +import { Video, VideoComment, VideoCommentThreadTree, VideoPrivacy } from '@shared/models' const expect = chai.expect @@ -385,9 +383,7 @@ describe('Test follows', function () { } { - await createVideoCaption({ - url: servers[2].url, - accessToken: servers[2].accessToken, + await servers[2].captionsCommand.createVideoCaption({ language: 'ar', videoId: video4.id, fixture: 'subtitle-good2.vtt' @@ -543,11 +539,11 @@ describe('Test follows', function () { }) it('Should have propagated captions', async function () { - const res = await listVideoCaptions(servers[0].url, video4.id) - expect(res.body.total).to.equal(1) - expect(res.body.data).to.have.lengthOf(1) + const body = await servers[0].captionsCommand.listVideoCaptions({ videoId: video4.id }) + expect(body.total).to.equal(1) + expect(body.data).to.have.lengthOf(1) - const caption1: VideoCaption = res.body.data[0] + const caption1 = body.data[0] expect(caption1.language.id).to.equal('ar') expect(caption1.language.label).to.equal('Arabic') expect(caption1.captionPath).to.match(new RegExp('^/lazy-static/video-captions/.+-ar.vtt$')) diff --git a/server/tests/api/videos/video-captions.ts b/server/tests/api/videos/video-captions.ts index 14ecedfa6..83ee809b8 100644 --- a/server/tests/api/videos/video-captions.ts +++ b/server/tests/api/videos/video-captions.ts @@ -1,25 +1,20 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ -import * as chai from 'chai' import 'mocha' +import * as chai from 'chai' import { checkVideoFilesWereRemoved, cleanupTests, doubleFollow, flushAndRunMultipleServers, removeVideo, + ServerInfo, + setAccessTokensToServers, + testCaptionFile, uploadVideo, - wait -} from '../../../../shared/extra-utils' -import { ServerInfo, setAccessTokensToServers } from '../../../../shared/extra-utils/index' -import { waitJobs } from '../../../../shared/extra-utils/server/jobs' -import { - createVideoCaption, - deleteVideoCaption, - listVideoCaptions, - testCaptionFile -} from '../../../../shared/extra-utils/videos/video-captions' -import { VideoCaption } from '../../../../shared/models/videos/caption/video-caption.model' + wait, + waitJobs +} from '@shared/extra-utils' const expect = chai.expect @@ -47,26 +42,22 @@ describe('Test video captions', function () { it('Should list the captions and return an empty list', async function () { for (const server of servers) { - const res = await listVideoCaptions(server.url, videoUUID) - expect(res.body.total).to.equal(0) - expect(res.body.data).to.have.lengthOf(0) + const body = await server.captionsCommand.listVideoCaptions({ videoId: videoUUID }) + expect(body.total).to.equal(0) + expect(body.data).to.have.lengthOf(0) } }) it('Should create two new captions', async function () { this.timeout(30000) - await createVideoCaption({ - url: servers[0].url, - accessToken: servers[0].accessToken, + await servers[0].captionsCommand.createVideoCaption({ language: 'ar', videoId: videoUUID, fixture: 'subtitle-good1.vtt' }) - await createVideoCaption({ - url: servers[0].url, - accessToken: servers[0].accessToken, + await servers[0].captionsCommand.createVideoCaption({ language: 'zh', videoId: videoUUID, fixture: 'subtitle-good2.vtt', @@ -78,17 +69,17 @@ describe('Test video captions', function () { it('Should list these uploaded captions', async function () { for (const server of servers) { - const res = await listVideoCaptions(server.url, videoUUID) - expect(res.body.total).to.equal(2) - expect(res.body.data).to.have.lengthOf(2) + const body = await server.captionsCommand.listVideoCaptions({ videoId: videoUUID }) + expect(body.total).to.equal(2) + expect(body.data).to.have.lengthOf(2) - const caption1: VideoCaption = res.body.data[0] + const caption1 = body.data[0] expect(caption1.language.id).to.equal('ar') expect(caption1.language.label).to.equal('Arabic') expect(caption1.captionPath).to.match(new RegExp('^/lazy-static/video-captions/' + uuidRegex + '-ar.vtt$')) await testCaptionFile(server.url, caption1.captionPath, 'Subtitle good 1.') - const caption2: VideoCaption = res.body.data[1] + const caption2 = body.data[1] expect(caption2.language.id).to.equal('zh') expect(caption2.language.label).to.equal('Chinese') expect(caption2.captionPath).to.match(new RegExp('^/lazy-static/video-captions/' + uuidRegex + '-zh.vtt$')) @@ -99,9 +90,7 @@ describe('Test video captions', function () { it('Should replace an existing caption', async function () { this.timeout(30000) - await createVideoCaption({ - url: servers[0].url, - accessToken: servers[0].accessToken, + await servers[0].captionsCommand.createVideoCaption({ language: 'ar', videoId: videoUUID, fixture: 'subtitle-good2.vtt' @@ -112,11 +101,11 @@ describe('Test video captions', function () { it('Should have this caption updated', async function () { for (const server of servers) { - const res = await listVideoCaptions(server.url, videoUUID) - expect(res.body.total).to.equal(2) - expect(res.body.data).to.have.lengthOf(2) + const body = await server.captionsCommand.listVideoCaptions({ videoId: videoUUID }) + expect(body.total).to.equal(2) + expect(body.data).to.have.lengthOf(2) - const caption1: VideoCaption = res.body.data[0] + const caption1 = body.data[0] expect(caption1.language.id).to.equal('ar') expect(caption1.language.label).to.equal('Arabic') expect(caption1.captionPath).to.match(new RegExp('^/lazy-static/video-captions/' + uuidRegex + '-ar.vtt$')) @@ -127,9 +116,7 @@ describe('Test video captions', function () { it('Should replace an existing caption with a srt file and convert it', async function () { this.timeout(30000) - await createVideoCaption({ - url: servers[0].url, - accessToken: servers[0].accessToken, + await servers[0].captionsCommand.createVideoCaption({ language: 'ar', videoId: videoUUID, fixture: 'subtitle-good.srt' @@ -143,11 +130,11 @@ describe('Test video captions', function () { it('Should have this caption updated and converted', async function () { for (const server of servers) { - const res = await listVideoCaptions(server.url, videoUUID) - expect(res.body.total).to.equal(2) - expect(res.body.data).to.have.lengthOf(2) + const body = await server.captionsCommand.listVideoCaptions({ videoId: videoUUID }) + expect(body.total).to.equal(2) + expect(body.data).to.have.lengthOf(2) - const caption1: VideoCaption = res.body.data[0] + const caption1 = body.data[0] expect(caption1.language.id).to.equal('ar') expect(caption1.language.label).to.equal('Arabic') expect(caption1.captionPath).to.match(new RegExp('^/lazy-static/video-captions/' + uuidRegex + '-ar.vtt$')) @@ -172,18 +159,18 @@ describe('Test video captions', function () { it('Should remove one caption', async function () { this.timeout(30000) - await deleteVideoCaption(servers[0].url, servers[0].accessToken, videoUUID, 'ar') + await servers[0].captionsCommand.deleteVideoCaption({ videoId: videoUUID, language: 'ar' }) await waitJobs(servers) }) it('Should only list the caption that was not deleted', async function () { for (const server of servers) { - const res = await listVideoCaptions(server.url, videoUUID) - expect(res.body.total).to.equal(1) - expect(res.body.data).to.have.lengthOf(1) + const body = await server.captionsCommand.listVideoCaptions({ videoId: videoUUID }) + expect(body.total).to.equal(1) + expect(body.data).to.have.lengthOf(1) - const caption: VideoCaption = res.body.data[0] + const caption = body.data[0] expect(caption.language.id).to.equal('zh') expect(caption.language.label).to.equal('Chinese') diff --git a/server/tests/api/videos/video-imports.ts b/server/tests/api/videos/video-imports.ts index a4a9132b4..14aed604f 100644 --- a/server/tests/api/videos/video-imports.ts +++ b/server/tests/api/videos/video-imports.ts @@ -11,7 +11,6 @@ import { getVideo, getVideosList, immutableAssign, - listVideoCaptions, ServerInfo, setAccessTokensToServers, testCaptionFile @@ -25,7 +24,7 @@ import { getYoutubeVideoUrl, importVideo } from '../../../../shared/extra-utils/videos/video-imports' -import { VideoCaption, VideoDetails, VideoImport, VideoPrivacy, VideoResolution } from '../../../../shared/models/videos' +import { VideoDetails, VideoImport, VideoPrivacy, VideoResolution } from '../../../../shared/models/videos' const expect = chai.expect @@ -36,8 +35,8 @@ describe('Test video imports', function () { if (areHttpImportTestsDisabled()) return - async function checkVideosServer1 (url: string, idHttp: string, idMagnet: string, idTorrent: string) { - const resHttp = await getVideo(url, idHttp) + async function checkVideosServer1 (server: ServerInfo, idHttp: string, idMagnet: string, idTorrent: string) { + const resHttp = await getVideo(server.url, idHttp) const videoHttp: VideoDetails = resHttp.body expect(videoHttp.name).to.equal('small video - youtube') @@ -55,9 +54,9 @@ describe('Test video imports', function () { expect(originallyPublishedAt.getMonth()).to.equal(0) expect(originallyPublishedAt.getFullYear()).to.equal(2019) - const resMagnet = await getVideo(url, idMagnet) + const resMagnet = await getVideo(server.url, idMagnet) const videoMagnet: VideoDetails = resMagnet.body - const resTorrent = await getVideo(url, idTorrent) + const resTorrent = await getVideo(server.url, idTorrent) const videoTorrent: VideoDetails = resTorrent.body for (const video of [ videoMagnet, videoTorrent ]) { @@ -73,12 +72,12 @@ describe('Test video imports', function () { expect(videoTorrent.name).to.contain('你好 世界 720p.mp4') expect(videoMagnet.name).to.contain('super peertube2 video') - const resCaptions = await listVideoCaptions(url, idHttp) - expect(resCaptions.body.total).to.equal(2) + const bodyCaptions = await server.captionsCommand.listVideoCaptions({ videoId: idHttp }) + expect(bodyCaptions.total).to.equal(2) } - async function checkVideoServer2 (url: string, id: number | string) { - const res = await getVideo(url, id) + async function checkVideoServer2 (server: ServerInfo, id: number | string) { + const res = await getVideo(server.url, id) const video: VideoDetails = res.body expect(video.name).to.equal('my super name') @@ -91,8 +90,8 @@ describe('Test video imports', function () { expect(video.files).to.have.lengthOf(1) - const resCaptions = await listVideoCaptions(url, id) - expect(resCaptions.body.total).to.equal(2) + const bodyCaptions = await server.captionsCommand.listVideoCaptions({ videoId: id }) + expect(bodyCaptions.total).to.equal(2) } before(async function () { @@ -135,8 +134,8 @@ describe('Test video imports', function () { await testImage(servers[0].url, 'video_import_thumbnail', res.body.video.thumbnailPath) await testImage(servers[0].url, 'video_import_preview', res.body.video.previewPath) - const resCaptions = await listVideoCaptions(servers[0].url, res.body.video.id) - const videoCaptions: VideoCaption[] = resCaptions.body.data + const bodyCaptions = await servers[0].captionsCommand.listVideoCaptions({ videoId: res.body.video.id }) + const videoCaptions = bodyCaptions.data expect(videoCaptions).to.have.lengthOf(2) const enCaption = videoCaptions.find(caption => caption.language.id === 'en') @@ -241,7 +240,7 @@ Ajouter un sous-titre est vraiment facile`) expect(res.body.data).to.have.lengthOf(3) const [ videoHttp, videoMagnet, videoTorrent ] = res.body.data - await checkVideosServer1(server.url, videoHttp.uuid, videoMagnet.uuid, videoTorrent.uuid) + await checkVideosServer1(server, videoHttp.uuid, videoMagnet.uuid, videoTorrent.uuid) } }) @@ -273,10 +272,10 @@ Ajouter un sous-titre est vraiment facile`) expect(res.body.total).to.equal(4) expect(res.body.data).to.have.lengthOf(4) - await checkVideoServer2(server.url, res.body.data[0].uuid) + await checkVideoServer2(server, res.body.data[0].uuid) const [ , videoHttp, videoMagnet, videoTorrent ] = res.body.data - await checkVideosServer1(server.url, videoHttp.uuid, videoMagnet.uuid, videoTorrent.uuid) + await checkVideosServer1(server, videoHttp.uuid, videoMagnet.uuid, videoTorrent.uuid) } }) diff --git a/shared/extra-utils/server/servers.ts b/shared/extra-utils/server/servers.ts index a4432902f..170360341 100644 --- a/shared/extra-utils/server/servers.ts +++ b/shared/extra-utils/server/servers.ts @@ -18,7 +18,7 @@ import { makeGetRequest } from '../requests/requests' import { SearchCommand } from '../search' import { SocketIOCommand } from '../socket' import { AccountsCommand, BlocklistCommand, SubscriptionsCommand } from '../users' -import { LiveCommand, ServicesCommand, BlacklistCommand } from '../videos' +import { LiveCommand, ServicesCommand, BlacklistCommand, CaptionsCommand } from '../videos' import { ConfigCommand } from './config-command' import { ContactFormCommand } from './contact-form-command' import { DebugCommand } from './debug-command' @@ -103,6 +103,7 @@ interface ServerInfo { liveCommand?: LiveCommand servicesCommand?: ServicesCommand blacklistCommand?: BlacklistCommand + captionsCommand?: CaptionsCommand } function parallelTests () { @@ -331,6 +332,7 @@ async function runServer (server: ServerInfo, configOverrideArg?: any, args = [] server.liveCommand = new LiveCommand(server) server.servicesCommand = new ServicesCommand(server) server.blacklistCommand = new BlacklistCommand(server) + server.captionsCommand = new CaptionsCommand(server) res(server) }) diff --git a/shared/extra-utils/videos/captions-command.ts b/shared/extra-utils/videos/captions-command.ts new file mode 100644 index 000000000..908b6dae6 --- /dev/null +++ b/shared/extra-utils/videos/captions-command.ts @@ -0,0 +1,66 @@ +import { ResultList, VideoCaption } from '@shared/models' +import { HttpStatusCode } from '../../core-utils/miscs/http-error-codes' +import { buildAbsoluteFixturePath } from '../miscs/miscs' +import { AbstractCommand, OverrideCommandOptions } from '../shared' + +export class CaptionsCommand extends AbstractCommand { + + createVideoCaption (options: OverrideCommandOptions & { + videoId: string | number + language: string + fixture: string + mimeType?: string + }) { + const { videoId, language, fixture, mimeType } = options + + const path = '/api/v1/videos/' + videoId + '/captions/' + language + + const captionfile = buildAbsoluteFixturePath(fixture) + const captionfileAttach = mimeType + ? [ captionfile, { contentType: mimeType } ] + : captionfile + + return this.putUploadRequest({ + ...options, + + path, + fields: {}, + attaches: { + captionfile: captionfileAttach + }, + implicitToken: true, + defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 + }) + } + + listVideoCaptions (options: OverrideCommandOptions & { + videoId: string | number + }) { + const { videoId } = options + const path = '/api/v1/videos/' + videoId + '/captions' + + return this.getRequestBody>({ + ...options, + + path, + implicitToken: false, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } + + deleteVideoCaption (options: OverrideCommandOptions & { + videoId: string | number + language: string + }) { + const { videoId, language } = options + const path = '/api/v1/videos/' + videoId + '/captions/' + language + + return this.deleteRequest({ + ...options, + + path, + implicitToken: true, + defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 + }) + } +} diff --git a/shared/extra-utils/videos/captions.ts b/shared/extra-utils/videos/captions.ts new file mode 100644 index 000000000..2246bd133 --- /dev/null +++ b/shared/extra-utils/videos/captions.ts @@ -0,0 +1,17 @@ +import { expect } from 'chai' +import * as request from 'supertest' +import { HttpStatusCode } from '../../core-utils/miscs/http-error-codes' + +async function testCaptionFile (url: string, captionPath: string, containsString: string) { + const res = await request(url) + .get(captionPath) + .expect(HttpStatusCode.OK_200) + + expect(res.text).to.contain(containsString) +} + +// --------------------------------------------------------------------------- + +export { + testCaptionFile +} diff --git a/shared/extra-utils/videos/index.ts b/shared/extra-utils/videos/index.ts index 67f5faf54..03b4756d5 100644 --- a/shared/extra-utils/videos/index.ts +++ b/shared/extra-utils/videos/index.ts @@ -1,8 +1,9 @@ export * from './blacklist-command' +export * from './captions' +export * from './captions-command' export * from './live-command' export * from './live' export * from './services-command' -export * from './video-captions' export * from './video-change-ownership' export * from './video-channels' export * from './video-comments' diff --git a/shared/extra-utils/videos/video-captions.ts b/shared/extra-utils/videos/video-captions.ts deleted file mode 100644 index 62eec7b90..000000000 --- a/shared/extra-utils/videos/video-captions.ts +++ /dev/null @@ -1,72 +0,0 @@ -import { makeDeleteRequest, makeGetRequest, makeUploadRequest } from '../requests/requests' -import * as request from 'supertest' -import * as chai from 'chai' -import { buildAbsoluteFixturePath } from '../miscs/miscs' -import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' - -const expect = chai.expect - -function createVideoCaption (args: { - url: string - accessToken: string - videoId: string | number - language: string - fixture: string - mimeType?: string - statusCodeExpected?: number -}) { - const path = '/api/v1/videos/' + args.videoId + '/captions/' + args.language - - const captionfile = buildAbsoluteFixturePath(args.fixture) - const captionfileAttach = args.mimeType ? [ captionfile, { contentType: args.mimeType } ] : captionfile - - return makeUploadRequest({ - method: 'PUT', - url: args.url, - path, - token: args.accessToken, - fields: {}, - attaches: { - captionfile: captionfileAttach - }, - statusCodeExpected: args.statusCodeExpected || HttpStatusCode.NO_CONTENT_204 - }) -} - -function listVideoCaptions (url: string, videoId: string | number) { - const path = '/api/v1/videos/' + videoId + '/captions' - - return makeGetRequest({ - url, - path, - statusCodeExpected: HttpStatusCode.OK_200 - }) -} - -function deleteVideoCaption (url: string, token: string, videoId: string | number, language: string) { - const path = '/api/v1/videos/' + videoId + '/captions/' + language - - return makeDeleteRequest({ - url, - token, - path, - statusCodeExpected: HttpStatusCode.NO_CONTENT_204 - }) -} - -async function testCaptionFile (url: string, captionPath: string, containsString: string) { - const res = await request(url) - .get(captionPath) - .expect(HttpStatusCode.OK_200) - - expect(res.text).to.contain(containsString) -} - -// --------------------------------------------------------------------------- - -export { - createVideoCaption, - listVideoCaptions, - testCaptionFile, - deleteVideoCaption -} -- cgit v1.2.3 From dcc30997d14600a48bf7e28e911bf50a382b9e53 Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Thu, 8 Jul 2021 11:50:57 +0200 Subject: Trigger a build for any branch --- .github/workflows/stats.yml | 4 ---- 1 file changed, 4 deletions(-) diff --git a/.github/workflows/stats.yml b/.github/workflows/stats.yml index 968eb9612..ebe16fb1d 100644 --- a/.github/workflows/stats.yml +++ b/.github/workflows/stats.yml @@ -2,10 +2,6 @@ name: "Stats" on: push: - branches: - - develop - - ci - - next pull_request: types: [synchronize, opened] -- cgit v1.2.3 From 44364d06d7434e7e01c5bb383a27e6c3bd8a0f13 Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Thu, 8 Jul 2021 13:44:08 +0200 Subject: Trigger test build for any branch --- .github/workflows/stats.yml | 4 ++++ .github/workflows/test.yml | 5 ----- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/.github/workflows/stats.yml b/.github/workflows/stats.yml index ebe16fb1d..968eb9612 100644 --- a/.github/workflows/stats.yml +++ b/.github/workflows/stats.yml @@ -2,6 +2,10 @@ name: "Stats" on: push: + branches: + - develop + - ci + - next pull_request: types: [synchronize, opened] diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 46b243244..c5bbd9e2c 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -2,11 +2,6 @@ name: Test Suite on: push: - branches: - - develop - - master - - ci - - next pull_request: types: [synchronize, opened] schedule: -- cgit v1.2.3 From 72cbfc5695ec5ebdb9721d3648218f63feeaeac5 Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Thu, 8 Jul 2021 13:56:04 +0200 Subject: Introduce change ownership command --- server/tests/api/videos/video-change-ownership.ts | 185 +++++++++++---------- shared/extra-utils/server/servers.ts | 4 +- .../extra-utils/videos/change-ownership-command.ts | 69 ++++++++ shared/extra-utils/videos/index.ts | 2 +- .../extra-utils/videos/video-change-ownership.ts | 72 -------- 5 files changed, 173 insertions(+), 159 deletions(-) create mode 100644 shared/extra-utils/videos/change-ownership-command.ts delete mode 100644 shared/extra-utils/videos/video-change-ownership.ts diff --git a/server/tests/api/videos/video-change-ownership.ts b/server/tests/api/videos/video-change-ownership.ts index 3c33cf015..1b81fe047 100644 --- a/server/tests/api/videos/video-change-ownership.ts +++ b/server/tests/api/videos/video-change-ownership.ts @@ -4,8 +4,7 @@ import 'mocha' import * as chai from 'chai' import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' import { - acceptChangeOwnership, - changeVideoOwnership, + ChangeOwnershipCommand, cleanupTests, createUser, doubleFollow, @@ -13,9 +12,7 @@ import { flushAndRunServer, getMyUserInformation, getVideo, - getVideoChangeOwnershipList, getVideosList, - refuseChangeOwnership, ServerInfo, setAccessTokensToServers, setDefaultVideoChannel, @@ -39,16 +36,18 @@ describe('Test video change ownership - nominal', function () { password: 'My other password' } - let firstUserAccessToken = '' + let firstUserToken = '' let firstUserChannelId: number - let secondUserAccessToken = '' + let secondUserToken = '' let secondUserChannelId: number - let lastRequestChangeOwnershipId = '' + let lastRequestId: number let liveId: number + let command: ChangeOwnershipCommand + before(async function () { this.timeout(50000) @@ -83,17 +82,17 @@ describe('Test video change ownership - nominal', function () { videoQuota: videoQuota }) - firstUserAccessToken = await userLogin(servers[0], firstUser) - secondUserAccessToken = await userLogin(servers[0], secondUser) + firstUserToken = await userLogin(servers[0], firstUser) + secondUserToken = await userLogin(servers[0], secondUser) { - const res = await getMyUserInformation(servers[0].url, firstUserAccessToken) + const res = await getMyUserInformation(servers[0].url, firstUserToken) const firstUserInformation: User = res.body firstUserChannelId = firstUserInformation.videoChannels[0].id } { - const res = await getMyUserInformation(servers[0].url, secondUserAccessToken) + const res = await getMyUserInformation(servers[0].url, secondUserToken) const secondUserInformation: User = res.body secondUserChannelId = secondUserInformation.videoChannels[0].id } @@ -103,7 +102,7 @@ describe('Test video change ownership - nominal', function () { name: 'my super name', description: 'my super description' } - const res = await uploadVideo(servers[0].url, firstUserAccessToken, videoAttributes) + const res = await uploadVideo(servers[0].url, firstUserToken, videoAttributes) const resVideo = await getVideo(servers[0].url, res.body.video.id) servers[0].video = resVideo.body @@ -111,116 +110,129 @@ describe('Test video change ownership - nominal', function () { { const attributes = { name: 'live', channelId: firstUserChannelId, privacy: VideoPrivacy.PUBLIC } - const video = await servers[0].liveCommand.create({ token: firstUserAccessToken, fields: attributes }) + const video = await servers[0].liveCommand.create({ token: firstUserToken, fields: attributes }) liveId = video.id } + command = servers[0].changeOwnershipCommand + await doubleFollow(servers[0], servers[1]) }) it('Should not have video change ownership', async function () { - const resFirstUser = await getVideoChangeOwnershipList(servers[0].url, firstUserAccessToken) + { + const body = await command.list({ token: firstUserToken }) - expect(resFirstUser.body.total).to.equal(0) - expect(resFirstUser.body.data).to.be.an('array') - expect(resFirstUser.body.data.length).to.equal(0) + expect(body.total).to.equal(0) + expect(body.data).to.be.an('array') + expect(body.data.length).to.equal(0) + } - const resSecondUser = await getVideoChangeOwnershipList(servers[0].url, secondUserAccessToken) + { + const body = await command.list({ token: secondUserToken }) - expect(resSecondUser.body.total).to.equal(0) - expect(resSecondUser.body.data).to.be.an('array') - expect(resSecondUser.body.data.length).to.equal(0) + expect(body.total).to.equal(0) + expect(body.data).to.be.an('array') + expect(body.data.length).to.equal(0) + } }) it('Should send a request to change ownership of a video', async function () { this.timeout(15000) - await changeVideoOwnership(servers[0].url, firstUserAccessToken, servers[0].video.id, secondUser.username) + await command.create({ token: firstUserToken, videoId: servers[0].video.id, username: secondUser.username }) }) it('Should only return a request to change ownership for the second user', async function () { - const resFirstUser = await getVideoChangeOwnershipList(servers[0].url, firstUserAccessToken) + { + const body = await command.list({ token: firstUserToken }) - expect(resFirstUser.body.total).to.equal(0) - expect(resFirstUser.body.data).to.be.an('array') - expect(resFirstUser.body.data.length).to.equal(0) + expect(body.total).to.equal(0) + expect(body.data).to.be.an('array') + expect(body.data.length).to.equal(0) + } - const resSecondUser = await getVideoChangeOwnershipList(servers[0].url, secondUserAccessToken) + { + const body = await command.list({ token: secondUserToken }) - expect(resSecondUser.body.total).to.equal(1) - expect(resSecondUser.body.data).to.be.an('array') - expect(resSecondUser.body.data.length).to.equal(1) + expect(body.total).to.equal(1) + expect(body.data).to.be.an('array') + expect(body.data.length).to.equal(1) - lastRequestChangeOwnershipId = resSecondUser.body.data[0].id + lastRequestId = body.data[0].id + } }) it('Should accept the same change ownership request without crashing', async function () { this.timeout(10000) - await changeVideoOwnership(servers[0].url, firstUserAccessToken, servers[0].video.id, secondUser.username) + await command.create({ token: firstUserToken, videoId: servers[0].video.id, username: secondUser.username }) }) it('Should not create multiple change ownership requests while one is waiting', async function () { this.timeout(10000) - const resSecondUser = await getVideoChangeOwnershipList(servers[0].url, secondUserAccessToken) + const body = await command.list({ token: secondUserToken }) - expect(resSecondUser.body.total).to.equal(1) - expect(resSecondUser.body.data).to.be.an('array') - expect(resSecondUser.body.data.length).to.equal(1) + expect(body.total).to.equal(1) + expect(body.data).to.be.an('array') + expect(body.data.length).to.equal(1) }) it('Should not be possible to refuse the change of ownership from first user', async function () { this.timeout(10000) - await refuseChangeOwnership(servers[0].url, firstUserAccessToken, lastRequestChangeOwnershipId, HttpStatusCode.FORBIDDEN_403) + await command.refuse({ token: firstUserToken, ownershipId: lastRequestId, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) it('Should be possible to refuse the change of ownership from second user', async function () { this.timeout(10000) - await refuseChangeOwnership(servers[0].url, secondUserAccessToken, lastRequestChangeOwnershipId) + await command.refuse({ token: secondUserToken, ownershipId: lastRequestId }) }) it('Should send a new request to change ownership of a video', async function () { this.timeout(15000) - await changeVideoOwnership(servers[0].url, firstUserAccessToken, servers[0].video.id, secondUser.username) + await command.create({ token: firstUserToken, videoId: servers[0].video.id, username: secondUser.username }) }) it('Should return two requests to change ownership for the second user', async function () { - const resFirstUser = await getVideoChangeOwnershipList(servers[0].url, firstUserAccessToken) + { + const body = await command.list({ token: firstUserToken }) - expect(resFirstUser.body.total).to.equal(0) - expect(resFirstUser.body.data).to.be.an('array') - expect(resFirstUser.body.data.length).to.equal(0) + expect(body.total).to.equal(0) + expect(body.data).to.be.an('array') + expect(body.data.length).to.equal(0) + } - const resSecondUser = await getVideoChangeOwnershipList(servers[0].url, secondUserAccessToken) + { + const body = await command.list({ token: secondUserToken }) - expect(resSecondUser.body.total).to.equal(2) - expect(resSecondUser.body.data).to.be.an('array') - expect(resSecondUser.body.data.length).to.equal(2) + expect(body.total).to.equal(2) + expect(body.data).to.be.an('array') + expect(body.data.length).to.equal(2) - lastRequestChangeOwnershipId = resSecondUser.body.data[0].id + lastRequestId = body.data[0].id + } }) it('Should not be possible to accept the change of ownership from first user', async function () { this.timeout(10000) - await acceptChangeOwnership( - servers[0].url, - firstUserAccessToken, - lastRequestChangeOwnershipId, - secondUserChannelId, - HttpStatusCode.FORBIDDEN_403 - ) + await command.accept({ + token: firstUserToken, + ownershipId: lastRequestId, + channelId: secondUserChannelId, + expectedStatus: HttpStatusCode.FORBIDDEN_403 + }) }) it('Should be possible to accept the change of ownership from second user', async function () { this.timeout(10000) - await acceptChangeOwnership(servers[0].url, secondUserAccessToken, lastRequestChangeOwnershipId, secondUserChannelId) + await command.accept({ token: secondUserToken, ownershipId: lastRequestId, channelId: secondUserChannelId }) await waitJobs(servers) }) @@ -240,20 +252,20 @@ describe('Test video change ownership - nominal', function () { it('Should send a request to change ownership of a live', async function () { this.timeout(15000) - await changeVideoOwnership(servers[0].url, firstUserAccessToken, liveId, secondUser.username) + await command.create({ token: firstUserToken, videoId: liveId, username: secondUser.username }) - const resSecondUser = await getVideoChangeOwnershipList(servers[0].url, secondUserAccessToken) + const body = await command.list({ token: secondUserToken }) - expect(resSecondUser.body.total).to.equal(3) - expect(resSecondUser.body.data.length).to.equal(3) + expect(body.total).to.equal(3) + expect(body.data.length).to.equal(3) - lastRequestChangeOwnershipId = resSecondUser.body.data[0].id + lastRequestId = body.data[0].id }) it('Should accept a live ownership change', async function () { this.timeout(20000) - await acceptChangeOwnership(servers[0].url, secondUserAccessToken, lastRequestChangeOwnershipId, secondUserChannelId) + await command.accept({ token: secondUserToken, ownershipId: lastRequestId, channelId: secondUserChannelId }) await waitJobs(servers) @@ -283,9 +295,9 @@ describe('Test video change ownership - quota too small', function () { username: 'second', password: 'My other password' } - let firstUserAccessToken = '' - let secondUserAccessToken = '' - let lastRequestChangeOwnershipId = '' + let firstUserToken = '' + let secondUserToken = '' + let lastRequestId: number before(async function () { this.timeout(50000) @@ -311,15 +323,15 @@ describe('Test video change ownership - quota too small', function () { videoQuota: limitedVideoQuota }) - firstUserAccessToken = await userLogin(server, firstUser) - secondUserAccessToken = await userLogin(server, secondUser) + firstUserToken = await userLogin(server, firstUser) + secondUserToken = await userLogin(server, secondUser) // Upload some videos on the server const video1Attributes = { name: 'my super name', description: 'my super description' } - await uploadVideo(server.url, firstUserAccessToken, video1Attributes) + await uploadVideo(server.url, firstUserToken, video1Attributes) await waitJobs(server) @@ -334,39 +346,42 @@ describe('Test video change ownership - quota too small', function () { it('Should send a request to change ownership of a video', async function () { this.timeout(15000) - await changeVideoOwnership(server.url, firstUserAccessToken, server.video.id, secondUser.username) + await server.changeOwnershipCommand.create({ token: firstUserToken, videoId: server.video.id, username: secondUser.username }) }) it('Should only return a request to change ownership for the second user', async function () { - const resFirstUser = await getVideoChangeOwnershipList(server.url, firstUserAccessToken) + { + const body = await server.changeOwnershipCommand.list({ token: firstUserToken }) - expect(resFirstUser.body.total).to.equal(0) - expect(resFirstUser.body.data).to.be.an('array') - expect(resFirstUser.body.data.length).to.equal(0) + expect(body.total).to.equal(0) + expect(body.data).to.be.an('array') + expect(body.data.length).to.equal(0) + } - const resSecondUser = await getVideoChangeOwnershipList(server.url, secondUserAccessToken) + { + const body = await server.changeOwnershipCommand.list({ token: secondUserToken }) - expect(resSecondUser.body.total).to.equal(1) - expect(resSecondUser.body.data).to.be.an('array') - expect(resSecondUser.body.data.length).to.equal(1) + expect(body.total).to.equal(1) + expect(body.data).to.be.an('array') + expect(body.data.length).to.equal(1) - lastRequestChangeOwnershipId = resSecondUser.body.data[0].id + lastRequestId = body.data[0].id + } }) it('Should not be possible to accept the change of ownership from second user because of exceeded quota', async function () { this.timeout(10000) - const secondUserInformationResponse = await getMyUserInformation(server.url, secondUserAccessToken) + const secondUserInformationResponse = await getMyUserInformation(server.url, secondUserToken) const secondUserInformation: User = secondUserInformationResponse.body const channelId = secondUserInformation.videoChannels[0].id - await acceptChangeOwnership( - server.url, - secondUserAccessToken, - lastRequestChangeOwnershipId, + await server.changeOwnershipCommand.accept({ + token: secondUserToken, + ownershipId: lastRequestId, channelId, - HttpStatusCode.PAYLOAD_TOO_LARGE_413 - ) + expectedStatus: HttpStatusCode.PAYLOAD_TOO_LARGE_413 + }) }) after(async function () { diff --git a/shared/extra-utils/server/servers.ts b/shared/extra-utils/server/servers.ts index 170360341..33f558414 100644 --- a/shared/extra-utils/server/servers.ts +++ b/shared/extra-utils/server/servers.ts @@ -18,7 +18,7 @@ import { makeGetRequest } from '../requests/requests' import { SearchCommand } from '../search' import { SocketIOCommand } from '../socket' import { AccountsCommand, BlocklistCommand, SubscriptionsCommand } from '../users' -import { LiveCommand, ServicesCommand, BlacklistCommand, CaptionsCommand } from '../videos' +import { BlacklistCommand, CaptionsCommand, ChangeOwnershipCommand, LiveCommand, ServicesCommand } from '../videos' import { ConfigCommand } from './config-command' import { ContactFormCommand } from './contact-form-command' import { DebugCommand } from './debug-command' @@ -104,6 +104,7 @@ interface ServerInfo { servicesCommand?: ServicesCommand blacklistCommand?: BlacklistCommand captionsCommand?: CaptionsCommand + changeOwnershipCommand?: ChangeOwnershipCommand } function parallelTests () { @@ -333,6 +334,7 @@ async function runServer (server: ServerInfo, configOverrideArg?: any, args = [] server.servicesCommand = new ServicesCommand(server) server.blacklistCommand = new BlacklistCommand(server) server.captionsCommand = new CaptionsCommand(server) + server.changeOwnershipCommand = new ChangeOwnershipCommand(server) res(server) }) diff --git a/shared/extra-utils/videos/change-ownership-command.ts b/shared/extra-utils/videos/change-ownership-command.ts new file mode 100644 index 000000000..03f77a95f --- /dev/null +++ b/shared/extra-utils/videos/change-ownership-command.ts @@ -0,0 +1,69 @@ + +import { ResultList, VideoChangeOwnership } from '@shared/models' +import { HttpStatusCode } from '../../core-utils/miscs/http-error-codes' +import { AbstractCommand, OverrideCommandOptions } from '../shared' + +export class ChangeOwnershipCommand extends AbstractCommand { + + create (options: OverrideCommandOptions & { + videoId: number | string + username: string + }) { + const { videoId, username } = options + const path = '/api/v1/videos/' + videoId + '/give-ownership' + + return this.postBodyRequest({ + ...options, + + path, + fields: { username }, + implicitToken: true, + defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 + }) + } + + list (options: OverrideCommandOptions = {}) { + const path = '/api/v1/videos/ownership' + + return this.getRequestBody>({ + ...options, + + path, + query: { sort: '-createdAt' }, + implicitToken: true, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } + + accept (options: OverrideCommandOptions & { + ownershipId: number + channelId: number + }) { + const { ownershipId, channelId } = options + const path = '/api/v1/videos/ownership/' + ownershipId + '/accept' + + return this.postBodyRequest({ + ...options, + + path, + fields: { channelId }, + implicitToken: true, + defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 + }) + } + + refuse (options: OverrideCommandOptions & { + ownershipId: number + }) { + const { ownershipId } = options + const path = '/api/v1/videos/ownership/' + ownershipId + '/refuse' + + return this.postBodyRequest({ + ...options, + + path, + implicitToken: true, + defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 + }) + } +} diff --git a/shared/extra-utils/videos/index.ts b/shared/extra-utils/videos/index.ts index 03b4756d5..815c7f944 100644 --- a/shared/extra-utils/videos/index.ts +++ b/shared/extra-utils/videos/index.ts @@ -1,10 +1,10 @@ export * from './blacklist-command' export * from './captions' export * from './captions-command' +export * from './change-ownership-command' export * from './live-command' export * from './live' export * from './services-command' -export * from './video-change-ownership' export * from './video-channels' export * from './video-comments' export * from './video-history' diff --git a/shared/extra-utils/videos/video-change-ownership.ts b/shared/extra-utils/videos/video-change-ownership.ts deleted file mode 100644 index ef82a7636..000000000 --- a/shared/extra-utils/videos/video-change-ownership.ts +++ /dev/null @@ -1,72 +0,0 @@ -import * as request from 'supertest' -import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' - -function changeVideoOwnership ( - url: string, - token: string, - videoId: number | string, - username, - expectedStatus = HttpStatusCode.NO_CONTENT_204 -) { - const path = '/api/v1/videos/' + videoId + '/give-ownership' - - return request(url) - .post(path) - .set('Accept', 'application/json') - .set('Authorization', 'Bearer ' + token) - .send({ username }) - .expect(expectedStatus) -} - -function getVideoChangeOwnershipList (url: string, token: string) { - const path = '/api/v1/videos/ownership' - - return request(url) - .get(path) - .query({ sort: '-createdAt' }) - .set('Accept', 'application/json') - .set('Authorization', 'Bearer ' + token) - .expect(HttpStatusCode.OK_200) - .expect('Content-Type', /json/) -} - -function acceptChangeOwnership ( - url: string, - token: string, - ownershipId: string, - channelId: number, - expectedStatus = HttpStatusCode.NO_CONTENT_204 -) { - const path = '/api/v1/videos/ownership/' + ownershipId + '/accept' - - return request(url) - .post(path) - .set('Accept', 'application/json') - .set('Authorization', 'Bearer ' + token) - .send({ channelId }) - .expect(expectedStatus) -} - -function refuseChangeOwnership ( - url: string, - token: string, - ownershipId: string, - expectedStatus = HttpStatusCode.NO_CONTENT_204 -) { - const path = '/api/v1/videos/ownership/' + ownershipId + '/refuse' - - return request(url) - .post(path) - .set('Accept', 'application/json') - .set('Authorization', 'Bearer ' + token) - .expect(expectedStatus) -} - -// --------------------------------------------------------------------------- - -export { - changeVideoOwnership, - getVideoChangeOwnershipList, - acceptChangeOwnership, - refuseChangeOwnership -} -- cgit v1.2.3 From e6346d59e63135cf012ed18c102d3b0179ef565f Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Thu, 8 Jul 2021 15:54:39 +0200 Subject: Introduce playlist command --- server/controllers/api/video-playlist.ts | 7 +- server/tests/api/activitypub/client.ts | 6 +- server/tests/api/activitypub/refresher.ts | 22 +- server/tests/api/check-params/services.ts | 18 +- server/tests/api/check-params/video-playlists.ts | 347 +++++++------ .../search/search-activitypub-video-playlists.ts | 45 +- server/tests/api/search/search-playlists.ts | 26 +- server/tests/api/server/services.ts | 18 +- server/tests/api/server/stats.ts | 7 +- .../tests/api/videos/video-playlist-thumbnails.ts | 123 ++--- server/tests/api/videos/video-playlists.ts | 564 +++++++++------------ server/tests/cli/prune-storage.ts | 7 +- server/tests/client.ts | 14 +- server/tests/plugins/action-hooks.ts | 17 +- server/tests/plugins/filter-hooks.ts | 10 +- server/tests/plugins/video-constants.ts | 17 +- shared/extra-utils/server/servers.ts | 4 +- shared/extra-utils/videos/index.ts | 3 +- shared/extra-utils/videos/playlists-command.ts | 280 ++++++++++ shared/extra-utils/videos/playlists.ts | 25 + shared/extra-utils/videos/video-playlists.ts | 320 ------------ shared/extra-utils/videos/videos.ts | 23 - shared/models/videos/playlist/index.ts | 1 + .../video-playlist-element-create-result.model.ts | 3 + 24 files changed, 853 insertions(+), 1054 deletions(-) create mode 100644 shared/extra-utils/videos/playlists-command.ts create mode 100644 shared/extra-utils/videos/playlists.ts delete mode 100644 shared/extra-utils/videos/video-playlists.ts create mode 100644 shared/models/videos/playlist/video-playlist-element-create-result.model.ts diff --git a/server/controllers/api/video-playlist.ts b/server/controllers/api/video-playlist.ts index 87a6f6bbe..78cbd9cff 100644 --- a/server/controllers/api/video-playlist.ts +++ b/server/controllers/api/video-playlist.ts @@ -5,6 +5,7 @@ import { scheduleRefreshIfNeeded } from '@server/lib/activitypub/playlists' import { Hooks } from '@server/lib/plugins/hooks' import { getServerActor } from '@server/models/application/application' import { MVideoPlaylistFull, MVideoPlaylistThumbnail, MVideoThumbnail } from '@server/types/models' +import { VideoPlaylistCreateResult, VideoPlaylistElementCreateResult } from '@shared/models' import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' import { VideoPlaylistCreate } from '../../../shared/models/videos/playlist/video-playlist-create.model' import { VideoPlaylistElementCreate } from '../../../shared/models/videos/playlist/video-playlist-element-create.model' @@ -202,7 +203,7 @@ async function addVideoPlaylist (req: express.Request, res: express.Response) { id: videoPlaylistCreated.id, shortUUID: uuidToShort(videoPlaylistCreated.uuid), uuid: videoPlaylistCreated.uuid - } + } as VideoPlaylistCreateResult }) } @@ -338,8 +339,8 @@ async function addVideoInPlaylist (req: express.Request, res: express.Response) return res.json({ videoPlaylistElement: { id: playlistElement.id - } - }).end() + } as VideoPlaylistElementCreateResult + }) } async function updateVideoPlaylistElement (req: express.Request, res: express.Response) { diff --git a/server/tests/api/activitypub/client.ts b/server/tests/api/activitypub/client.ts index be94e219c..e8536a214 100644 --- a/server/tests/api/activitypub/client.ts +++ b/server/tests/api/activitypub/client.ts @@ -6,7 +6,6 @@ import { VideoPlaylistPrivacy } from '@shared/models' import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' import { cleanupTests, - createVideoPlaylist, doubleFollow, flushAndRunMultipleServers, makeActivityPubGetRequest, @@ -74,9 +73,8 @@ describe('Test activitypub', function () { } { - const playlistAttrs = { displayName: 'playlist', privacy: VideoPlaylistPrivacy.PUBLIC, videoChannelId: servers[0].videoChannel.id } - const resCreate = await createVideoPlaylist({ url: servers[0].url, token: servers[0].accessToken, playlistAttrs }) - playlist = resCreate.body.videoPlaylist + const attributes = { displayName: 'playlist', privacy: VideoPlaylistPrivacy.PUBLIC, videoChannelId: servers[0].videoChannel.id } + playlist = await servers[0].playlistsCommand.create({ attributes }) } await doubleFollow(servers[0], servers[1]) diff --git a/server/tests/api/activitypub/refresher.ts b/server/tests/api/activitypub/refresher.ts index 0d5452ea4..f295dfab7 100644 --- a/server/tests/api/activitypub/refresher.ts +++ b/server/tests/api/activitypub/refresher.ts @@ -5,12 +5,10 @@ import { HttpStatusCode } from '@shared/core-utils' import { cleanupTests, closeAllSequelize, - createVideoPlaylist, doubleFollow, flushAndRunMultipleServers, generateUserAccessToken, getVideo, - getVideoPlaylist, killallServers, reRunServer, ServerInfo, @@ -58,15 +56,15 @@ describe('Test AP refresher', function () { } { - const playlistAttrs = { displayName: 'playlist1', privacy: VideoPlaylistPrivacy.PUBLIC, videoChannelId: servers[1].videoChannel.id } - const res = await createVideoPlaylist({ url: servers[1].url, token: servers[1].accessToken, playlistAttrs }) - playlistUUID1 = res.body.videoPlaylist.uuid + const attributes = { displayName: 'playlist1', privacy: VideoPlaylistPrivacy.PUBLIC, videoChannelId: servers[1].videoChannel.id } + const created = await servers[1].playlistsCommand.create({ attributes }) + playlistUUID1 = created.uuid } { - const playlistAttrs = { displayName: 'playlist2', privacy: VideoPlaylistPrivacy.PUBLIC, videoChannelId: servers[1].videoChannel.id } - const res = await createVideoPlaylist({ url: servers[1].url, token: servers[1].accessToken, playlistAttrs }) - playlistUUID2 = res.body.videoPlaylist.uuid + const attributes = { displayName: 'playlist2', privacy: VideoPlaylistPrivacy.PUBLIC, videoChannelId: servers[1].videoChannel.id } + const created = await servers[1].playlistsCommand.create({ attributes }) + playlistUUID2 = created.uuid } await doubleFollow(servers[0], servers[1]) @@ -144,13 +142,13 @@ describe('Test AP refresher', function () { // Change UUID so the remote server returns a 404 await setPlaylistField(servers[1].internalServerNumber, playlistUUID2, 'uuid', '304afe4f-39f9-4d49-8ed7-ac57b86b178e') - await getVideoPlaylist(servers[0].url, playlistUUID1) - await getVideoPlaylist(servers[0].url, playlistUUID2) + await servers[0].playlistsCommand.get({ playlistId: playlistUUID1 }) + await servers[0].playlistsCommand.get({ playlistId: playlistUUID2 }) await waitJobs(servers) - await getVideoPlaylist(servers[0].url, playlistUUID1, HttpStatusCode.OK_200) - await getVideoPlaylist(servers[0].url, playlistUUID2, HttpStatusCode.NOT_FOUND_404) + await servers[0].playlistsCommand.get({ playlistId: playlistUUID1, expectedStatus: HttpStatusCode.OK_200 }) + await servers[0].playlistsCommand.get({ playlistId: playlistUUID2, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) }) diff --git a/server/tests/api/check-params/services.ts b/server/tests/api/check-params/services.ts index 514e3da70..595fab70d 100644 --- a/server/tests/api/check-params/services.ts +++ b/server/tests/api/check-params/services.ts @@ -1,19 +1,17 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ import 'mocha' - +import { VideoPlaylistPrivacy } from '@shared/models' +import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' import { cleanupTests, flushAndRunServer, makeGetRequest, ServerInfo, setAccessTokensToServers, - uploadVideo, - createVideoPlaylist, - setDefaultVideoChannel + setDefaultVideoChannel, + uploadVideo } from '../../../../shared/extra-utils' -import { VideoPlaylistPrivacy } from '@shared/models' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' describe('Test services API validators', function () { let server: ServerInfo @@ -34,17 +32,15 @@ describe('Test services API validators', function () { } { - const res = await createVideoPlaylist({ - url: server.url, - token: server.accessToken, - playlistAttrs: { + const created = await server.playlistsCommand.create({ + attributes: { displayName: 'super playlist', privacy: VideoPlaylistPrivacy.PUBLIC, videoChannelId: server.videoChannel.id } }) - playlistUUID = res.body.videoPlaylist.uuid + playlistUUID = created.uuid } }) diff --git a/server/tests/api/check-params/video-playlists.ts b/server/tests/api/check-params/video-playlists.ts index 18253d11a..1c507a047 100644 --- a/server/tests/api/check-params/video-playlists.ts +++ b/server/tests/api/check-params/video-playlists.ts @@ -1,29 +1,29 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ import 'mocha' -import { VideoPlaylistCreateResult, VideoPlaylistPrivacy, VideoPlaylistType } from '@shared/models' +import { + VideoPlaylistCreate, + VideoPlaylistCreateResult, + VideoPlaylistElementCreate, + VideoPlaylistElementUpdate, + VideoPlaylistPrivacy, + VideoPlaylistReorder, + VideoPlaylistType +} from '@shared/models' import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' import { - addVideoInPlaylist, checkBadCountPagination, checkBadSortPagination, checkBadStartPagination, cleanupTests, - createVideoPlaylist, - deleteVideoPlaylist, flushAndRunServer, generateUserAccessToken, - getAccountPlaylistsListWithToken, - getVideoPlaylist, immutableAssign, makeGetRequest, - removeVideoFromPlaylist, - reorderVideosPlaylist, + PlaylistsCommand, ServerInfo, setAccessTokensToServers, setDefaultVideoChannel, - updateVideoPlaylist, - updateVideoPlaylistElement, uploadVideoAndGetId } from '../../../../shared/extra-utils' @@ -36,7 +36,9 @@ describe('Test video playlists API validator', function () { let watchLaterPlaylistId: number let videoId: number - let playlistElementId: number + let elementId: number + + let command: PlaylistsCommand // --------------------------------------------------------------- @@ -51,34 +53,37 @@ describe('Test video playlists API validator', function () { userAccessToken = await generateUserAccessToken(server, 'user1') videoId = (await uploadVideoAndGetId({ server, videoName: 'video 1' })).id + command = server.playlistsCommand + { - const res = await getAccountPlaylistsListWithToken(server.url, server.accessToken, 'root', 0, 5, VideoPlaylistType.WATCH_LATER) - watchLaterPlaylistId = res.body.data[0].id + const { data } = await command.listByAccount({ + token: server.accessToken, + handle: 'root', + start: 0, + count: 5, + playlistType: VideoPlaylistType.WATCH_LATER + }) + watchLaterPlaylistId = data[0].id } { - const res = await createVideoPlaylist({ - url: server.url, - token: server.accessToken, - playlistAttrs: { + playlist = await command.create({ + attributes: { displayName: 'super playlist', privacy: VideoPlaylistPrivacy.PUBLIC, videoChannelId: server.videoChannel.id } }) - playlist = res.body.videoPlaylist } { - const res = await createVideoPlaylist({ - url: server.url, - token: server.accessToken, - playlistAttrs: { + const created = await command.create({ + attributes: { displayName: 'private', privacy: VideoPlaylistPrivacy.PRIVATE } }) - privatePlaylistUUID = res.body.videoPlaylist.uuid + privatePlaylistUUID = created.uuid } }) @@ -163,47 +168,50 @@ describe('Test video playlists API validator', function () { describe('When getting a video playlist', function () { it('Should fail with a bad id or uuid', async function () { - await getVideoPlaylist(server.url, 'toto', HttpStatusCode.BAD_REQUEST_400) + await command.get({ playlistId: 'toto', expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) it('Should fail with an unknown playlist', async function () { - await getVideoPlaylist(server.url, 42, HttpStatusCode.NOT_FOUND_404) + await command.get({ playlistId: 42, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) it('Should fail to get an unlisted playlist with the number id', async function () { - const res = await createVideoPlaylist({ - url: server.url, - token: server.accessToken, - playlistAttrs: { + const playlist = await command.create({ + attributes: { displayName: 'super playlist', videoChannelId: server.videoChannel.id, privacy: VideoPlaylistPrivacy.UNLISTED } }) - const playlist = res.body.videoPlaylist - await getVideoPlaylist(server.url, playlist.id, HttpStatusCode.NOT_FOUND_404) - await getVideoPlaylist(server.url, playlist.uuid, HttpStatusCode.OK_200) + await command.get({ playlistId: playlist.id, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) + await command.get({ playlistId: playlist.uuid, expectedStatus: HttpStatusCode.OK_200 }) }) it('Should succeed with the correct params', async function () { - await getVideoPlaylist(server.url, playlist.uuid, HttpStatusCode.OK_200) + await command.get({ playlistId: playlist.uuid, expectedStatus: HttpStatusCode.OK_200 }) }) }) describe('When creating/updating a video playlist', function () { - const getBase = (playlistAttrs: any = {}, wrapper: any = {}) => { - return Object.assign({ - expectedStatus: HttpStatusCode.BAD_REQUEST_400, - url: server.url, - token: server.accessToken, - playlistAttrs: Object.assign({ + const getBase = ( + attributes?: Partial, + wrapper?: Partial[0]> + ) => { + return { + attributes: { displayName: 'display name', privacy: VideoPlaylistPrivacy.UNLISTED, thumbnailfile: 'thumbnail.jpg', - videoChannelId: server.videoChannel.id - }, playlistAttrs) - }, wrapper) + videoChannelId: server.videoChannel.id, + + ...attributes + }, + + expectedStatus: HttpStatusCode.BAD_REQUEST_400, + + ...wrapper + } } const getUpdate = (params: any, playlistId: number | string) => { return immutableAssign(params, { playlistId: playlistId }) @@ -212,86 +220,86 @@ describe('Test video playlists API validator', function () { it('Should fail with an unauthenticated user', async function () { const params = getBase({}, { token: null, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) - await createVideoPlaylist(params) - await updateVideoPlaylist(getUpdate(params, playlist.shortUUID)) + await command.create(params) + await command.update(getUpdate(params, playlist.shortUUID)) }) it('Should fail without displayName', async function () { const params = getBase({ displayName: undefined }) - await createVideoPlaylist(params) + await command.create(params) }) it('Should fail with an incorrect display name', async function () { const params = getBase({ displayName: 's'.repeat(300) }) - await createVideoPlaylist(params) - await updateVideoPlaylist(getUpdate(params, playlist.shortUUID)) + await command.create(params) + await command.update(getUpdate(params, playlist.shortUUID)) }) it('Should fail with an incorrect description', async function () { const params = getBase({ description: 't' }) - await createVideoPlaylist(params) - await updateVideoPlaylist(getUpdate(params, playlist.shortUUID)) + await command.create(params) + await command.update(getUpdate(params, playlist.shortUUID)) }) it('Should fail with an incorrect privacy', async function () { const params = getBase({ privacy: 45 }) - await createVideoPlaylist(params) - await updateVideoPlaylist(getUpdate(params, playlist.shortUUID)) + await command.create(params) + await command.update(getUpdate(params, playlist.shortUUID)) }) it('Should fail with an unknown video channel id', async function () { const params = getBase({ videoChannelId: 42 }, { expectedStatus: HttpStatusCode.NOT_FOUND_404 }) - await createVideoPlaylist(params) - await updateVideoPlaylist(getUpdate(params, playlist.shortUUID)) + await command.create(params) + await command.update(getUpdate(params, playlist.shortUUID)) }) it('Should fail with an incorrect thumbnail file', async function () { const params = getBase({ thumbnailfile: 'video_short.mp4' }) - await createVideoPlaylist(params) - await updateVideoPlaylist(getUpdate(params, playlist.shortUUID)) + await command.create(params) + await command.update(getUpdate(params, playlist.shortUUID)) }) it('Should fail with a thumbnail file too big', async function () { const params = getBase({ thumbnailfile: 'preview-big.png' }) - await createVideoPlaylist(params) - await updateVideoPlaylist(getUpdate(params, playlist.shortUUID)) + await command.create(params) + await command.update(getUpdate(params, playlist.shortUUID)) }) it('Should fail to set "public" a playlist not assigned to a channel', async function () { const params = getBase({ privacy: VideoPlaylistPrivacy.PUBLIC, videoChannelId: undefined }) - const params2 = getBase({ privacy: VideoPlaylistPrivacy.PUBLIC, videoChannelId: 'null' }) - const params3 = getBase({ privacy: undefined, videoChannelId: 'null' }) + const params2 = getBase({ privacy: VideoPlaylistPrivacy.PUBLIC, videoChannelId: 'null' as any }) + const params3 = getBase({ privacy: undefined, videoChannelId: 'null' as any }) - await createVideoPlaylist(params) - await createVideoPlaylist(params2) - await updateVideoPlaylist(getUpdate(params, privatePlaylistUUID)) - await updateVideoPlaylist(getUpdate(params2, playlist.shortUUID)) - await updateVideoPlaylist(getUpdate(params3, playlist.shortUUID)) + await command.create(params) + await command.create(params2) + await command.update(getUpdate(params, privatePlaylistUUID)) + await command.update(getUpdate(params2, playlist.shortUUID)) + await command.update(getUpdate(params3, playlist.shortUUID)) }) it('Should fail with an unknown playlist to update', async function () { - await updateVideoPlaylist(getUpdate( + await command.update(getUpdate( getBase({}, { expectedStatus: HttpStatusCode.NOT_FOUND_404 }), 42 )) }) it('Should fail to update a playlist of another user', async function () { - await updateVideoPlaylist(getUpdate( + await command.update(getUpdate( getBase({}, { token: userAccessToken, expectedStatus: HttpStatusCode.FORBIDDEN_403 }), playlist.shortUUID )) }) it('Should fail to update the watch later playlist', async function () { - await updateVideoPlaylist(getUpdate( + await command.update(getUpdate( getBase({}, { expectedStatus: HttpStatusCode.BAD_REQUEST_400 }), watchLaterPlaylistId )) @@ -300,146 +308,158 @@ describe('Test video playlists API validator', function () { it('Should succeed with the correct params', async function () { { const params = getBase({}, { expectedStatus: HttpStatusCode.OK_200 }) - await createVideoPlaylist(params) + await command.create(params) } { const params = getBase({}, { expectedStatus: HttpStatusCode.NO_CONTENT_204 }) - await updateVideoPlaylist(getUpdate(params, playlist.shortUUID)) + await command.update(getUpdate(params, playlist.shortUUID)) } }) }) describe('When adding an element in a playlist', function () { - const getBase = (elementAttrs: any = {}, wrapper: any = {}) => { - return Object.assign({ - expectedStatus: HttpStatusCode.BAD_REQUEST_400, - url: server.url, - token: server.accessToken, - playlistId: playlist.id, - elementAttrs: Object.assign({ + const getBase = ( + attributes?: Partial, + wrapper?: Partial[0]> + ) => { + return { + attributes: { videoId, startTimestamp: 2, - stopTimestamp: 3 - }, elementAttrs) - }, wrapper) + stopTimestamp: 3, + + ...attributes + }, + + expectedStatus: HttpStatusCode.BAD_REQUEST_400, + playlistId: playlist.id, + + ...wrapper + } } it('Should fail with an unauthenticated user', async function () { const params = getBase({}, { token: null, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) - await addVideoInPlaylist(params) + await command.addElement(params) }) it('Should fail with the playlist of another user', async function () { const params = getBase({}, { token: userAccessToken, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) - await addVideoInPlaylist(params) + await command.addElement(params) }) it('Should fail with an unknown or incorrect playlist id', async function () { { const params = getBase({}, { playlistId: 'toto' }) - await addVideoInPlaylist(params) + await command.addElement(params) } { const params = getBase({}, { playlistId: 42, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) - await addVideoInPlaylist(params) + await command.addElement(params) } }) it('Should fail with an unknown or incorrect video id', async function () { const params = getBase({ videoId: 42 }, { expectedStatus: HttpStatusCode.NOT_FOUND_404 }) - await addVideoInPlaylist(params) + await command.addElement(params) }) it('Should fail with a bad start/stop timestamp', async function () { { const params = getBase({ startTimestamp: -42 }) - await addVideoInPlaylist(params) + await command.addElement(params) } { const params = getBase({ stopTimestamp: 'toto' as any }) - await addVideoInPlaylist(params) + await command.addElement(params) } }) it('Succeed with the correct params', async function () { const params = getBase({}, { expectedStatus: HttpStatusCode.OK_200 }) - const res = await addVideoInPlaylist(params) - playlistElementId = res.body.videoPlaylistElement.id + const created = await command.addElement(params) + elementId = created.id }) }) describe('When updating an element in a playlist', function () { - const getBase = (elementAttrs: any = {}, wrapper: any = {}) => { - return Object.assign({ - url: server.url, - token: server.accessToken, - elementAttrs: Object.assign({ + const getBase = ( + attributes?: Partial, + wrapper?: Partial[0]> + ) => { + return { + attributes: { startTimestamp: 1, - stopTimestamp: 2 - }, elementAttrs), - playlistElementId, + stopTimestamp: 2, + + ...attributes + }, + + elementId, playlistId: playlist.id, - expectedStatus: HttpStatusCode.BAD_REQUEST_400 - }, wrapper) + expectedStatus: HttpStatusCode.BAD_REQUEST_400, + + ...wrapper + } } it('Should fail with an unauthenticated user', async function () { const params = getBase({}, { token: null, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) - await updateVideoPlaylistElement(params) + await command.updateElement(params) }) it('Should fail with the playlist of another user', async function () { const params = getBase({}, { token: userAccessToken, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) - await updateVideoPlaylistElement(params) + await command.updateElement(params) }) it('Should fail with an unknown or incorrect playlist id', async function () { { const params = getBase({}, { playlistId: 'toto' }) - await updateVideoPlaylistElement(params) + await command.updateElement(params) } { const params = getBase({}, { playlistId: 42, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) - await updateVideoPlaylistElement(params) + await command.updateElement(params) } }) it('Should fail with an unknown or incorrect playlistElement id', async function () { { - const params = getBase({}, { playlistElementId: 'toto' }) - await updateVideoPlaylistElement(params) + const params = getBase({}, { elementId: 'toto' }) + await command.updateElement(params) } { - const params = getBase({}, { playlistElementId: 42, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) - await updateVideoPlaylistElement(params) + const params = getBase({}, { elementId: 42, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) + await command.updateElement(params) } }) it('Should fail with a bad start/stop timestamp', async function () { { const params = getBase({ startTimestamp: 'toto' as any }) - await updateVideoPlaylistElement(params) + await command.updateElement(params) } { const params = getBase({ stopTimestamp: -42 }) - await updateVideoPlaylistElement(params) + await command.updateElement(params) } }) it('Should fail with an unknown element', async function () { - const params = getBase({}, { playlistElementId: 888, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) - await updateVideoPlaylistElement(params) + const params = getBase({}, { elementId: 888, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) + await command.updateElement(params) }) it('Succeed with the correct params', async function () { const params = getBase({}, { expectedStatus: HttpStatusCode.NO_CONTENT_204 }) - await updateVideoPlaylistElement(params) + await command.updateElement(params) }) }) @@ -447,18 +467,24 @@ describe('Test video playlists API validator', function () { let videoId3: number let videoId4: number - const getBase = (elementAttrs: any = {}, wrapper: any = {}) => { - return Object.assign({ - url: server.url, - token: server.accessToken, - playlistId: playlist.shortUUID, - elementAttrs: Object.assign({ + const getBase = ( + attributes?: Partial, + wrapper?: Partial[0]> + ) => { + return { + attributes: { startPosition: 1, insertAfterPosition: 2, - reorderLength: 3 - }, elementAttrs), - expectedStatus: HttpStatusCode.BAD_REQUEST_400 - }, wrapper) + reorderLength: 3, + + ...attributes + }, + + playlistId: playlist.shortUUID, + expectedStatus: HttpStatusCode.BAD_REQUEST_400, + + ...wrapper + } } before(async function () { @@ -466,91 +492,86 @@ describe('Test video playlists API validator', function () { videoId4 = (await uploadVideoAndGetId({ server, videoName: 'video 4' })).id for (const id of [ videoId3, videoId4 ]) { - await addVideoInPlaylist({ - url: server.url, - token: server.accessToken, - playlistId: playlist.shortUUID, - elementAttrs: { videoId: id } - }) + await command.addElement({ playlistId: playlist.shortUUID, attributes: { videoId: id } }) } }) it('Should fail with an unauthenticated user', async function () { const params = getBase({}, { token: null, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) - await reorderVideosPlaylist(params) + await command.reorderElements(params) }) it('Should fail with the playlist of another user', async function () { const params = getBase({}, { token: userAccessToken, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) - await reorderVideosPlaylist(params) + await command.reorderElements(params) }) it('Should fail with an invalid playlist', async function () { { const params = getBase({}, { playlistId: 'toto' }) - await reorderVideosPlaylist(params) + await command.reorderElements(params) } { const params = getBase({}, { playlistId: 42, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) - await reorderVideosPlaylist(params) + await command.reorderElements(params) } }) it('Should fail with an invalid start position', async function () { { const params = getBase({ startPosition: -1 }) - await reorderVideosPlaylist(params) + await command.reorderElements(params) } { const params = getBase({ startPosition: 'toto' as any }) - await reorderVideosPlaylist(params) + await command.reorderElements(params) } { const params = getBase({ startPosition: 42 }) - await reorderVideosPlaylist(params) + await command.reorderElements(params) } }) it('Should fail with an invalid insert after position', async function () { { const params = getBase({ insertAfterPosition: 'toto' as any }) - await reorderVideosPlaylist(params) + await command.reorderElements(params) } { const params = getBase({ insertAfterPosition: -2 }) - await reorderVideosPlaylist(params) + await command.reorderElements(params) } { const params = getBase({ insertAfterPosition: 42 }) - await reorderVideosPlaylist(params) + await command.reorderElements(params) } }) it('Should fail with an invalid reorder length', async function () { { const params = getBase({ reorderLength: 'toto' as any }) - await reorderVideosPlaylist(params) + await command.reorderElements(params) } { const params = getBase({ reorderLength: -2 }) - await reorderVideosPlaylist(params) + await command.reorderElements(params) } { const params = getBase({ reorderLength: 42 }) - await reorderVideosPlaylist(params) + await command.reorderElements(params) } }) it('Succeed with the correct params', async function () { const params = getBase({}, { expectedStatus: HttpStatusCode.NO_CONTENT_204 }) - await reorderVideosPlaylist(params) + await command.reorderElements(params) }) }) @@ -601,76 +622,76 @@ describe('Test video playlists API validator', function () { }) describe('When deleting an element in a playlist', function () { - const getBase = (wrapper: any = {}) => { - return Object.assign({ - url: server.url, - token: server.accessToken, - playlistElementId, + const getBase = (wrapper: Partial[0]>) => { + return { + elementId, playlistId: playlist.uuid, - expectedStatus: HttpStatusCode.BAD_REQUEST_400 - }, wrapper) + expectedStatus: HttpStatusCode.BAD_REQUEST_400, + + ...wrapper + } } it('Should fail with an unauthenticated user', async function () { const params = getBase({ token: null, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) - await removeVideoFromPlaylist(params) + await command.removeElement(params) }) it('Should fail with the playlist of another user', async function () { const params = getBase({ token: userAccessToken, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) - await removeVideoFromPlaylist(params) + await command.removeElement(params) }) it('Should fail with an unknown or incorrect playlist id', async function () { { const params = getBase({ playlistId: 'toto' }) - await removeVideoFromPlaylist(params) + await command.removeElement(params) } { const params = getBase({ playlistId: 42, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) - await removeVideoFromPlaylist(params) + await command.removeElement(params) } }) it('Should fail with an unknown or incorrect video id', async function () { { - const params = getBase({ playlistElementId: 'toto' }) - await removeVideoFromPlaylist(params) + const params = getBase({ elementId: 'toto' as any }) + await command.removeElement(params) } { - const params = getBase({ playlistElementId: 42, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) - await removeVideoFromPlaylist(params) + const params = getBase({ elementId: 42, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) + await command.removeElement(params) } }) it('Should fail with an unknown element', async function () { - const params = getBase({ playlistElementId: 888, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) - await removeVideoFromPlaylist(params) + const params = getBase({ elementId: 888, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) + await command.removeElement(params) }) it('Succeed with the correct params', async function () { const params = getBase({ expectedStatus: HttpStatusCode.NO_CONTENT_204 }) - await removeVideoFromPlaylist(params) + await command.removeElement(params) }) }) describe('When deleting a playlist', function () { it('Should fail with an unknown playlist', async function () { - await deleteVideoPlaylist(server.url, server.accessToken, 42, HttpStatusCode.NOT_FOUND_404) + await command.delete({ playlistId: 42, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) it('Should fail with a playlist of another user', async function () { - await deleteVideoPlaylist(server.url, userAccessToken, playlist.uuid, HttpStatusCode.FORBIDDEN_403) + await command.delete({ token: userAccessToken, playlistId: playlist.uuid, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) it('Should fail with the watch later playlist', async function () { - await deleteVideoPlaylist(server.url, server.accessToken, watchLaterPlaylistId, HttpStatusCode.BAD_REQUEST_400) + await command.delete({ playlistId: watchLaterPlaylistId, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) it('Should succeed with the correct params', async function () { - await deleteVideoPlaylist(server.url, server.accessToken, playlist.uuid) + await command.delete({ playlistId: playlist.uuid }) }) }) diff --git a/server/tests/api/search/search-activitypub-video-playlists.ts b/server/tests/api/search/search-activitypub-video-playlists.ts index 1df18173a..cb7582d29 100644 --- a/server/tests/api/search/search-activitypub-video-playlists.ts +++ b/server/tests/api/search/search-activitypub-video-playlists.ts @@ -3,12 +3,8 @@ import 'mocha' import * as chai from 'chai' import { - addVideoInPlaylist, cleanupTests, - createVideoPlaylist, - deleteVideoPlaylist, flushAndRunMultipleServers, - getVideoPlaylistsList, SearchCommand, ServerInfo, setAccessTokensToServers, @@ -46,16 +42,11 @@ describe('Test ActivityPub playlists search', function () { privacy: VideoPlaylistPrivacy.PUBLIC, videoChannelId: servers[0].videoChannel.id } - const res = await createVideoPlaylist({ url: servers[0].url, token: servers[0].accessToken, playlistAttrs: attributes }) - playlistServer1UUID = res.body.videoPlaylist.uuid + const created = await servers[0].playlistsCommand.create({ attributes }) + playlistServer1UUID = created.uuid for (const videoId of [ video1, video2 ]) { - await addVideoInPlaylist({ - url: servers[0].url, - token: servers[0].accessToken, - playlistId: playlistServer1UUID, - elementAttrs: { videoId } - }) + await servers[0].playlistsCommand.addElement({ playlistId: playlistServer1UUID, attributes: { videoId } }) } } @@ -68,15 +59,10 @@ describe('Test ActivityPub playlists search', function () { privacy: VideoPlaylistPrivacy.PUBLIC, videoChannelId: servers[1].videoChannel.id } - const res = await createVideoPlaylist({ url: servers[1].url, token: servers[1].accessToken, playlistAttrs: attributes }) - playlistServer2UUID = res.body.videoPlaylist.uuid - - await addVideoInPlaylist({ - url: servers[1].url, - token: servers[1].accessToken, - playlistId: playlistServer2UUID, - elementAttrs: { videoId } - }) + const created = await servers[1].playlistsCommand.create({ attributes }) + playlistServer2UUID = created.uuid + + await servers[1].playlistsCommand.addElement({ playlistId: playlistServer2UUID, attributes: { videoId } }) } await waitJobs(servers) @@ -154,21 +140,16 @@ describe('Test ActivityPub playlists search', function () { }) it('Should not list this remote playlist', async function () { - const res = await getVideoPlaylistsList(servers[0].url, 0, 10) - expect(res.body.total).to.equal(1) - expect(res.body.data).to.have.lengthOf(1) - expect(res.body.data[0].displayName).to.equal('playlist 1 on server 1') + const body = await servers[0].playlistsCommand.list({ start: 0, count: 10 }) + expect(body.total).to.equal(1) + expect(body.data).to.have.lengthOf(1) + expect(body.data[0].displayName).to.equal('playlist 1 on server 1') }) it('Should update the playlist of server 2, and refresh it on server 1', async function () { this.timeout(60000) - await addVideoInPlaylist({ - url: servers[1].url, - token: servers[1].accessToken, - playlistId: playlistServer2UUID, - elementAttrs: { videoId: video2Server2 } - }) + await servers[1].playlistsCommand.addElement({ playlistId: playlistServer2UUID, attributes: { videoId: video2Server2 } }) await waitJobs(servers) // Expire playlist @@ -192,7 +173,7 @@ describe('Test ActivityPub playlists search', function () { it('Should delete playlist of server 2, and delete it on server 1', async function () { this.timeout(60000) - await deleteVideoPlaylist(servers[1].url, servers[1].accessToken, playlistServer2UUID) + await servers[1].playlistsCommand.delete({ playlistId: playlistServer2UUID }) await waitJobs(servers) // Expiration diff --git a/server/tests/api/search/search-playlists.ts b/server/tests/api/search/search-playlists.ts index 1862ecd31..517884503 100644 --- a/server/tests/api/search/search-playlists.ts +++ b/server/tests/api/search/search-playlists.ts @@ -4,9 +4,7 @@ import 'mocha' import * as chai from 'chai' import { VideoPlaylistPrivacy } from '@shared/models' import { - addVideoInPlaylist, cleanupTests, - createVideoPlaylist, flushAndRunServer, SearchCommand, ServerInfo, @@ -37,14 +35,9 @@ describe('Test playlists search', function () { privacy: VideoPlaylistPrivacy.PUBLIC, videoChannelId: server.videoChannel.id } - const res = await createVideoPlaylist({ url: server.url, token: server.accessToken, playlistAttrs: attributes }) - - await addVideoInPlaylist({ - url: server.url, - token: server.accessToken, - playlistId: res.body.videoPlaylist.id, - elementAttrs: { videoId } - }) + const created = await server.playlistsCommand.create({ attributes }) + + await server.playlistsCommand.addElement({ playlistId: created.id, attributes: { videoId } }) } { @@ -53,14 +46,9 @@ describe('Test playlists search', function () { privacy: VideoPlaylistPrivacy.PUBLIC, videoChannelId: server.videoChannel.id } - const res = await createVideoPlaylist({ url: server.url, token: server.accessToken, playlistAttrs: attributes }) - - await addVideoInPlaylist({ - url: server.url, - token: server.accessToken, - playlistId: res.body.videoPlaylist.id, - elementAttrs: { videoId } - }) + const created = await server.playlistsCommand.create({ attributes }) + + await server.playlistsCommand.addElement({ playlistId: created.id, attributes: { videoId } }) } { @@ -69,7 +57,7 @@ describe('Test playlists search', function () { privacy: VideoPlaylistPrivacy.PUBLIC, videoChannelId: server.videoChannel.id } - await createVideoPlaylist({ url: server.url, token: server.accessToken, playlistAttrs: attributes }) + await server.playlistsCommand.create({ attributes }) } command = server.searchCommand diff --git a/server/tests/api/server/services.ts b/server/tests/api/server/services.ts index 0adf6b667..77b95de10 100644 --- a/server/tests/api/server/services.ts +++ b/server/tests/api/server/services.ts @@ -4,8 +4,6 @@ import 'mocha' import * as chai from 'chai' import { Video, VideoPlaylistPrivacy } from '@shared/models' import { - addVideoInPlaylist, - createVideoPlaylist, getVideosList, ServerInfo, setAccessTokensToServers, @@ -41,24 +39,20 @@ describe('Test services', function () { } { - const res = await createVideoPlaylist({ - url: server.url, - token: server.accessToken, - playlistAttrs: { + const created = await server.playlistsCommand.create({ + attributes: { displayName: 'The Life and Times of Scrooge McDuck', privacy: VideoPlaylistPrivacy.PUBLIC, videoChannelId: server.videoChannel.id } }) - playlistUUID = res.body.videoPlaylist.uuid + playlistUUID = created.uuid playlistDisplayName = 'The Life and Times of Scrooge McDuck' - await addVideoInPlaylist({ - url: server.url, - token: server.accessToken, - playlistId: res.body.videoPlaylist.id, - elementAttrs: { + await server.playlistsCommand.addElement({ + playlistId: created.id, + attributes: { videoId: video.id } }) diff --git a/server/tests/api/server/stats.ts b/server/tests/api/server/stats.ts index f01188d67..c877a65eb 100644 --- a/server/tests/api/server/stats.ts +++ b/server/tests/api/server/stats.ts @@ -7,7 +7,6 @@ import { addVideoCommentThread, cleanupTests, createUser, - createVideoPlaylist, doubleFollow, flushAndRunMultipleServers, ServerInfo, @@ -178,10 +177,8 @@ describe('Test stats (excluding redundancy)', function () { } { - await createVideoPlaylist({ - url: server.url, - token: server.accessToken, - playlistAttrs: { + await server.playlistsCommand.create({ + attributes: { displayName: 'playlist for count', privacy: VideoPlaylistPrivacy.PUBLIC, videoChannelId: channelId diff --git a/server/tests/api/videos/video-playlist-thumbnails.ts b/server/tests/api/videos/video-playlist-thumbnails.ts index a93a0b7de..af5df8d90 100644 --- a/server/tests/api/videos/video-playlist-thumbnails.ts +++ b/server/tests/api/videos/video-playlist-thumbnails.ts @@ -1,16 +1,11 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ -import * as chai from 'chai' import 'mocha' +import * as chai from 'chai' import { - addVideoInPlaylist, cleanupTests, - createVideoPlaylist, doubleFollow, flushAndRunMultipleServers, - getVideoPlaylistsList, - removeVideoFromPlaylist, - reorderVideosPlaylist, ServerInfo, setAccessTokensToServers, setDefaultVideoChannel, @@ -25,8 +20,8 @@ const expect = chai.expect describe('Playlist thumbnail', function () { let servers: ServerInfo[] = [] - let playlistWithoutThumbnail: number - let playlistWithThumbnail: number + let playlistWithoutThumbnailId: number + let playlistWithThumbnailId: number let withThumbnailE1: number let withThumbnailE2: number @@ -37,15 +32,15 @@ describe('Playlist thumbnail', function () { let video2: number async function getPlaylistWithoutThumbnail (server: ServerInfo) { - const res = await getVideoPlaylistsList(server.url, 0, 10) + const body = await server.playlistsCommand.list({ start: 0, count: 10 }) - return res.body.data.find(p => p.displayName === 'playlist without thumbnail') + return body.data.find(p => p.displayName === 'playlist without thumbnail') } async function getPlaylistWithThumbnail (server: ServerInfo) { - const res = await getVideoPlaylistsList(server.url, 0, 10) + const body = await server.playlistsCommand.list({ start: 0, count: 10 }) - return res.body.data.find(p => p.displayName === 'playlist with thumbnail') + return body.data.find(p => p.displayName === 'playlist with thumbnail') } before(async function () { @@ -69,24 +64,20 @@ describe('Playlist thumbnail', function () { it('Should automatically update the thumbnail when adding an element', async function () { this.timeout(30000) - const res = await createVideoPlaylist({ - url: servers[1].url, - token: servers[1].accessToken, - playlistAttrs: { + const created = await servers[1].playlistsCommand.create({ + attributes: { displayName: 'playlist without thumbnail', privacy: VideoPlaylistPrivacy.PUBLIC, videoChannelId: servers[1].videoChannel.id } }) - playlistWithoutThumbnail = res.body.videoPlaylist.id + playlistWithoutThumbnailId = created.id - const res2 = await addVideoInPlaylist({ - url: servers[1].url, - token: servers[1].accessToken, - playlistId: playlistWithoutThumbnail, - elementAttrs: { videoId: video1 } + const added = await servers[1].playlistsCommand.addElement({ + playlistId: playlistWithoutThumbnailId, + attributes: { videoId: video1 } }) - withoutThumbnailE1 = res2.body.videoPlaylistElement.id + withoutThumbnailE1 = added.id await waitJobs(servers) @@ -99,25 +90,21 @@ describe('Playlist thumbnail', function () { it('Should not update the thumbnail if we explicitly uploaded a thumbnail', async function () { this.timeout(30000) - const res = await createVideoPlaylist({ - url: servers[1].url, - token: servers[1].accessToken, - playlistAttrs: { + const created = await servers[1].playlistsCommand.create({ + attributes: { displayName: 'playlist with thumbnail', privacy: VideoPlaylistPrivacy.PUBLIC, videoChannelId: servers[1].videoChannel.id, thumbnailfile: 'thumbnail.jpg' } }) - playlistWithThumbnail = res.body.videoPlaylist.id + playlistWithThumbnailId = created.id - const res2 = await addVideoInPlaylist({ - url: servers[1].url, - token: servers[1].accessToken, - playlistId: playlistWithThumbnail, - elementAttrs: { videoId: video1 } + const added = await servers[1].playlistsCommand.addElement({ + playlistId: playlistWithThumbnailId, + attributes: { videoId: video1 } }) - withThumbnailE1 = res2.body.videoPlaylistElement.id + withThumbnailE1 = added.id await waitJobs(servers) @@ -130,19 +117,15 @@ describe('Playlist thumbnail', function () { it('Should automatically update the thumbnail when moving the first element', async function () { this.timeout(30000) - const res = await addVideoInPlaylist({ - url: servers[1].url, - token: servers[1].accessToken, - playlistId: playlistWithoutThumbnail, - elementAttrs: { videoId: video2 } + const added = await servers[1].playlistsCommand.addElement({ + playlistId: playlistWithoutThumbnailId, + attributes: { videoId: video2 } }) - withoutThumbnailE2 = res.body.videoPlaylistElement.id + withoutThumbnailE2 = added.id - await reorderVideosPlaylist({ - url: servers[1].url, - token: servers[1].accessToken, - playlistId: playlistWithoutThumbnail, - elementAttrs: { + await servers[1].playlistsCommand.reorderElements({ + playlistId: playlistWithoutThumbnailId, + attributes: { startPosition: 1, insertAfterPosition: 2 } @@ -159,19 +142,15 @@ describe('Playlist thumbnail', function () { it('Should not update the thumbnail when moving the first element if we explicitly uploaded a thumbnail', async function () { this.timeout(30000) - const res = await addVideoInPlaylist({ - url: servers[1].url, - token: servers[1].accessToken, - playlistId: playlistWithThumbnail, - elementAttrs: { videoId: video2 } + const added = await servers[1].playlistsCommand.addElement({ + playlistId: playlistWithThumbnailId, + attributes: { videoId: video2 } }) - withThumbnailE2 = res.body.videoPlaylistElement.id + withThumbnailE2 = added.id - await reorderVideosPlaylist({ - url: servers[1].url, - token: servers[1].accessToken, - playlistId: playlistWithThumbnail, - elementAttrs: { + await servers[1].playlistsCommand.reorderElements({ + playlistId: playlistWithThumbnailId, + attributes: { startPosition: 1, insertAfterPosition: 2 } @@ -188,11 +167,9 @@ describe('Playlist thumbnail', function () { it('Should automatically update the thumbnail when deleting the first element', async function () { this.timeout(30000) - await removeVideoFromPlaylist({ - url: servers[1].url, - token: servers[1].accessToken, - playlistId: playlistWithoutThumbnail, - playlistElementId: withoutThumbnailE1 + await servers[1].playlistsCommand.removeElement({ + playlistId: playlistWithoutThumbnailId, + elementId: withoutThumbnailE1 }) await waitJobs(servers) @@ -206,11 +183,9 @@ describe('Playlist thumbnail', function () { it('Should not update the thumbnail when deleting the first element if we explicitly uploaded a thumbnail', async function () { this.timeout(30000) - await removeVideoFromPlaylist({ - url: servers[1].url, - token: servers[1].accessToken, - playlistId: playlistWithThumbnail, - playlistElementId: withThumbnailE1 + await servers[1].playlistsCommand.removeElement({ + playlistId: playlistWithThumbnailId, + elementId: withThumbnailE1 }) await waitJobs(servers) @@ -224,11 +199,9 @@ describe('Playlist thumbnail', function () { it('Should the thumbnail when we delete the last element', async function () { this.timeout(30000) - await removeVideoFromPlaylist({ - url: servers[1].url, - token: servers[1].accessToken, - playlistId: playlistWithoutThumbnail, - playlistElementId: withoutThumbnailE2 + await servers[1].playlistsCommand.removeElement({ + playlistId: playlistWithoutThumbnailId, + elementId: withoutThumbnailE2 }) await waitJobs(servers) @@ -242,11 +215,9 @@ describe('Playlist thumbnail', function () { it('Should not update the thumbnail when we delete the last element if we explicitly uploaded a thumbnail', async function () { this.timeout(30000) - await removeVideoFromPlaylist({ - url: servers[1].url, - token: servers[1].accessToken, - playlistId: playlistWithThumbnail, - playlistElementId: withThumbnailE2 + await servers[1].playlistsCommand.removeElement({ + playlistId: playlistWithThumbnailId, + elementId: withThumbnailE2 }) await waitJobs(servers) diff --git a/server/tests/api/videos/video-playlists.ts b/server/tests/api/videos/video-playlists.ts index 069450453..4de6b3abf 100644 --- a/server/tests/api/videos/video-playlists.ts +++ b/server/tests/api/videos/video-playlists.ts @@ -5,37 +5,22 @@ import * as chai from 'chai' import { HttpStatusCode } from '@shared/core-utils' import { addVideoChannel, - addVideoInPlaylist, checkPlaylistFilesWereRemoved, cleanupTests, createUser, - createVideoPlaylist, deleteVideoChannel, - deleteVideoPlaylist, doubleFollow, - doVideosExistInMyPlaylist, flushAndRunMultipleServers, generateUserAccessToken, getAccessToken, - getAccountPlaylistsList, - getAccountPlaylistsListWithToken, getMyUserInformation, - getPlaylistVideos, - getVideoChannelPlaylistsList, - getVideoPlaylist, - getVideoPlaylistPrivacies, - getVideoPlaylistsList, - getVideoPlaylistWithToken, + PlaylistsCommand, removeUser, - removeVideoFromPlaylist, - reorderVideosPlaylist, ServerInfo, setAccessTokensToServers, setDefaultVideoChannel, testImage, updateVideo, - updateVideoPlaylist, - updateVideoPlaylistElement, uploadVideo, uploadVideoAndGetId, userLogin, @@ -44,10 +29,8 @@ import { } from '@shared/extra-utils' import { User, - VideoExistInPlaylist, VideoPlaylist, VideoPlaylistCreateResult, - VideoPlaylistElement, VideoPlaylistElementType, VideoPlaylistPrivacy, VideoPlaylistType, @@ -65,10 +48,10 @@ async function checkPlaylistElementType ( total: number ) { for (const server of servers) { - const res = await getPlaylistVideos(server.url, server.accessToken, playlistId, 0, 10) - expect(res.body.total).to.equal(total) + const body = await server.playlistsCommand.listVideos({ token: server.accessToken, playlistId, start: 0, count: 10 }) + expect(body.total).to.equal(total) - const videoElement: VideoPlaylistElement = res.body.data.find((e: VideoPlaylistElement) => e.position === position) + const videoElement = body.data.find(e => e.position === position) expect(videoElement.type).to.equal(type, 'On server ' + server.url) if (type === VideoPlaylistElementType.REGULAR) { @@ -85,7 +68,7 @@ describe('Test video playlists', function () { let playlistServer2Id1: number let playlistServer2Id2: number - let playlistServer2UUID2: number + let playlistServer2UUID2: string let playlistServer1Id: number let playlistServer1UUID: string @@ -97,7 +80,9 @@ describe('Test video playlists', function () { let nsfwVideoServer1: number - let userAccessTokenServer1: string + let userTokenServer1: string + + let commands: PlaylistsCommand[] before(async function () { this.timeout(120000) @@ -113,6 +98,8 @@ describe('Test video playlists', function () { // Server 1 and server 3 follow each other await doubleFollow(servers[0], servers[2]) + commands = servers.map(s => s.playlistsCommand) + { servers[0].videos = [] servers[1].videos = [] @@ -137,62 +124,60 @@ describe('Test video playlists', function () { username: 'user1', password: 'password' }) - userAccessTokenServer1 = await getAccessToken(servers[0].url, 'user1', 'password') + userTokenServer1 = await getAccessToken(servers[0].url, 'user1', 'password') } await waitJobs(servers) }) describe('Get default playlists', function () { + it('Should list video playlist privacies', async function () { - const res = await getVideoPlaylistPrivacies(servers[0].url) + const privacies = await commands[0].getPrivacies() - const privacies = res.body expect(Object.keys(privacies)).to.have.length.at.least(3) - expect(privacies[3]).to.equal('Private') }) it('Should list watch later playlist', async function () { - const url = servers[0].url - const accessToken = servers[0].accessToken + const token = servers[0].accessToken { - const res = await getAccountPlaylistsListWithToken(url, accessToken, 'root', 0, 5, VideoPlaylistType.WATCH_LATER) + const body = await commands[0].listByAccount({ token, handle: 'root', playlistType: VideoPlaylistType.WATCH_LATER }) - expect(res.body.total).to.equal(1) - expect(res.body.data).to.have.lengthOf(1) + expect(body.total).to.equal(1) + expect(body.data).to.have.lengthOf(1) - const playlist: VideoPlaylist = res.body.data[0] + const playlist = body.data[0] expect(playlist.displayName).to.equal('Watch later') expect(playlist.type.id).to.equal(VideoPlaylistType.WATCH_LATER) expect(playlist.type.label).to.equal('Watch later') } { - const res = await getAccountPlaylistsListWithToken(url, accessToken, 'root', 0, 5, VideoPlaylistType.REGULAR) + const body = await commands[0].listByAccount({ token, handle: 'root', playlistType: VideoPlaylistType.REGULAR }) - expect(res.body.total).to.equal(0) - expect(res.body.data).to.have.lengthOf(0) + expect(body.total).to.equal(0) + expect(body.data).to.have.lengthOf(0) } { - const res = await getAccountPlaylistsList(url, 'root', 0, 5) - expect(res.body.total).to.equal(0) - expect(res.body.data).to.have.lengthOf(0) + const body = await commands[0].listByAccount({ handle: 'root' }) + expect(body.total).to.equal(0) + expect(body.data).to.have.lengthOf(0) } }) it('Should get private playlist for a classic user', async function () { const token = await generateUserAccessToken(servers[0], 'toto') - const res = await getAccountPlaylistsListWithToken(servers[0].url, token, 'toto', 0, 5) + const body = await commands[0].listByAccount({ token, handle: 'toto' }) - expect(res.body.total).to.equal(1) - expect(res.body.data).to.have.lengthOf(1) + expect(body.total).to.equal(1) + expect(body.data).to.have.lengthOf(1) - const playlistId = res.body.data[0].id - await getPlaylistVideos(servers[0].url, token, playlistId, 0, 5) + const playlistId = body.data[0].id + await commands[0].listVideos({ token, playlistId }) }) }) @@ -201,10 +186,8 @@ describe('Test video playlists', function () { it('Should create a playlist on server 1 and have the playlist on server 2 and 3', async function () { this.timeout(30000) - await createVideoPlaylist({ - url: servers[0].url, - token: servers[0].accessToken, - playlistAttrs: { + await commands[0].create({ + attributes: { displayName: 'my super playlist', privacy: VideoPlaylistPrivacy.PUBLIC, description: 'my super description', @@ -218,14 +201,13 @@ describe('Test video playlists', function () { await wait(3000) for (const server of servers) { - const res = await getVideoPlaylistsList(server.url, 0, 5) - expect(res.body.total).to.equal(1) - expect(res.body.data).to.have.lengthOf(1) + const body = await server.playlistsCommand.list({ start: 0, count: 5 }) + expect(body.total).to.equal(1) + expect(body.data).to.have.lengthOf(1) - const playlistFromList = res.body.data[0] as VideoPlaylist + const playlistFromList = body.data[0] - const res2 = await getVideoPlaylist(server.url, playlistFromList.uuid) - const playlistFromGet = res2.body as VideoPlaylist + const playlistFromGet = await server.playlistsCommand.get({ playlistId: playlistFromList.uuid }) for (const playlist of [ playlistFromGet, playlistFromList ]) { expect(playlist.id).to.be.a('number') @@ -255,23 +237,19 @@ describe('Test video playlists', function () { this.timeout(30000) { - const res = await createVideoPlaylist({ - url: servers[1].url, - token: servers[1].accessToken, - playlistAttrs: { + const playlist = await servers[1].playlistsCommand.create({ + attributes: { displayName: 'playlist 2', privacy: VideoPlaylistPrivacy.PUBLIC, videoChannelId: servers[1].videoChannel.id } }) - playlistServer2Id1 = res.body.videoPlaylist.id + playlistServer2Id1 = playlist.id } { - const res = await createVideoPlaylist({ - url: servers[1].url, - token: servers[1].accessToken, - playlistAttrs: { + const playlist = await servers[1].playlistsCommand.create({ + attributes: { displayName: 'playlist 3', privacy: VideoPlaylistPrivacy.PUBLIC, thumbnailfile: 'thumbnail.jpg', @@ -279,22 +257,18 @@ describe('Test video playlists', function () { } }) - playlistServer2Id2 = res.body.videoPlaylist.id - playlistServer2UUID2 = res.body.videoPlaylist.uuid + playlistServer2Id2 = playlist.id + playlistServer2UUID2 = playlist.uuid } for (const id of [ playlistServer2Id1, playlistServer2Id2 ]) { - await addVideoInPlaylist({ - url: servers[1].url, - token: servers[1].accessToken, + await servers[1].playlistsCommand.addElement({ playlistId: id, - elementAttrs: { videoId: servers[1].videos[0].id, startTimestamp: 1, stopTimestamp: 2 } + attributes: { videoId: servers[1].videos[0].id, startTimestamp: 1, stopTimestamp: 2 } }) - await addVideoInPlaylist({ - url: servers[1].url, - token: servers[1].accessToken, + await servers[1].playlistsCommand.addElement({ playlistId: id, - elementAttrs: { videoId: servers[1].videos[1].id } + attributes: { videoId: servers[1].videos[1].id } }) } @@ -302,20 +276,20 @@ describe('Test video playlists', function () { await wait(3000) for (const server of [ servers[0], servers[1] ]) { - const res = await getVideoPlaylistsList(server.url, 0, 5) + const body = await server.playlistsCommand.list({ start: 0, count: 5 }) - const playlist2 = res.body.data.find(p => p.displayName === 'playlist 2') + const playlist2 = body.data.find(p => p.displayName === 'playlist 2') expect(playlist2).to.not.be.undefined await testImage(server.url, 'thumbnail-playlist', playlist2.thumbnailPath) - const playlist3 = res.body.data.find(p => p.displayName === 'playlist 3') + const playlist3 = body.data.find(p => p.displayName === 'playlist 3') expect(playlist3).to.not.be.undefined await testImage(server.url, 'thumbnail', playlist3.thumbnailPath) } - const res = await getVideoPlaylistsList(servers[2].url, 0, 5) - expect(res.body.data.find(p => p.displayName === 'playlist 2')).to.be.undefined - expect(res.body.data.find(p => p.displayName === 'playlist 3')).to.be.undefined + const body = await servers[2].playlistsCommand.list({ start: 0, count: 5 }) + expect(body.data.find(p => p.displayName === 'playlist 2')).to.be.undefined + expect(body.data.find(p => p.displayName === 'playlist 3')).to.be.undefined }) it('Should have the playlist on server 3 after a new follow', async function () { @@ -324,13 +298,13 @@ describe('Test video playlists', function () { // Server 2 and server 3 follow each other await doubleFollow(servers[1], servers[2]) - const res = await getVideoPlaylistsList(servers[2].url, 0, 5) + const body = await servers[2].playlistsCommand.list({ start: 0, count: 5 }) - const playlist2 = res.body.data.find(p => p.displayName === 'playlist 2') + const playlist2 = body.data.find(p => p.displayName === 'playlist 2') expect(playlist2).to.not.be.undefined await testImage(servers[2].url, 'thumbnail-playlist', playlist2.thumbnailPath) - expect(res.body.data.find(p => p.displayName === 'playlist 3')).to.not.be.undefined + expect(body.data.find(p => p.displayName === 'playlist 3')).to.not.be.undefined }) }) @@ -340,22 +314,20 @@ describe('Test video playlists', function () { this.timeout(30000) { - const res = await getVideoPlaylistsList(servers[2].url, 1, 2, 'createdAt') + const body = await servers[2].playlistsCommand.list({ start: 1, count: 2, sort: 'createdAt' }) + expect(body.total).to.equal(3) - expect(res.body.total).to.equal(3) - - const data: VideoPlaylist[] = res.body.data + const data = body.data expect(data).to.have.lengthOf(2) expect(data[0].displayName).to.equal('playlist 2') expect(data[1].displayName).to.equal('playlist 3') } { - const res = await getVideoPlaylistsList(servers[2].url, 1, 2, '-createdAt') - - expect(res.body.total).to.equal(3) + const body = await servers[2].playlistsCommand.list({ start: 1, count: 2, sort: '-createdAt' }) + expect(body.total).to.equal(3) - const data: VideoPlaylist[] = res.body.data + const data = body.data expect(data).to.have.lengthOf(2) expect(data[0].displayName).to.equal('playlist 2') expect(data[1].displayName).to.equal('my super playlist') @@ -366,11 +338,10 @@ describe('Test video playlists', function () { this.timeout(30000) { - const res = await getVideoChannelPlaylistsList(servers[0].url, 'root_channel', 0, 2, '-createdAt') + const body = await commands[0].listByChannel({ handle: 'root_channel', start: 0, count: 2, sort: '-createdAt' }) + expect(body.total).to.equal(1) - expect(res.body.total).to.equal(1) - - const data: VideoPlaylist[] = res.body.data + const data = body.data expect(data).to.have.lengthOf(1) expect(data[0].displayName).to.equal('my super playlist') } @@ -380,41 +351,37 @@ describe('Test video playlists', function () { this.timeout(30000) { - const res = await getAccountPlaylistsList(servers[1].url, 'root', 1, 2, '-createdAt') - - expect(res.body.total).to.equal(2) + const body = await servers[1].playlistsCommand.listByAccount({ handle: 'root', start: 1, count: 2, sort: '-createdAt' }) + expect(body.total).to.equal(2) - const data: VideoPlaylist[] = res.body.data + const data = body.data expect(data).to.have.lengthOf(1) expect(data[0].displayName).to.equal('playlist 2') } { - const res = await getAccountPlaylistsList(servers[1].url, 'root', 1, 2, 'createdAt') + const body = await servers[1].playlistsCommand.listByAccount({ handle: 'root', start: 1, count: 2, sort: 'createdAt' }) + expect(body.total).to.equal(2) - expect(res.body.total).to.equal(2) - - const data: VideoPlaylist[] = res.body.data + const data = body.data expect(data).to.have.lengthOf(1) expect(data[0].displayName).to.equal('playlist 3') } { - const res = await getAccountPlaylistsList(servers[1].url, 'root', 0, 10, 'createdAt', '3') - - expect(res.body.total).to.equal(1) + const body = await servers[1].playlistsCommand.listByAccount({ handle: 'root', sort: 'createdAt', search: '3' }) + expect(body.total).to.equal(1) - const data: VideoPlaylist[] = res.body.data + const data = body.data expect(data).to.have.lengthOf(1) expect(data[0].displayName).to.equal('playlist 3') } { - const res = await getAccountPlaylistsList(servers[1].url, 'root', 0, 10, 'createdAt', '4') - - expect(res.body.total).to.equal(0) + const body = await servers[1].playlistsCommand.listByAccount({ handle: 'root', sort: 'createdAt', search: '4' }) + expect(body.total).to.equal(0) - const data: VideoPlaylist[] = res.body.data + const data = body.data expect(data).to.have.lengthOf(0) } }) @@ -428,28 +395,22 @@ describe('Test video playlists', function () { this.timeout(30000) { - const res = await createVideoPlaylist({ - url: servers[1].url, - token: servers[1].accessToken, - playlistAttrs: { + unlistedPlaylist = await servers[1].playlistsCommand.create({ + attributes: { displayName: 'playlist unlisted', privacy: VideoPlaylistPrivacy.UNLISTED, videoChannelId: servers[1].videoChannel.id } }) - unlistedPlaylist = res.body.videoPlaylist } { - const res = await createVideoPlaylist({ - url: servers[1].url, - token: servers[1].accessToken, - playlistAttrs: { + privatePlaylist = await servers[1].playlistsCommand.create({ + attributes: { displayName: 'playlist private', privacy: VideoPlaylistPrivacy.PRIVATE } }) - privatePlaylist = res.body.videoPlaylist } await waitJobs(servers) @@ -459,15 +420,15 @@ describe('Test video playlists', function () { it('Should not list unlisted or private playlists', async function () { for (const server of servers) { const results = [ - await getAccountPlaylistsList(server.url, 'root@localhost:' + servers[1].port, 0, 5, '-createdAt'), - await getVideoPlaylistsList(server.url, 0, 2, '-createdAt') + await server.playlistsCommand.listByAccount({ handle: 'root@localhost:' + servers[1].port, sort: '-createdAt' }), + await server.playlistsCommand.list({ start: 0, count: 2, sort: '-createdAt' }) ] - expect(results[0].body.total).to.equal(2) - expect(results[1].body.total).to.equal(3) + expect(results[0].total).to.equal(2) + expect(results[1].total).to.equal(3) - for (const res of results) { - const data: VideoPlaylist[] = res.body.data + for (const body of results) { + const data = body.data expect(data).to.have.lengthOf(2) expect(data[0].displayName).to.equal('playlist 3') expect(data[1].displayName).to.equal('playlist 2') @@ -476,23 +437,23 @@ describe('Test video playlists', function () { }) it('Should not get unlisted playlist using only the id', async function () { - await getVideoPlaylist(servers[1].url, unlistedPlaylist.id, 404) + await servers[1].playlistsCommand.get({ playlistId: unlistedPlaylist.id, expectedStatus: 404 }) }) it('Should get unlisted plyaylist using uuid or shortUUID', async function () { - await getVideoPlaylist(servers[1].url, unlistedPlaylist.uuid) - await getVideoPlaylist(servers[1].url, unlistedPlaylist.shortUUID) + await servers[1].playlistsCommand.get({ playlistId: unlistedPlaylist.uuid }) + await servers[1].playlistsCommand.get({ playlistId: unlistedPlaylist.shortUUID }) }) it('Should not get private playlist without token', async function () { for (const id of [ privatePlaylist.id, privatePlaylist.uuid, privatePlaylist.shortUUID ]) { - await getVideoPlaylist(servers[1].url, id, 401) + await servers[1].playlistsCommand.get({ playlistId: id, expectedStatus: 401 }) } }) it('Should get private playlist with a token', async function () { for (const id of [ privatePlaylist.id, privatePlaylist.uuid, privatePlaylist.shortUUID ]) { - await getVideoPlaylistWithToken(servers[1].url, servers[1].accessToken, id) + await servers[1].playlistsCommand.get({ token: servers[1].accessToken, playlistId: id }) } }) }) @@ -502,10 +463,8 @@ describe('Test video playlists', function () { it('Should update a playlist', async function () { this.timeout(30000) - await updateVideoPlaylist({ - url: servers[1].url, - token: servers[1].accessToken, - playlistAttrs: { + await servers[1].playlistsCommand.update({ + attributes: { displayName: 'playlist 3 updated', description: 'description updated', privacy: VideoPlaylistPrivacy.UNLISTED, @@ -518,8 +477,7 @@ describe('Test video playlists', function () { await waitJobs(servers) for (const server of servers) { - const res = await getVideoPlaylist(server.url, playlistServer2UUID2) - const playlist: VideoPlaylist = res.body + const playlist = await server.playlistsCommand.get({ playlistId: playlistServer2UUID2 }) expect(playlist.displayName).to.equal('playlist 3 updated') expect(playlist.description).to.equal('description updated') @@ -545,39 +503,37 @@ describe('Test video playlists', function () { it('Should create a playlist containing different startTimestamp/endTimestamp videos', async function () { this.timeout(30000) - const addVideo = (elementAttrs: any) => { - return addVideoInPlaylist({ url: servers[0].url, token: servers[0].accessToken, playlistId: playlistServer1Id, elementAttrs }) + const addVideo = (attributes: any) => { + return commands[0].addElement({ playlistId: playlistServer1Id, attributes }) } - const res = await createVideoPlaylist({ - url: servers[0].url, - token: servers[0].accessToken, - playlistAttrs: { + const playlist = await commands[0].create({ + attributes: { displayName: 'playlist 4', privacy: VideoPlaylistPrivacy.PUBLIC, videoChannelId: servers[0].videoChannel.id } }) - playlistServer1Id = res.body.videoPlaylist.id - playlistServer1UUID = res.body.videoPlaylist.uuid + playlistServer1Id = playlist.id + playlistServer1UUID = playlist.uuid await addVideo({ videoId: servers[0].videos[0].uuid, startTimestamp: 15, stopTimestamp: 28 }) await addVideo({ videoId: servers[2].videos[1].uuid, startTimestamp: 35 }) await addVideo({ videoId: servers[2].videos[2].uuid }) { - const res = await addVideo({ videoId: servers[0].videos[3].uuid, stopTimestamp: 35 }) - playlistElementServer1Video4 = res.body.videoPlaylistElement.id + const element = await addVideo({ videoId: servers[0].videos[3].uuid, stopTimestamp: 35 }) + playlistElementServer1Video4 = element.id } { - const res = await addVideo({ videoId: servers[0].videos[4].uuid, startTimestamp: 45, stopTimestamp: 60 }) - playlistElementServer1Video5 = res.body.videoPlaylistElement.id + const element = await addVideo({ videoId: servers[0].videos[4].uuid, startTimestamp: 45, stopTimestamp: 60 }) + playlistElementServer1Video5 = element.id } { - const res = await addVideo({ videoId: nsfwVideoServer1, startTimestamp: 5 }) - playlistElementNSFW = res.body.videoPlaylistElement.id + const element = await addVideo({ videoId: nsfwVideoServer1, startTimestamp: 5 }) + playlistElementNSFW = element.id await addVideo({ videoId: nsfwVideoServer1, startTimestamp: 4 }) await addVideo({ videoId: nsfwVideoServer1 }) @@ -590,55 +546,59 @@ describe('Test video playlists', function () { this.timeout(30000) for (const server of servers) { - const res = await getPlaylistVideos(server.url, server.accessToken, playlistServer1UUID, 0, 10) - - expect(res.body.total).to.equal(8) - - const videoElements: VideoPlaylistElement[] = res.body.data - expect(videoElements).to.have.lengthOf(8) - - expect(videoElements[0].video.name).to.equal('video 0 server 1') - expect(videoElements[0].position).to.equal(1) - expect(videoElements[0].startTimestamp).to.equal(15) - expect(videoElements[0].stopTimestamp).to.equal(28) - - expect(videoElements[1].video.name).to.equal('video 1 server 3') - expect(videoElements[1].position).to.equal(2) - expect(videoElements[1].startTimestamp).to.equal(35) - expect(videoElements[1].stopTimestamp).to.be.null - - expect(videoElements[2].video.name).to.equal('video 2 server 3') - expect(videoElements[2].position).to.equal(3) - expect(videoElements[2].startTimestamp).to.be.null - expect(videoElements[2].stopTimestamp).to.be.null - - expect(videoElements[3].video.name).to.equal('video 3 server 1') - expect(videoElements[3].position).to.equal(4) - expect(videoElements[3].startTimestamp).to.be.null - expect(videoElements[3].stopTimestamp).to.equal(35) - - expect(videoElements[4].video.name).to.equal('video 4 server 1') - expect(videoElements[4].position).to.equal(5) - expect(videoElements[4].startTimestamp).to.equal(45) - expect(videoElements[4].stopTimestamp).to.equal(60) - - expect(videoElements[5].video.name).to.equal('NSFW video') - expect(videoElements[5].position).to.equal(6) - expect(videoElements[5].startTimestamp).to.equal(5) - expect(videoElements[5].stopTimestamp).to.be.null - - expect(videoElements[6].video.name).to.equal('NSFW video') - expect(videoElements[6].position).to.equal(7) - expect(videoElements[6].startTimestamp).to.equal(4) - expect(videoElements[6].stopTimestamp).to.be.null - - expect(videoElements[7].video.name).to.equal('NSFW video') - expect(videoElements[7].position).to.equal(8) - expect(videoElements[7].startTimestamp).to.be.null - expect(videoElements[7].stopTimestamp).to.be.null - - const res3 = await getPlaylistVideos(server.url, server.accessToken, playlistServer1UUID, 0, 2) - expect(res3.body.data).to.have.lengthOf(2) + { + const body = await server.playlistsCommand.listVideos({ playlistId: playlistServer1UUID, start: 0, count: 10 }) + + expect(body.total).to.equal(8) + + const videoElements = body.data + expect(videoElements).to.have.lengthOf(8) + + expect(videoElements[0].video.name).to.equal('video 0 server 1') + expect(videoElements[0].position).to.equal(1) + expect(videoElements[0].startTimestamp).to.equal(15) + expect(videoElements[0].stopTimestamp).to.equal(28) + + expect(videoElements[1].video.name).to.equal('video 1 server 3') + expect(videoElements[1].position).to.equal(2) + expect(videoElements[1].startTimestamp).to.equal(35) + expect(videoElements[1].stopTimestamp).to.be.null + + expect(videoElements[2].video.name).to.equal('video 2 server 3') + expect(videoElements[2].position).to.equal(3) + expect(videoElements[2].startTimestamp).to.be.null + expect(videoElements[2].stopTimestamp).to.be.null + + expect(videoElements[3].video.name).to.equal('video 3 server 1') + expect(videoElements[3].position).to.equal(4) + expect(videoElements[3].startTimestamp).to.be.null + expect(videoElements[3].stopTimestamp).to.equal(35) + + expect(videoElements[4].video.name).to.equal('video 4 server 1') + expect(videoElements[4].position).to.equal(5) + expect(videoElements[4].startTimestamp).to.equal(45) + expect(videoElements[4].stopTimestamp).to.equal(60) + + expect(videoElements[5].video.name).to.equal('NSFW video') + expect(videoElements[5].position).to.equal(6) + expect(videoElements[5].startTimestamp).to.equal(5) + expect(videoElements[5].stopTimestamp).to.be.null + + expect(videoElements[6].video.name).to.equal('NSFW video') + expect(videoElements[6].position).to.equal(7) + expect(videoElements[6].startTimestamp).to.equal(4) + expect(videoElements[6].stopTimestamp).to.be.null + + expect(videoElements[7].video.name).to.equal('NSFW video') + expect(videoElements[7].position).to.equal(8) + expect(videoElements[7].startTimestamp).to.be.null + expect(videoElements[7].stopTimestamp).to.be.null + } + + { + const body = await server.playlistsCommand.listVideos({ playlistId: playlistServer1UUID, start: 0, count: 2 }) + expect(body.data).to.have.lengthOf(2) + } } }) }) @@ -656,29 +616,28 @@ describe('Test video playlists', function () { before(async function () { this.timeout(60000) - groupUser1 = [ Object.assign({}, servers[0], { accessToken: userAccessTokenServer1 }) ] + groupUser1 = [ Object.assign({}, servers[0], { accessToken: userTokenServer1 }) ] groupWithoutToken1 = [ Object.assign({}, servers[0], { accessToken: undefined }) ] group1 = [ servers[0] ] group2 = [ servers[1], servers[2] ] - const res = await createVideoPlaylist({ - url: servers[0].url, - token: userAccessTokenServer1, - playlistAttrs: { + const playlist = await commands[0].create({ + token: userTokenServer1, + attributes: { displayName: 'playlist 56', privacy: VideoPlaylistPrivacy.PUBLIC, videoChannelId: servers[0].videoChannel.id } }) - const playlistServer1Id2 = res.body.videoPlaylist.id - playlistServer1UUID2 = res.body.videoPlaylist.uuid + const playlistServer1Id2 = playlist.id + playlistServer1UUID2 = playlist.uuid - const addVideo = (elementAttrs: any) => { - return addVideoInPlaylist({ url: servers[0].url, token: userAccessTokenServer1, playlistId: playlistServer1Id2, elementAttrs }) + const addVideo = (attributes: any) => { + return commands[0].addElement({ token: userTokenServer1, playlistId: playlistServer1Id2, attributes }) } - video1 = (await uploadVideoAndGetId({ server: servers[0], videoName: 'video 89', token: userAccessTokenServer1 })).uuid + video1 = (await uploadVideoAndGetId({ server: servers[0], videoName: 'video 89', token: userTokenServer1 })).uuid video2 = (await uploadVideoAndGetId({ server: servers[1], videoName: 'video 90' })).uuid video3 = (await uploadVideoAndGetId({ server: servers[0], videoName: 'video 91', nsfw: true })).uuid @@ -756,26 +715,26 @@ describe('Test video playlists', function () { const position = 2 { - await command.addToMyBlocklist({ token: userAccessTokenServer1, account: 'root@localhost:' + servers[1].port }) + await command.addToMyBlocklist({ token: userTokenServer1, account: 'root@localhost:' + servers[1].port }) await waitJobs(servers) await checkPlaylistElementType(groupUser1, playlistServer1UUID2, VideoPlaylistElementType.UNAVAILABLE, position, name, 3) await checkPlaylistElementType(group2, playlistServer1UUID2, VideoPlaylistElementType.REGULAR, position, name, 3) - await command.removeFromMyBlocklist({ token: userAccessTokenServer1, account: 'root@localhost:' + servers[1].port }) + await command.removeFromMyBlocklist({ token: userTokenServer1, account: 'root@localhost:' + servers[1].port }) await waitJobs(servers) await checkPlaylistElementType(group2, playlistServer1UUID2, VideoPlaylistElementType.REGULAR, position, name, 3) } { - await command.addToMyBlocklist({ token: userAccessTokenServer1, server: 'localhost:' + servers[1].port }) + await command.addToMyBlocklist({ token: userTokenServer1, server: 'localhost:' + servers[1].port }) await waitJobs(servers) await checkPlaylistElementType(groupUser1, playlistServer1UUID2, VideoPlaylistElementType.UNAVAILABLE, position, name, 3) await checkPlaylistElementType(group2, playlistServer1UUID2, VideoPlaylistElementType.REGULAR, position, name, 3) - await command.removeFromMyBlocklist({ token: userAccessTokenServer1, server: 'localhost:' + servers[1].port }) + await command.removeFromMyBlocklist({ token: userTokenServer1, server: 'localhost:' + servers[1].port }) await waitJobs(servers) await checkPlaylistElementType(group2, playlistServer1UUID2, VideoPlaylistElementType.REGULAR, position, name, 3) @@ -809,10 +768,10 @@ describe('Test video playlists', function () { }) it('Should hide the video if it is NSFW', async function () { - const res = await getPlaylistVideos(servers[0].url, userAccessTokenServer1, playlistServer1UUID2, 0, 10, { nsfw: false }) - expect(res.body.total).to.equal(3) + const body = await commands[0].listVideos({ token: userTokenServer1, playlistId: playlistServer1UUID2, query: { nsfw: 'false' } }) + expect(body.total).to.equal(3) - const elements: VideoPlaylistElement[] = res.body.data + const elements = body.data const element = elements.find(e => e.position === 3) expect(element).to.exist @@ -828,11 +787,9 @@ describe('Test video playlists', function () { this.timeout(30000) { - await reorderVideosPlaylist({ - url: servers[0].url, - token: servers[0].accessToken, + await commands[0].reorderElements({ playlistId: playlistServer1Id, - elementAttrs: { + attributes: { startPosition: 2, insertAfterPosition: 3 } @@ -841,8 +798,8 @@ describe('Test video playlists', function () { await waitJobs(servers) for (const server of servers) { - const res = await getPlaylistVideos(server.url, server.accessToken, playlistServer1UUID, 0, 10) - const names = (res.body.data as VideoPlaylistElement[]).map(v => v.video.name) + const body = await server.playlistsCommand.listVideos({ playlistId: playlistServer1UUID, start: 0, count: 10 }) + const names = body.data.map(v => v.video.name) expect(names).to.deep.equal([ 'video 0 server 1', @@ -858,11 +815,9 @@ describe('Test video playlists', function () { } { - await reorderVideosPlaylist({ - url: servers[0].url, - token: servers[0].accessToken, + await commands[0].reorderElements({ playlistId: playlistServer1Id, - elementAttrs: { + attributes: { startPosition: 1, reorderLength: 3, insertAfterPosition: 4 @@ -872,8 +827,8 @@ describe('Test video playlists', function () { await waitJobs(servers) for (const server of servers) { - const res = await getPlaylistVideos(server.url, server.accessToken, playlistServer1UUID, 0, 10) - const names = (res.body.data as VideoPlaylistElement[]).map(v => v.video.name) + const body = await server.playlistsCommand.listVideos({ playlistId: playlistServer1UUID, start: 0, count: 10 }) + const names = body.data.map(v => v.video.name) expect(names).to.deep.equal([ 'video 3 server 1', @@ -889,11 +844,9 @@ describe('Test video playlists', function () { } { - await reorderVideosPlaylist({ - url: servers[0].url, - token: servers[0].accessToken, + await commands[0].reorderElements({ playlistId: playlistServer1Id, - elementAttrs: { + attributes: { startPosition: 6, insertAfterPosition: 3 } @@ -902,8 +855,7 @@ describe('Test video playlists', function () { await waitJobs(servers) for (const server of servers) { - const res = await getPlaylistVideos(server.url, server.accessToken, playlistServer1UUID, 0, 10) - const elements: VideoPlaylistElement[] = res.body.data + const { data: elements } = await server.playlistsCommand.listVideos({ playlistId: playlistServer1UUID, start: 0, count: 10 }) const names = elements.map(v => v.video.name) expect(names).to.deep.equal([ @@ -927,22 +879,18 @@ describe('Test video playlists', function () { it('Should update startTimestamp/endTimestamp of some elements', async function () { this.timeout(30000) - await updateVideoPlaylistElement({ - url: servers[0].url, - token: servers[0].accessToken, + await commands[0].updateElement({ playlistId: playlistServer1Id, - playlistElementId: playlistElementServer1Video4, - elementAttrs: { + elementId: playlistElementServer1Video4, + attributes: { startTimestamp: 1 } }) - await updateVideoPlaylistElement({ - url: servers[0].url, - token: servers[0].accessToken, + await commands[0].updateElement({ playlistId: playlistServer1Id, - playlistElementId: playlistElementServer1Video5, - elementAttrs: { + elementId: playlistElementServer1Video5, + attributes: { stopTimestamp: null } }) @@ -950,8 +898,7 @@ describe('Test video playlists', function () { await waitJobs(servers) for (const server of servers) { - const res = await getPlaylistVideos(server.url, server.accessToken, playlistServer1UUID, 0, 10) - const elements: VideoPlaylistElement[] = res.body.data + const { data: elements } = await server.playlistsCommand.listVideos({ playlistId: playlistServer1UUID, start: 0, count: 10 }) expect(elements[0].video.name).to.equal('video 3 server 1') expect(elements[0].position).to.equal(1) @@ -973,8 +920,7 @@ describe('Test video playlists', function () { 43000, servers[0].videos[4].id ] - const res = await doVideosExistInMyPlaylist(servers[0].url, servers[0].accessToken, videoIds) - const obj = res.body as VideoExistInPlaylist + const obj = await commands[0].videosExist({ videoIds }) { const elem = obj[servers[0].videos[0].id] @@ -1011,39 +957,26 @@ describe('Test video playlists', function () { const videoId = servers[1].videos[5].id async function getPlaylistNames () { - const res = await getAccountPlaylistsListWithToken(server.url, server.accessToken, 'root', 0, 5, undefined, '-updatedAt') + const { data } = await server.playlistsCommand.listByAccount({ token: server.accessToken, handle: 'root', sort: '-updatedAt' }) - return (res.body.data as VideoPlaylist[]).map(p => p.displayName) + return data.map(p => p.displayName) } - const elementAttrs = { videoId } - const res1 = await addVideoInPlaylist({ url: server.url, token: server.accessToken, playlistId: playlistServer2Id1, elementAttrs }) - const res2 = await addVideoInPlaylist({ url: server.url, token: server.accessToken, playlistId: playlistServer2Id2, elementAttrs }) - - const element1 = res1.body.videoPlaylistElement.id - const element2 = res2.body.videoPlaylistElement.id + const attributes = { videoId } + const element1 = await server.playlistsCommand.addElement({ playlistId: playlistServer2Id1, attributes }) + const element2 = await server.playlistsCommand.addElement({ playlistId: playlistServer2Id2, attributes }) const names1 = await getPlaylistNames() expect(names1[0]).to.equal('playlist 3 updated') expect(names1[1]).to.equal('playlist 2') - await removeVideoFromPlaylist({ - url: server.url, - token: server.accessToken, - playlistId: playlistServer2Id1, - playlistElementId: element1 - }) + await server.playlistsCommand.removeElement({ playlistId: playlistServer2Id1, elementId: element1.id }) const names2 = await getPlaylistNames() expect(names2[0]).to.equal('playlist 2') expect(names2[1]).to.equal('playlist 3 updated') - await removeVideoFromPlaylist({ - url: server.url, - token: server.accessToken, - playlistId: playlistServer2Id2, - playlistElementId: element2 - }) + await server.playlistsCommand.removeElement({ playlistId: playlistServer2Id2, elementId: element2.id }) const names3 = await getPlaylistNames() expect(names3[0]).to.equal('playlist 3 updated') @@ -1053,28 +986,16 @@ describe('Test video playlists', function () { it('Should delete some elements', async function () { this.timeout(30000) - await removeVideoFromPlaylist({ - url: servers[0].url, - token: servers[0].accessToken, - playlistId: playlistServer1Id, - playlistElementId: playlistElementServer1Video4 - }) - - await removeVideoFromPlaylist({ - url: servers[0].url, - token: servers[0].accessToken, - playlistId: playlistServer1Id, - playlistElementId: playlistElementNSFW - }) + await commands[0].removeElement({ playlistId: playlistServer1Id, elementId: playlistElementServer1Video4 }) + await commands[0].removeElement({ playlistId: playlistServer1Id, elementId: playlistElementNSFW }) await waitJobs(servers) for (const server of servers) { - const res = await getPlaylistVideos(server.url, server.accessToken, playlistServer1UUID, 0, 10) - - expect(res.body.total).to.equal(6) + const body = await server.playlistsCommand.listVideos({ playlistId: playlistServer1UUID, start: 0, count: 10 }) + expect(body.total).to.equal(6) - const elements: VideoPlaylistElement[] = res.body.data + const elements = body.data expect(elements).to.have.lengthOf(6) expect(elements[0].video.name).to.equal('video 0 server 1') @@ -1100,34 +1021,31 @@ describe('Test video playlists', function () { it('Should be able to create a public playlist, and set it to private', async function () { this.timeout(30000) - const res = await createVideoPlaylist({ - url: servers[0].url, - token: servers[0].accessToken, - playlistAttrs: { + const videoPlaylistIds = await commands[0].create({ + attributes: { displayName: 'my super public playlist', privacy: VideoPlaylistPrivacy.PUBLIC, videoChannelId: servers[0].videoChannel.id } }) - const videoPlaylistIds = res.body.videoPlaylist await waitJobs(servers) for (const server of servers) { - await getVideoPlaylist(server.url, videoPlaylistIds.uuid, HttpStatusCode.OK_200) + await server.playlistsCommand.get({ playlistId: videoPlaylistIds.uuid, expectedStatus: HttpStatusCode.OK_200 }) } - const playlistAttrs = { privacy: VideoPlaylistPrivacy.PRIVATE } - await updateVideoPlaylist({ url: servers[0].url, token: servers[0].accessToken, playlistId: videoPlaylistIds.id, playlistAttrs }) + const attributes = { privacy: VideoPlaylistPrivacy.PRIVATE } + await commands[0].update({ playlistId: videoPlaylistIds.id, attributes }) await waitJobs(servers) for (const server of [ servers[1], servers[2] ]) { - await getVideoPlaylist(server.url, videoPlaylistIds.uuid, HttpStatusCode.NOT_FOUND_404) + await server.playlistsCommand.get({ playlistId: videoPlaylistIds.uuid, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) } - await getVideoPlaylist(servers[0].url, videoPlaylistIds.uuid, HttpStatusCode.UNAUTHORIZED_401) - await getVideoPlaylistWithToken(servers[0].url, servers[0].accessToken, videoPlaylistIds.uuid, HttpStatusCode.OK_200) + await commands[0].get({ playlistId: videoPlaylistIds.uuid, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) + await commands[0].get({ token: servers[0].accessToken, playlistId: videoPlaylistIds.uuid, expectedStatus: HttpStatusCode.OK_200 }) }) }) @@ -1136,12 +1054,12 @@ describe('Test video playlists', function () { it('Should delete the playlist on server 1 and delete on server 2 and 3', async function () { this.timeout(30000) - await deleteVideoPlaylist(servers[0].url, servers[0].accessToken, playlistServer1Id) + await commands[0].delete({ playlistId: playlistServer1Id }) await waitJobs(servers) for (const server of servers) { - await getVideoPlaylist(server.url, playlistServer1UUID, HttpStatusCode.NOT_FOUND_404) + await server.playlistsCommand.get({ playlistId: playlistServer1UUID, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) } }) @@ -1156,21 +1074,22 @@ describe('Test video playlists', function () { it('Should unfollow servers 1 and 2 and hide their playlists', async function () { this.timeout(30000) - const finder = data => data.find(p => p.displayName === 'my super playlist') + const finder = (data: VideoPlaylist[]) => data.find(p => p.displayName === 'my super playlist') { - const res = await getVideoPlaylistsList(servers[2].url, 0, 5) - expect(res.body.total).to.equal(3) - expect(finder(res.body.data)).to.not.be.undefined + const body = await servers[2].playlistsCommand.list({ start: 0, count: 5 }) + expect(body.total).to.equal(3) + + expect(finder(body.data)).to.not.be.undefined } await servers[2].followsCommand.unfollow({ target: servers[0] }) { - const res = await getVideoPlaylistsList(servers[2].url, 0, 5) - expect(res.body.total).to.equal(1) + const body = await servers[2].playlistsCommand.list({ start: 0, count: 5 }) + expect(body.total).to.equal(1) - expect(finder(res.body.data)).to.be.undefined + expect(finder(body.data)).to.be.undefined } }) @@ -1180,16 +1099,13 @@ describe('Test video playlists', function () { const res = await addVideoChannel(servers[0].url, servers[0].accessToken, { name: 'super_channel', displayName: 'super channel' }) const videoChannelId = res.body.videoChannel.id - const res2 = await createVideoPlaylist({ - url: servers[0].url, - token: servers[0].accessToken, - playlistAttrs: { + const playlistCreated = await commands[0].create({ + attributes: { displayName: 'channel playlist', privacy: VideoPlaylistPrivacy.PUBLIC, videoChannelId } }) - const videoPlaylistUUID = res2.body.videoPlaylist.uuid await waitJobs(servers) @@ -1197,11 +1113,11 @@ describe('Test video playlists', function () { await waitJobs(servers) - const res3 = await getVideoPlaylistWithToken(servers[0].url, servers[0].accessToken, videoPlaylistUUID) - expect(res3.body.displayName).to.equal('channel playlist') - expect(res3.body.privacy.id).to.equal(VideoPlaylistPrivacy.PRIVATE) + const body = await commands[0].get({ token: servers[0].accessToken, playlistId: playlistCreated.uuid }) + expect(body.displayName).to.equal('channel playlist') + expect(body.privacy.id).to.equal(VideoPlaylistPrivacy.PRIVATE) - await getVideoPlaylist(servers[1].url, videoPlaylistUUID, HttpStatusCode.NOT_FOUND_404) + await servers[1].playlistsCommand.get({ playlistId: playlistCreated.uuid, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) it('Should delete an account and delete its playlists', async function () { @@ -1221,10 +1137,8 @@ describe('Test video playlists', function () { const resChannel = await getMyUserInformation(servers[0].url, userAccessToken) const userChannel = (resChannel.body as User).videoChannels[0] - await createVideoPlaylist({ - url: servers[0].url, - token: userAccessToken, - playlistAttrs: { + await commands[0].create({ + attributes: { displayName: 'playlist to be deleted', privacy: VideoPlaylistPrivacy.PUBLIC, videoChannelId: userChannel.id @@ -1233,12 +1147,13 @@ describe('Test video playlists', function () { await waitJobs(servers) - const finder = data => data.find(p => p.displayName === 'playlist to be deleted') + const finder = (data: VideoPlaylist[]) => data.find(p => p.displayName === 'playlist to be deleted') { for (const server of [ servers[0], servers[1] ]) { - const res = await getVideoPlaylistsList(server.url, 0, 15) - expect(finder(res.body.data)).to.not.be.undefined + const body = await server.playlistsCommand.list({ start: 0, count: 15 }) + + expect(finder(body.data)).to.not.be.undefined } } @@ -1247,8 +1162,9 @@ describe('Test video playlists', function () { { for (const server of [ servers[0], servers[1] ]) { - const res = await getVideoPlaylistsList(server.url, 0, 15) - expect(finder(res.body.data)).to.be.undefined + const body = await server.playlistsCommand.list({ start: 0, count: 15 }) + + expect(finder(body.data)).to.be.undefined } } }) diff --git a/server/tests/cli/prune-storage.ts b/server/tests/cli/prune-storage.ts index 95f573e50..fa1df65a9 100644 --- a/server/tests/cli/prune-storage.ts +++ b/server/tests/cli/prune-storage.ts @@ -10,7 +10,6 @@ import { buildServerDirectory, cleanupTests, CLICommand, - createVideoPlaylist, doubleFollow, flushAndRunMultipleServers, killallServers, @@ -77,10 +76,8 @@ describe('Test prune storage scripts', function () { await updateMyAvatar({ url: server.url, accessToken: server.accessToken, fixture: 'avatar.png' }) - await createVideoPlaylist({ - url: server.url, - token: server.accessToken, - playlistAttrs: { + await server.playlistsCommand.create({ + attributes: { displayName: 'playlist', privacy: VideoPlaylistPrivacy.PUBLIC, videoChannelId: server.videoChannel.id, diff --git a/server/tests/client.ts b/server/tests/client.ts index 60df878d7..129f1e1c0 100644 --- a/server/tests/client.ts +++ b/server/tests/client.ts @@ -6,9 +6,7 @@ import { omit } from 'lodash' import { HttpStatusCode } from '@shared/core-utils/miscs/http-error-codes' import { Account, HTMLServerConfig, ServerConfig, VideoPlaylistCreateResult, VideoPlaylistPrivacy } from '@shared/models' import { - addVideoInPlaylist, cleanupTests, - createVideoPlaylist, doubleFollow, flushAndRunMultipleServers, getVideosList, @@ -82,23 +80,17 @@ describe('Test a client controllers', function () { // Playlist - const playlistAttrs = { + const attributes = { displayName: playlistName, description: playlistDescription, privacy: VideoPlaylistPrivacy.PUBLIC, videoChannelId: servers[0].videoChannel.id } - const resVideoPlaylistRequest = await createVideoPlaylist({ url: servers[0].url, token: servers[0].accessToken, playlistAttrs }) - playlist = resVideoPlaylistRequest.body.videoPlaylist + playlist = await servers[0].playlistsCommand.create({ attributes }) playlistIds = [ playlist.id, playlist.shortUUID, playlist.uuid ] - await addVideoInPlaylist({ - url: servers[0].url, - token: servers[0].accessToken, - playlistId: playlist.shortUUID, - elementAttrs: { videoId: video.id } - }) + await servers[0].playlistsCommand.addElement({ playlistId: playlist.shortUUID, attributes: { videoId: video.id } }) // Account diff --git a/server/tests/plugins/action-hooks.ts b/server/tests/plugins/action-hooks.ts index 5e9dc3515..fd83bf2ac 100644 --- a/server/tests/plugins/action-hooks.ts +++ b/server/tests/plugins/action-hooks.ts @@ -5,10 +5,8 @@ import { ServerHookName, VideoPlaylistPrivacy, VideoPrivacy } from '@shared/mode import { addVideoCommentReply, addVideoCommentThread, - addVideoInPlaylist, blockUser, createUser, - createVideoPlaylist, deleteVideoComment, PluginsCommand, registerUser, @@ -180,15 +178,13 @@ describe('Test plugin action hooks', function () { before(async function () { { - const res = await createVideoPlaylist({ - url: servers[0].url, - token: servers[0].accessToken, - playlistAttrs: { + const { id } = await servers[0].playlistsCommand.create({ + attributes: { displayName: 'My playlist', privacy: VideoPlaylistPrivacy.PRIVATE } }) - playlistId = res.body.videoPlaylist.id + playlistId = id } { @@ -198,12 +194,7 @@ describe('Test plugin action hooks', function () { }) it('Should run action:api.video-playlist-element.created', async function () { - await addVideoInPlaylist({ - url: servers[0].url, - token: servers[0].accessToken, - playlistId, - elementAttrs: { videoId } - }) + await servers[0].playlistsCommand.addElement({ playlistId, attributes: { videoId } }) await checkHook('action:api.video-playlist-element.created') }) diff --git a/server/tests/plugins/filter-hooks.ts b/server/tests/plugins/filter-hooks.ts index e938663da..203642d8d 100644 --- a/server/tests/plugins/filter-hooks.ts +++ b/server/tests/plugins/filter-hooks.ts @@ -7,7 +7,6 @@ import { addVideoCommentReply, addVideoCommentThread, cleanupTests, - createVideoPlaylist, doubleFollow, flushAndRunMultipleServers, getAccountVideos, @@ -15,7 +14,6 @@ import { getVideo, getVideoChannelVideos, getVideoCommentThreads, - getVideoPlaylist, getVideosList, getVideosListPagination, getVideoThreadComments, @@ -443,11 +441,11 @@ describe('Test plugin filter hooks', function () { } { - const playlistAttrs = { displayName: name, videoChannelId: servers[0].videoChannel.id, privacy: VideoPlaylistPrivacy.PUBLIC } - const res = await createVideoPlaylist({ url: servers[0].url, token: servers[0].accessToken, playlistAttrs }) + const attributes = { displayName: name, videoChannelId: servers[0].videoChannel.id, privacy: VideoPlaylistPrivacy.PUBLIC } + const { id } = await servers[0].playlistsCommand.create({ attributes }) - const resPlaylist = await getVideoPlaylist(servers[0].url, res.body.videoPlaylist.id) - embedPlaylists.push(resPlaylist.body) + const playlist = await servers[0].playlistsCommand.get({ playlistId: id }) + embedPlaylists.push(playlist) } } }) diff --git a/server/tests/plugins/video-constants.ts b/server/tests/plugins/video-constants.ts index 4124e8a52..4a05af042 100644 --- a/server/tests/plugins/video-constants.ts +++ b/server/tests/plugins/video-constants.ts @@ -5,13 +5,11 @@ import * as chai from 'chai' import { HttpStatusCode } from '@shared/core-utils' import { cleanupTests, - createVideoPlaylist, flushAndRunServer, getVideo, getVideoCategories, getVideoLanguages, getVideoLicences, - getVideoPlaylistPrivacies, getVideoPrivacies, PluginsCommand, ServerInfo, @@ -79,8 +77,7 @@ describe('Test plugin altering video constants', function () { }) it('Should have updated playlist privacies', async function () { - const res = await getVideoPlaylistPrivacies(server.url) - const playlistPrivacies = res.body + const playlistPrivacies = await server.playlistsCommand.getPrivacies() expect(playlistPrivacies[1]).to.exist expect(playlistPrivacies[2]).to.exist @@ -93,13 +90,8 @@ describe('Test plugin altering video constants', function () { }) it('Should not be able to create a video with this privacy', async function () { - const attrs = { displayName: 'video playlist', privacy: VideoPlaylistPrivacy.PRIVATE } - await createVideoPlaylist({ - url: server.url, - token: server.accessToken, - playlistAttrs: attrs, - expectedStatus: HttpStatusCode.BAD_REQUEST_400 - }) + const attributes = { displayName: 'video playlist', privacy: VideoPlaylistPrivacy.PRIVATE } + await server.playlistsCommand.create({ attributes, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) it('Should be able to upload a video with these values', async function () { @@ -162,8 +154,7 @@ describe('Test plugin altering video constants', function () { } { - const res = await getVideoPlaylistPrivacies(server.url) - const playlistPrivacies = res.body + const playlistPrivacies = await server.playlistsCommand.getPrivacies() expect(playlistPrivacies[1]).to.exist expect(playlistPrivacies[2]).to.exist diff --git a/shared/extra-utils/server/servers.ts b/shared/extra-utils/server/servers.ts index 33f558414..78b3be9c7 100644 --- a/shared/extra-utils/server/servers.ts +++ b/shared/extra-utils/server/servers.ts @@ -18,7 +18,7 @@ import { makeGetRequest } from '../requests/requests' import { SearchCommand } from '../search' import { SocketIOCommand } from '../socket' import { AccountsCommand, BlocklistCommand, SubscriptionsCommand } from '../users' -import { BlacklistCommand, CaptionsCommand, ChangeOwnershipCommand, LiveCommand, ServicesCommand } from '../videos' +import { BlacklistCommand, CaptionsCommand, ChangeOwnershipCommand, LiveCommand, PlaylistsCommand, ServicesCommand } from '../videos' import { ConfigCommand } from './config-command' import { ContactFormCommand } from './contact-form-command' import { DebugCommand } from './debug-command' @@ -105,6 +105,7 @@ interface ServerInfo { blacklistCommand?: BlacklistCommand captionsCommand?: CaptionsCommand changeOwnershipCommand?: ChangeOwnershipCommand + playlistsCommand?: PlaylistsCommand } function parallelTests () { @@ -335,6 +336,7 @@ async function runServer (server: ServerInfo, configOverrideArg?: any, args = [] server.blacklistCommand = new BlacklistCommand(server) server.captionsCommand = new CaptionsCommand(server) server.changeOwnershipCommand = new ChangeOwnershipCommand(server) + server.playlistsCommand = new PlaylistsCommand(server) res(server) }) diff --git a/shared/extra-utils/videos/index.ts b/shared/extra-utils/videos/index.ts index 815c7f944..1f6241d7e 100644 --- a/shared/extra-utils/videos/index.ts +++ b/shared/extra-utils/videos/index.ts @@ -4,11 +4,12 @@ export * from './captions-command' export * from './change-ownership-command' export * from './live-command' export * from './live' +export * from './playlists-command' +export * from './playlists' export * from './services-command' export * from './video-channels' export * from './video-comments' export * from './video-history' export * from './video-imports' -export * from './video-playlists' export * from './video-streaming-playlists' export * from './videos' diff --git a/shared/extra-utils/videos/playlists-command.ts b/shared/extra-utils/videos/playlists-command.ts new file mode 100644 index 000000000..f77decc1a --- /dev/null +++ b/shared/extra-utils/videos/playlists-command.ts @@ -0,0 +1,280 @@ +import { omit, pick } from 'lodash' +import { + BooleanBothQuery, + ResultList, + VideoExistInPlaylist, + VideoPlaylist, + VideoPlaylistCreateResult, + VideoPlaylistElement, + VideoPlaylistElementCreateResult, + VideoPlaylistReorder +} from '@shared/models' +import { HttpStatusCode } from '../../core-utils/miscs/http-error-codes' +import { VideoPlaylistCreate } from '../../models/videos/playlist/video-playlist-create.model' +import { VideoPlaylistElementCreate } from '../../models/videos/playlist/video-playlist-element-create.model' +import { VideoPlaylistElementUpdate } from '../../models/videos/playlist/video-playlist-element-update.model' +import { VideoPlaylistType } from '../../models/videos/playlist/video-playlist-type.model' +import { VideoPlaylistUpdate } from '../../models/videos/playlist/video-playlist-update.model' +import { unwrapBody } from '../requests' +import { AbstractCommand, OverrideCommandOptions } from '../shared' +import { videoUUIDToId } from './videos' + +export class PlaylistsCommand extends AbstractCommand { + + list (options: OverrideCommandOptions & { + start?: number + count?: number + sort?: string + }) { + const path = '/api/v1/video-playlists' + const query = pick(options, [ 'start', 'count', 'sort' ]) + + return this.getRequestBody>({ + ...options, + + path, + query, + implicitToken: false, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } + + listByChannel (options: OverrideCommandOptions & { + handle: string + start?: number + count?: number + sort?: string + }) { + const path = '/api/v1/video-channels/' + options.handle + '/video-playlists' + const query = pick(options, [ 'start', 'count', 'sort' ]) + + return this.getRequestBody>({ + ...options, + + path, + query, + implicitToken: false, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } + + listByAccount (options: OverrideCommandOptions & { + handle: string + start?: number + count?: number + sort?: string + search?: string + playlistType?: VideoPlaylistType + }) { + const path = '/api/v1/accounts/' + options.handle + '/video-playlists' + const query = pick(options, [ 'start', 'count', 'sort', 'search', 'playlistType' ]) + + return this.getRequestBody>({ + ...options, + + path, + query, + implicitToken: false, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } + + get (options: OverrideCommandOptions & { + playlistId: number | string + }) { + const { playlistId } = options + const path = '/api/v1/video-playlists/' + playlistId + + return this.getRequestBody({ + ...options, + + path, + implicitToken: false, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } + + listVideos (options: OverrideCommandOptions & { + playlistId: number | string + start?: number + count?: number + query?: { nsfw?: BooleanBothQuery } + }) { + const path = '/api/v1/video-playlists/' + options.playlistId + '/videos' + const query = options.query ?? {} + + return this.getRequestBody>({ + ...options, + + path, + query: { + ...query, + start: options.start, + count: options.count + }, + implicitToken: true, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } + + delete (options: OverrideCommandOptions & { + playlistId: number | string + }) { + const path = '/api/v1/video-playlists/' + options.playlistId + + return this.deleteRequest({ + ...options, + + path, + implicitToken: true, + defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 + }) + } + + async create (options: OverrideCommandOptions & { + attributes: VideoPlaylistCreate + }) { + const path = '/api/v1/video-playlists' + + const fields = omit(options.attributes, 'thumbnailfile') + + const attaches = options.attributes.thumbnailfile + ? { thumbnailfile: options.attributes.thumbnailfile } + : {} + + const body = await unwrapBody<{ videoPlaylist: VideoPlaylistCreateResult }>(this.postUploadRequest({ + ...options, + + path, + fields, + attaches, + implicitToken: true, + defaultExpectedStatus: HttpStatusCode.OK_200 + })) + + return body.videoPlaylist + } + + update (options: OverrideCommandOptions & { + attributes: VideoPlaylistUpdate + playlistId: number | string + }) { + const path = '/api/v1/video-playlists/' + options.playlistId + + const fields = omit(options.attributes, 'thumbnailfile') + + const attaches = options.attributes.thumbnailfile + ? { thumbnailfile: options.attributes.thumbnailfile } + : {} + + return this.putUploadRequest({ + ...options, + + path, + fields, + attaches, + implicitToken: true, + defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 + }) + } + + async addElement (options: OverrideCommandOptions & { + playlistId: number | string + attributes: VideoPlaylistElementCreate | { videoId: string } + }) { + const attributes = { + ...options.attributes, + + videoId: await videoUUIDToId(this.server.url, options.attributes.videoId) + } + + const path = '/api/v1/video-playlists/' + options.playlistId + '/videos' + + const body = await unwrapBody<{ videoPlaylistElement: VideoPlaylistElementCreateResult }>(this.postBodyRequest({ + ...options, + + path, + fields: attributes, + implicitToken: true, + defaultExpectedStatus: HttpStatusCode.OK_200 + })) + + return body.videoPlaylistElement + } + + updateElement (options: OverrideCommandOptions & { + playlistId: number | string + elementId: number | string + attributes: VideoPlaylistElementUpdate + }) { + const path = '/api/v1/video-playlists/' + options.playlistId + '/videos/' + options.elementId + + return this.putBodyRequest({ + ...options, + + path, + fields: options.attributes, + implicitToken: true, + defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 + }) + } + + removeElement (options: OverrideCommandOptions & { + playlistId: number | string + elementId: number + }) { + const path = '/api/v1/video-playlists/' + options.playlistId + '/videos/' + options.elementId + + return this.deleteRequest({ + ...options, + + path, + implicitToken: true, + defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 + }) + } + + reorderElements (options: OverrideCommandOptions & { + playlistId: number | string + attributes: VideoPlaylistReorder + }) { + const path = '/api/v1/video-playlists/' + options.playlistId + '/videos/reorder' + + return this.postBodyRequest({ + ...options, + + path, + fields: options.attributes, + implicitToken: true, + defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 + }) + } + + getPrivacies (options: OverrideCommandOptions = {}) { + const path = '/api/v1/video-playlists/privacies' + + return this.getRequestBody<{ [ id: number ]: string }>({ + ...options, + + path, + implicitToken: false, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } + + videosExist (options: OverrideCommandOptions & { + videoIds: number[] + }) { + const { videoIds } = options + const path = '/api/v1/users/me/video-playlists/videos-exist' + + return this.getRequestBody({ + ...options, + + path, + query: { videoIds }, + implicitToken: true, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } +} diff --git a/shared/extra-utils/videos/playlists.ts b/shared/extra-utils/videos/playlists.ts new file mode 100644 index 000000000..023333c87 --- /dev/null +++ b/shared/extra-utils/videos/playlists.ts @@ -0,0 +1,25 @@ +import { expect } from 'chai' +import { readdir } from 'fs-extra' +import { join } from 'path' +import { root } from '../' + +async function checkPlaylistFilesWereRemoved ( + playlistUUID: string, + internalServerNumber: number, + directories = [ 'thumbnails' ] +) { + const testDirectory = 'test' + internalServerNumber + + for (const directory of directories) { + const directoryPath = join(root(), testDirectory, directory) + + const files = await readdir(directoryPath) + for (const file of files) { + expect(file).to.not.contain(playlistUUID) + } + } +} + +export { + checkPlaylistFilesWereRemoved +} diff --git a/shared/extra-utils/videos/video-playlists.ts b/shared/extra-utils/videos/video-playlists.ts deleted file mode 100644 index c6f799e5d..000000000 --- a/shared/extra-utils/videos/video-playlists.ts +++ /dev/null @@ -1,320 +0,0 @@ -import { makeDeleteRequest, makeGetRequest, makePostBodyRequest, makePutBodyRequest, makeUploadRequest } from '../requests/requests' -import { VideoPlaylistCreate } from '../../models/videos/playlist/video-playlist-create.model' -import { omit } from 'lodash' -import { VideoPlaylistUpdate } from '../../models/videos/playlist/video-playlist-update.model' -import { VideoPlaylistElementCreate } from '../../models/videos/playlist/video-playlist-element-create.model' -import { VideoPlaylistElementUpdate } from '../../models/videos/playlist/video-playlist-element-update.model' -import { videoUUIDToId } from './videos' -import { join } from 'path' -import { root } from '..' -import { readdir } from 'fs-extra' -import { expect } from 'chai' -import { VideoPlaylistType } from '../../models/videos/playlist/video-playlist-type.model' -import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' - -function getVideoPlaylistsList (url: string, start: number, count: number, sort?: string) { - const path = '/api/v1/video-playlists' - - const query = { - start, - count, - sort - } - - return makeGetRequest({ - url, - path, - query, - statusCodeExpected: HttpStatusCode.OK_200 - }) -} - -function getVideoChannelPlaylistsList (url: string, videoChannelName: string, start: number, count: number, sort?: string) { - const path = '/api/v1/video-channels/' + videoChannelName + '/video-playlists' - - const query = { - start, - count, - sort - } - - return makeGetRequest({ - url, - path, - query, - statusCodeExpected: HttpStatusCode.OK_200 - }) -} - -function getAccountPlaylistsList (url: string, accountName: string, start: number, count: number, sort?: string, search?: string) { - const path = '/api/v1/accounts/' + accountName + '/video-playlists' - - const query = { - start, - count, - sort, - search - } - - return makeGetRequest({ - url, - path, - query, - statusCodeExpected: HttpStatusCode.OK_200 - }) -} - -function getAccountPlaylistsListWithToken ( - url: string, - token: string, - accountName: string, - start: number, - count: number, - playlistType?: VideoPlaylistType, - sort?: string -) { - const path = '/api/v1/accounts/' + accountName + '/video-playlists' - - const query = { - start, - count, - playlistType, - sort - } - - return makeGetRequest({ - url, - token, - path, - query, - statusCodeExpected: HttpStatusCode.OK_200 - }) -} - -function getVideoPlaylist (url: string, playlistId: number | string, statusCodeExpected = HttpStatusCode.OK_200) { - const path = '/api/v1/video-playlists/' + playlistId - - return makeGetRequest({ - url, - path, - statusCodeExpected - }) -} - -function getVideoPlaylistWithToken (url: string, token: string, playlistId: number | string, statusCodeExpected = HttpStatusCode.OK_200) { - const path = '/api/v1/video-playlists/' + playlistId - - return makeGetRequest({ - url, - token, - path, - statusCodeExpected - }) -} - -function deleteVideoPlaylist (url: string, token: string, playlistId: number | string, statusCodeExpected = HttpStatusCode.NO_CONTENT_204) { - const path = '/api/v1/video-playlists/' + playlistId - - return makeDeleteRequest({ - url, - path, - token, - statusCodeExpected - }) -} - -function createVideoPlaylist (options: { - url: string - token: string - playlistAttrs: VideoPlaylistCreate - expectedStatus?: number -}) { - const path = '/api/v1/video-playlists' - - const fields = omit(options.playlistAttrs, 'thumbnailfile') - - const attaches = options.playlistAttrs.thumbnailfile - ? { thumbnailfile: options.playlistAttrs.thumbnailfile } - : {} - - return makeUploadRequest({ - method: 'POST', - url: options.url, - path, - token: options.token, - fields, - attaches, - statusCodeExpected: options.expectedStatus || HttpStatusCode.OK_200 - }) -} - -function updateVideoPlaylist (options: { - url: string - token: string - playlistAttrs: VideoPlaylistUpdate - playlistId: number | string - expectedStatus?: number -}) { - const path = '/api/v1/video-playlists/' + options.playlistId - - const fields = omit(options.playlistAttrs, 'thumbnailfile') - - const attaches = options.playlistAttrs.thumbnailfile - ? { thumbnailfile: options.playlistAttrs.thumbnailfile } - : {} - - return makeUploadRequest({ - method: 'PUT', - url: options.url, - path, - token: options.token, - fields, - attaches, - statusCodeExpected: options.expectedStatus || HttpStatusCode.NO_CONTENT_204 - }) -} - -async function addVideoInPlaylist (options: { - url: string - token: string - playlistId: number | string - elementAttrs: VideoPlaylistElementCreate | { videoId: string } - expectedStatus?: number -}) { - options.elementAttrs.videoId = await videoUUIDToId(options.url, options.elementAttrs.videoId) - - const path = '/api/v1/video-playlists/' + options.playlistId + '/videos' - - return makePostBodyRequest({ - url: options.url, - path, - token: options.token, - fields: options.elementAttrs, - statusCodeExpected: options.expectedStatus || HttpStatusCode.OK_200 - }) -} - -function updateVideoPlaylistElement (options: { - url: string - token: string - playlistId: number | string - playlistElementId: number | string - elementAttrs: VideoPlaylistElementUpdate - expectedStatus?: number -}) { - const path = '/api/v1/video-playlists/' + options.playlistId + '/videos/' + options.playlistElementId - - return makePutBodyRequest({ - url: options.url, - path, - token: options.token, - fields: options.elementAttrs, - statusCodeExpected: options.expectedStatus || HttpStatusCode.NO_CONTENT_204 - }) -} - -function removeVideoFromPlaylist (options: { - url: string - token: string - playlistId: number | string - playlistElementId: number - expectedStatus?: number -}) { - const path = '/api/v1/video-playlists/' + options.playlistId + '/videos/' + options.playlistElementId - - return makeDeleteRequest({ - url: options.url, - path, - token: options.token, - statusCodeExpected: options.expectedStatus || HttpStatusCode.NO_CONTENT_204 - }) -} - -function reorderVideosPlaylist (options: { - url: string - token: string - playlistId: number | string - elementAttrs: { - startPosition: number - insertAfterPosition: number - reorderLength?: number - } - expectedStatus?: number -}) { - const path = '/api/v1/video-playlists/' + options.playlistId + '/videos/reorder' - - return makePostBodyRequest({ - url: options.url, - path, - token: options.token, - fields: options.elementAttrs, - statusCodeExpected: options.expectedStatus || HttpStatusCode.NO_CONTENT_204 - }) -} - -async function checkPlaylistFilesWereRemoved ( - playlistUUID: string, - internalServerNumber: number, - directories = [ 'thumbnails' ] -) { - const testDirectory = 'test' + internalServerNumber - - for (const directory of directories) { - const directoryPath = join(root(), testDirectory, directory) - - const files = await readdir(directoryPath) - for (const file of files) { - expect(file).to.not.contain(playlistUUID) - } - } -} - -function getVideoPlaylistPrivacies (url: string) { - const path = '/api/v1/video-playlists/privacies' - - return makeGetRequest({ - url, - path, - statusCodeExpected: HttpStatusCode.OK_200 - }) -} - -function doVideosExistInMyPlaylist (url: string, token: string, videoIds: number[]) { - const path = '/api/v1/users/me/video-playlists/videos-exist' - - return makeGetRequest({ - url, - token, - path, - query: { videoIds }, - statusCodeExpected: HttpStatusCode.OK_200 - }) -} - -// --------------------------------------------------------------------------- - -export { - getVideoPlaylistPrivacies, - - getVideoPlaylistsList, - getVideoChannelPlaylistsList, - getAccountPlaylistsList, - getAccountPlaylistsListWithToken, - - getVideoPlaylist, - getVideoPlaylistWithToken, - - createVideoPlaylist, - updateVideoPlaylist, - deleteVideoPlaylist, - - addVideoInPlaylist, - updateVideoPlaylistElement, - removeVideoFromPlaylist, - - reorderVideosPlaylist, - - checkPlaylistFilesWereRemoved, - - doVideosExistInMyPlaylist -} diff --git a/shared/extra-utils/videos/videos.ts b/shared/extra-utils/videos/videos.ts index a45c0402a..920c93072 100644 --- a/shared/extra-utils/videos/videos.ts +++ b/shared/extra-utils/videos/videos.ts @@ -262,28 +262,6 @@ function getVideoChannelVideos ( }) } -function getPlaylistVideos ( - url: string, - accessToken: string, - playlistId: number | string, - start: number, - count: number, - query: { nsfw?: boolean } = {} -) { - const path = '/api/v1/video-playlists/' + playlistId + '/videos' - - return makeGetRequest({ - url, - path, - query: immutableAssign(query, { - start, - count - }), - token: accessToken, - statusCodeExpected: HttpStatusCode.OK_200 - }) -} - function getVideosListPagination (url: string, start: number, count: number, sort?: string, skipCount?: boolean) { const path = '/api/v1/videos' @@ -871,7 +849,6 @@ export { getLocalVideos, completeVideoCheck, checkVideoFilesWereRemoved, - getPlaylistVideos, getMyVideosWithFilter, uploadVideoAndGetId, getLocalIdByUUID, diff --git a/shared/models/videos/playlist/index.ts b/shared/models/videos/playlist/index.ts index f11a4bd28..a9e8ce496 100644 --- a/shared/models/videos/playlist/index.ts +++ b/shared/models/videos/playlist/index.ts @@ -1,6 +1,7 @@ export * from './video-exist-in-playlist.model' export * from './video-playlist-create-result.model' export * from './video-playlist-create.model' +export * from './video-playlist-element-create-result.model' export * from './video-playlist-element-create.model' export * from './video-playlist-element-update.model' export * from './video-playlist-element.model' diff --git a/shared/models/videos/playlist/video-playlist-element-create-result.model.ts b/shared/models/videos/playlist/video-playlist-element-create-result.model.ts new file mode 100644 index 000000000..dc475e7d8 --- /dev/null +++ b/shared/models/videos/playlist/video-playlist-element-create-result.model.ts @@ -0,0 +1,3 @@ +export interface VideoPlaylistElementCreateResult { + id: number +} -- cgit v1.2.3 From 313228e9c3b5bcef5391228c9b949d05d32ad7bb Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Thu, 8 Jul 2021 16:21:42 +0200 Subject: Introduce history command --- server/tests/api/videos/videos-history.ts | 59 ++++++++++++++-------------- shared/extra-utils/server/servers.ts | 4 +- shared/extra-utils/videos/history-command.ts | 59 ++++++++++++++++++++++++++++ shared/extra-utils/videos/index.ts | 2 +- shared/extra-utils/videos/video-history.ts | 49 ----------------------- 5 files changed, 92 insertions(+), 81 deletions(-) create mode 100644 shared/extra-utils/videos/history-command.ts delete mode 100644 shared/extra-utils/videos/video-history.ts diff --git a/server/tests/api/videos/videos-history.ts b/server/tests/api/videos/videos-history.ts index 209b93014..731447135 100644 --- a/server/tests/api/videos/videos-history.ts +++ b/server/tests/api/videos/videos-history.ts @@ -9,6 +9,7 @@ import { flushAndRunServer, getVideosListWithToken, getVideoWithToken, + HistoryCommand, killallServers, reRunServer, ServerInfo, @@ -18,7 +19,6 @@ import { userLogin, wait } from '@shared/extra-utils' -import { listMyVideosHistory, removeMyVideosHistory, userWatchVideo } from '@shared/extra-utils/videos/video-history' import { Video, VideoDetails } from '@shared/models' const expect = chai.expect @@ -30,6 +30,7 @@ describe('Test videos history', function () { let video3UUID: string let video3WatchedDate: Date let userAccessToken: string + let command: HistoryCommand before(async function () { this.timeout(30000) @@ -38,6 +39,8 @@ describe('Test videos history', function () { await setAccessTokensToServers([ server ]) + command = server.historyCommand + { const res = await uploadVideo(server.url, server.accessToken, { name: 'video 1' }) video1UUID = res.body.video.uuid @@ -75,8 +78,8 @@ describe('Test videos history', function () { }) it('Should watch the first and second video', async function () { - await userWatchVideo(server.url, server.accessToken, video2UUID, 8) - await userWatchVideo(server.url, server.accessToken, video1UUID, 3) + await command.wathVideo({ videoId: video2UUID, currentTime: 8 }) + await command.wathVideo({ videoId: video1UUID, currentTime: 3 }) }) it('Should return the correct history when listing, searching and getting videos', async function () { @@ -132,44 +135,42 @@ describe('Test videos history', function () { it('Should have these videos when listing my history', async function () { video3WatchedDate = new Date() - await userWatchVideo(server.url, server.accessToken, video3UUID, 2) + await command.wathVideo({ videoId: video3UUID, currentTime: 2 }) - const res = await listMyVideosHistory(server.url, server.accessToken) + const body = await command.list() - expect(res.body.total).to.equal(3) + expect(body.total).to.equal(3) - const videos: Video[] = res.body.data + const videos = body.data expect(videos[0].name).to.equal('video 3') expect(videos[1].name).to.equal('video 1') expect(videos[2].name).to.equal('video 2') }) it('Should not have videos history on another user', async function () { - const res = await listMyVideosHistory(server.url, userAccessToken) + const body = await command.list({ token: userAccessToken }) - expect(res.body.total).to.equal(0) - expect(res.body.data).to.have.lengthOf(0) + expect(body.total).to.equal(0) + expect(body.data).to.have.lengthOf(0) }) it('Should be able to search through videos in my history', async function () { - const res = await listMyVideosHistory(server.url, server.accessToken, '2') - - expect(res.body.total).to.equal(1) + const body = await command.list({ search: '2' }) + expect(body.total).to.equal(1) - const videos: Video[] = res.body.data + const videos = body.data expect(videos[0].name).to.equal('video 2') }) it('Should clear my history', async function () { - await removeMyVideosHistory(server.url, server.accessToken, video3WatchedDate.toISOString()) + await command.remove({ beforeDate: video3WatchedDate.toISOString() }) }) it('Should have my history cleared', async function () { - const res = await listMyVideosHistory(server.url, server.accessToken) - - expect(res.body.total).to.equal(1) + const body = await command.list() + expect(body.total).to.equal(1) - const videos: Video[] = res.body.data + const videos = body.data expect(videos[0].name).to.equal('video 3') }) @@ -180,7 +181,7 @@ describe('Test videos history', function () { videosHistoryEnabled: false }) - await userWatchVideo(server.url, server.accessToken, video2UUID, 8, HttpStatusCode.CONFLICT_409) + await command.wathVideo({ videoId: video2UUID, currentTime: 8, expectedStatus: HttpStatusCode.CONFLICT_409 }) }) it('Should re-enable videos history', async function () { @@ -190,13 +191,12 @@ describe('Test videos history', function () { videosHistoryEnabled: true }) - await userWatchVideo(server.url, server.accessToken, video1UUID, 8) - - const res = await listMyVideosHistory(server.url, server.accessToken) + await command.wathVideo({ videoId: video1UUID, currentTime: 8 }) - expect(res.body.total).to.equal(2) + const body = await command.list() + expect(body.total).to.equal(2) - const videos: Video[] = res.body.data + const videos = body.data expect(videos[0].name).to.equal('video 1') expect(videos[1].name).to.equal('video 3') }) @@ -212,9 +212,8 @@ describe('Test videos history', function () { // Should still have history - const res = await listMyVideosHistory(server.url, server.accessToken) - - expect(res.body.total).to.equal(2) + const body = await command.list() + expect(body.total).to.equal(2) }) it('Should clean old history', async function () { @@ -226,8 +225,8 @@ describe('Test videos history', function () { await wait(6000) - const res = await listMyVideosHistory(server.url, server.accessToken) - expect(res.body.total).to.equal(0) + const body = await command.list() + expect(body.total).to.equal(0) }) after(async function () { diff --git a/shared/extra-utils/server/servers.ts b/shared/extra-utils/server/servers.ts index 78b3be9c7..bd5c29e51 100644 --- a/shared/extra-utils/server/servers.ts +++ b/shared/extra-utils/server/servers.ts @@ -18,7 +18,7 @@ import { makeGetRequest } from '../requests/requests' import { SearchCommand } from '../search' import { SocketIOCommand } from '../socket' import { AccountsCommand, BlocklistCommand, SubscriptionsCommand } from '../users' -import { BlacklistCommand, CaptionsCommand, ChangeOwnershipCommand, LiveCommand, PlaylistsCommand, ServicesCommand } from '../videos' +import { BlacklistCommand, CaptionsCommand, ChangeOwnershipCommand, HistoryCommand, LiveCommand, PlaylistsCommand, ServicesCommand } from '../videos' import { ConfigCommand } from './config-command' import { ContactFormCommand } from './contact-form-command' import { DebugCommand } from './debug-command' @@ -106,6 +106,7 @@ interface ServerInfo { captionsCommand?: CaptionsCommand changeOwnershipCommand?: ChangeOwnershipCommand playlistsCommand?: PlaylistsCommand + historyCommand?: HistoryCommand } function parallelTests () { @@ -337,6 +338,7 @@ async function runServer (server: ServerInfo, configOverrideArg?: any, args = [] server.captionsCommand = new CaptionsCommand(server) server.changeOwnershipCommand = new ChangeOwnershipCommand(server) server.playlistsCommand = new PlaylistsCommand(server) + server.historyCommand = new HistoryCommand(server) res(server) }) diff --git a/shared/extra-utils/videos/history-command.ts b/shared/extra-utils/videos/history-command.ts new file mode 100644 index 000000000..8a144a312 --- /dev/null +++ b/shared/extra-utils/videos/history-command.ts @@ -0,0 +1,59 @@ +import { ResultList, Video } from '@shared/models' +import { HttpStatusCode } from '../../core-utils/miscs/http-error-codes' +import { AbstractCommand, OverrideCommandOptions } from '../shared' + +export class HistoryCommand extends AbstractCommand { + + wathVideo (options: OverrideCommandOptions & { + videoId: number | string + currentTime: number + }) { + const { videoId, currentTime } = options + + const path = '/api/v1/videos/' + videoId + '/watching' + const fields = { currentTime } + + return this.putBodyRequest({ + ...options, + + path, + fields, + implicitToken: true, + defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 + }) + } + + list (options: OverrideCommandOptions & { + search?: string + } = {}) { + const { search } = options + const path = '/api/v1/users/me/history/videos' + + return this.getRequestBody>({ + ...options, + + path, + query: { + search + }, + implicitToken: true, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } + + remove (options: OverrideCommandOptions & { + beforeDate?: string + } = {}) { + const { beforeDate } = options + const path = '/api/v1/users/me/history/videos/remove' + + return this.postBodyRequest({ + ...options, + + path, + fields: { beforeDate }, + implicitToken: true, + defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 + }) + } +} diff --git a/shared/extra-utils/videos/index.ts b/shared/extra-utils/videos/index.ts index 1f6241d7e..74667fc06 100644 --- a/shared/extra-utils/videos/index.ts +++ b/shared/extra-utils/videos/index.ts @@ -2,6 +2,7 @@ export * from './blacklist-command' export * from './captions' export * from './captions-command' export * from './change-ownership-command' +export * from './history-command' export * from './live-command' export * from './live' export * from './playlists-command' @@ -9,7 +10,6 @@ export * from './playlists' export * from './services-command' export * from './video-channels' export * from './video-comments' -export * from './video-history' export * from './video-imports' export * from './video-streaming-playlists' export * from './videos' diff --git a/shared/extra-utils/videos/video-history.ts b/shared/extra-utils/videos/video-history.ts deleted file mode 100644 index b989e14dc..000000000 --- a/shared/extra-utils/videos/video-history.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { makeGetRequest, makePostBodyRequest, makePutBodyRequest } from '../requests/requests' -import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' - -function userWatchVideo ( - url: string, - token: string, - videoId: number | string, - currentTime: number, - statusCodeExpected = HttpStatusCode.NO_CONTENT_204 -) { - const path = '/api/v1/videos/' + videoId + '/watching' - const fields = { currentTime } - - return makePutBodyRequest({ url, path, token, fields, statusCodeExpected }) -} - -function listMyVideosHistory (url: string, token: string, search?: string) { - const path = '/api/v1/users/me/history/videos' - - return makeGetRequest({ - url, - path, - token, - query: { - search - }, - statusCodeExpected: HttpStatusCode.OK_200 - }) -} - -function removeMyVideosHistory (url: string, token: string, beforeDate?: string) { - const path = '/api/v1/users/me/history/videos/remove' - - return makePostBodyRequest({ - url, - path, - token, - fields: beforeDate ? { beforeDate } : {}, - statusCodeExpected: HttpStatusCode.NO_CONTENT_204 - }) -} - -// --------------------------------------------------------------------------- - -export { - userWatchVideo, - listMyVideosHistory, - removeMyVideosHistory -} -- cgit v1.2.3 From 6910f20f114b5bd020258a3a9a3f2117819a60c2 Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Thu, 8 Jul 2021 16:49:51 +0200 Subject: Introduce import command --- server/tests/api/check-params/upload-quota.ts | 16 ++-- server/tests/api/check-params/video-imports.ts | 6 +- server/tests/api/moderation/video-blacklist.ts | 10 +-- .../tests/api/notifications/user-notifications.ts | 30 ++++---- server/tests/api/videos/video-imports.ts | 72 ++++++++--------- server/tests/cli/peertube.ts | 7 +- server/tests/plugins/filter-hooks.ts | 67 +++++++--------- shared/extra-utils/server/servers.ts | 13 +++- shared/extra-utils/videos/imports-command.ts | 86 +++++++++++++++++++++ shared/extra-utils/videos/index.ts | 2 +- shared/extra-utils/videos/video-imports.ts | 90 ---------------------- 11 files changed, 192 insertions(+), 207 deletions(-) create mode 100644 shared/extra-utils/videos/imports-command.ts delete mode 100644 shared/extra-utils/videos/video-imports.ts diff --git a/server/tests/api/check-params/upload-quota.ts b/server/tests/api/check-params/upload-quota.ts index d0fbec415..c444663b8 100644 --- a/server/tests/api/check-params/upload-quota.ts +++ b/server/tests/api/check-params/upload-quota.ts @@ -3,13 +3,12 @@ import 'mocha' import { expect } from 'chai' import { HttpStatusCode, randomInt } from '@shared/core-utils' -import { getGoodVideoUrl, getMagnetURI, getMyVideoImports, importVideo } from '@shared/extra-utils/videos/video-imports' -import { MyUser, VideoImport, VideoImportState, VideoPrivacy } from '@shared/models' +import { MyUser, VideoImportState, VideoPrivacy } from '@shared/models' import { cleanupTests, flushAndRunServer, getMyUserInformation, - immutableAssign, + ImportsCommand, registerUser, ServerInfo, setAccessTokensToServers, @@ -83,16 +82,15 @@ describe('Test upload quota', function () { channelId: server.videoChannel.id, privacy: VideoPrivacy.PUBLIC } - await importVideo(server.url, server.accessToken, immutableAssign(baseAttributes, { targetUrl: getGoodVideoUrl() })) - await importVideo(server.url, server.accessToken, immutableAssign(baseAttributes, { magnetUri: getMagnetURI() })) - await importVideo(server.url, server.accessToken, immutableAssign(baseAttributes, { torrentfile: 'video-720p.torrent' as any })) + await server.importsCommand.importVideo({ attributes: { ...baseAttributes, targetUrl: ImportsCommand.getGoodVideoUrl() } }) + await server.importsCommand.importVideo({ attributes: { ...baseAttributes, magnetUri: ImportsCommand.getMagnetURI() } }) + await server.importsCommand.importVideo({ attributes: { ...baseAttributes, torrentfile: 'video-720p.torrent' as any } }) await waitJobs([ server ]) - const res = await getMyVideoImports(server.url, server.accessToken) + const { total, data: videoImports } = await server.importsCommand.getMyVideoImports() + expect(total).to.equal(3) - expect(res.body.total).to.equal(3) - const videoImports: VideoImport[] = res.body.data expect(videoImports).to.have.lengthOf(3) for (const videoImport of videoImports) { diff --git a/server/tests/api/check-params/video-imports.ts b/server/tests/api/check-params/video-imports.ts index dae3860ef..ea473191e 100644 --- a/server/tests/api/check-params/video-imports.ts +++ b/server/tests/api/check-params/video-imports.ts @@ -13,6 +13,7 @@ import { flushAndRunServer, getMyUserInformation, immutableAssign, + ImportsCommand, makeGetRequest, makePostBodyRequest, makeUploadRequest, @@ -20,7 +21,6 @@ import { setAccessTokensToServers, userLogin } from '@shared/extra-utils' -import { getGoodVideoUrl, getMagnetURI } from '@shared/extra-utils/videos/video-imports' import { VideoPrivacy } from '@shared/models' describe('Test video imports API validator', function () { @@ -74,7 +74,7 @@ describe('Test video imports API validator', function () { before(function () { baseCorrectParams = { - targetUrl: getGoodVideoUrl(), + targetUrl: ImportsCommand.getGoodVideoUrl(), name: 'my super name', category: 5, licence: 1, @@ -301,7 +301,7 @@ describe('Test video imports API validator', function () { }) let fields = omit(baseCorrectParams, 'targetUrl') - fields = immutableAssign(fields, { magnetUri: getMagnetURI() }) + fields = immutableAssign(fields, { magnetUri: ImportsCommand.getMagnetURI() }) await makePostBodyRequest({ url: server.url, diff --git a/server/tests/api/moderation/video-blacklist.ts b/server/tests/api/moderation/video-blacklist.ts index 17a68e4a6..c72ebc16b 100644 --- a/server/tests/api/moderation/video-blacklist.ts +++ b/server/tests/api/moderation/video-blacklist.ts @@ -12,6 +12,7 @@ import { getMyUserInformation, getMyVideos, getVideosList, + ImportsCommand, killallServers, reRunServer, ServerInfo, @@ -21,7 +22,6 @@ import { userLogin, waitJobs } from '@shared/extra-utils' -import { getGoodVideoUrl, getMagnetURI, importVideo } from '@shared/extra-utils/videos/video-imports' import { User, UserAdminFlag, UserRole, VideoBlacklist, VideoBlacklistType } from '@shared/models' const expect = chai.expect @@ -402,11 +402,11 @@ describe('Test video blacklist', function () { this.timeout(15000) const attributes = { - targetUrl: getGoodVideoUrl(), + targetUrl: ImportsCommand.getGoodVideoUrl(), name: 'URL import', channelId: channelOfUserWithoutFlag } - await importVideo(servers[0].url, userWithoutFlag, attributes) + await servers[0].importsCommand.importVideo({ token: userWithoutFlag, attributes }) const body = await command.list({ sort: 'createdAt', type: VideoBlacklistType.AUTO_BEFORE_PUBLISHED }) expect(body.total).to.equal(2) @@ -415,11 +415,11 @@ describe('Test video blacklist', function () { it('Should auto blacklist a video on torrent import', async function () { const attributes = { - magnetUri: getMagnetURI(), + magnetUri: ImportsCommand.getMagnetURI(), name: 'Torrent import', channelId: channelOfUserWithoutFlag } - await importVideo(servers[0].url, userWithoutFlag, attributes) + await servers[0].importsCommand.importVideo({ token: userWithoutFlag, attributes }) const body = await command.list({ sort: 'createdAt', type: VideoBlacklistType.AUTO_BEFORE_PUBLISHED }) expect(body.total).to.equal(3) diff --git a/server/tests/api/notifications/user-notifications.ts b/server/tests/api/notifications/user-notifications.ts index 15be983f2..a9315c818 100644 --- a/server/tests/api/notifications/user-notifications.ts +++ b/server/tests/api/notifications/user-notifications.ts @@ -11,6 +11,7 @@ import { checkVideoIsPublished, cleanupTests, getLastNotification, + ImportsCommand, MockSmtpServer, prepareNotificationsTest, ServerInfo, @@ -21,7 +22,6 @@ import { wait, waitJobs } from '@shared/extra-utils' -import { getBadVideoUrl, getGoodVideoUrl, importVideo } from '@shared/extra-utils/videos/video-imports' import { UserNotification, UserNotificationType, VideoPrivacy } from '@shared/models' const expect = chai.expect @@ -209,14 +209,13 @@ describe('Test user notifications', function () { name, channelId, privacy: VideoPrivacy.PUBLIC, - targetUrl: getGoodVideoUrl() + targetUrl: ImportsCommand.getGoodVideoUrl() } - const res = await importVideo(servers[0].url, servers[0].accessToken, attributes) - const uuid = res.body.video.uuid + const { video } = await servers[0].importsCommand.importVideo({ attributes }) await waitJobs(servers) - await checkNewVideoFromSubscription(baseParams, name, uuid, 'presence') + await checkNewVideoFromSubscription(baseParams, name, video.uuid, 'presence') }) }) @@ -280,14 +279,13 @@ describe('Test user notifications', function () { name, channelId, privacy: VideoPrivacy.PUBLIC, - targetUrl: getGoodVideoUrl(), + targetUrl: ImportsCommand.getGoodVideoUrl(), waitTranscoding: true } - const res = await importVideo(servers[1].url, servers[1].accessToken, attributes) - const uuid = res.body.video.uuid + const { video } = await servers[1].importsCommand.importVideo({ attributes }) await waitJobs(servers) - await checkVideoIsPublished(baseParams, name, uuid, 'presence') + await checkVideoIsPublished(baseParams, name, video.uuid, 'presence') }) it('Should send a notification when the scheduled update has been proceeded', async function () { @@ -349,13 +347,12 @@ describe('Test user notifications', function () { name, channelId, privacy: VideoPrivacy.PRIVATE, - targetUrl: getBadVideoUrl() + targetUrl: ImportsCommand.getBadVideoUrl() } - const res = await importVideo(servers[0].url, servers[0].accessToken, attributes) - const uuid = res.body.video.uuid + const { video } = await servers[0].importsCommand.importVideo({ attributes }) await waitJobs(servers) - await checkMyVideoImportIsFinished(baseParams, name, uuid, getBadVideoUrl(), false, 'presence') + await checkMyVideoImportIsFinished(baseParams, name, video.uuid, ImportsCommand.getBadVideoUrl(), false, 'presence') }) it('Should send a notification when the video import succeeded', async function () { @@ -367,13 +364,12 @@ describe('Test user notifications', function () { name, channelId, privacy: VideoPrivacy.PRIVATE, - targetUrl: getGoodVideoUrl() + targetUrl: ImportsCommand.getGoodVideoUrl() } - const res = await importVideo(servers[0].url, servers[0].accessToken, attributes) - const uuid = res.body.video.uuid + const { video } = await servers[0].importsCommand.importVideo({ attributes }) await waitJobs(servers) - await checkMyVideoImportIsFinished(baseParams, name, uuid, getGoodVideoUrl(), true, 'presence') + await checkMyVideoImportIsFinished(baseParams, name, video.uuid, ImportsCommand.getGoodVideoUrl(), true, 'presence') }) }) diff --git a/server/tests/api/videos/video-imports.ts b/server/tests/api/videos/video-imports.ts index 14aed604f..4f9ecbe8e 100644 --- a/server/tests/api/videos/video-imports.ts +++ b/server/tests/api/videos/video-imports.ts @@ -3,6 +3,7 @@ import 'mocha' import * as chai from 'chai' import { + areHttpImportTestsDisabled, cleanupTests, doubleFollow, flushAndRunMultipleServers, @@ -11,20 +12,14 @@ import { getVideo, getVideosList, immutableAssign, + ImportsCommand, ServerInfo, setAccessTokensToServers, - testCaptionFile -} from '../../../../shared/extra-utils' -import { areHttpImportTestsDisabled, testImage } from '../../../../shared/extra-utils/miscs/miscs' -import { waitJobs } from '../../../../shared/extra-utils/server/jobs' -import { - getMagnetURI, - getMyVideoImports, - getYoutubeHDRVideoUrl, - getYoutubeVideoUrl, - importVideo -} from '../../../../shared/extra-utils/videos/video-imports' -import { VideoDetails, VideoImport, VideoPrivacy, VideoResolution } from '../../../../shared/models/videos' + testCaptionFile, + testImage, + waitJobs +} from '@shared/extra-utils' +import { VideoDetails, VideoPrivacy, VideoResolution } from '@shared/models' const expect = chai.expect @@ -124,17 +119,17 @@ describe('Test video imports', function () { } { - const attributes = immutableAssign(baseAttributes, { targetUrl: getYoutubeVideoUrl() }) - const res = await importVideo(servers[0].url, servers[0].accessToken, attributes) - expect(res.body.video.name).to.equal('small video - youtube') + const attributes = immutableAssign(baseAttributes, { targetUrl: ImportsCommand.getYoutubeVideoUrl() }) + const { video } = await servers[0].importsCommand.importVideo({ attributes }) + expect(video.name).to.equal('small video - youtube') - expect(res.body.video.thumbnailPath).to.match(new RegExp(`^/static/thumbnails/.+.jpg$`)) - expect(res.body.video.previewPath).to.match(new RegExp(`^/lazy-static/previews/.+.jpg$`)) + expect(video.thumbnailPath).to.match(new RegExp(`^/static/thumbnails/.+.jpg$`)) + expect(video.previewPath).to.match(new RegExp(`^/lazy-static/previews/.+.jpg$`)) - await testImage(servers[0].url, 'video_import_thumbnail', res.body.video.thumbnailPath) - await testImage(servers[0].url, 'video_import_preview', res.body.video.previewPath) + await testImage(servers[0].url, 'video_import_thumbnail', video.thumbnailPath) + await testImage(servers[0].url, 'video_import_preview', video.previewPath) - const bodyCaptions = await servers[0].captionsCommand.listVideoCaptions({ videoId: res.body.video.id }) + const bodyCaptions = await servers[0].captionsCommand.listVideoCaptions({ videoId: video.id }) const videoCaptions = bodyCaptions.data expect(videoCaptions).to.have.lengthOf(2) @@ -175,12 +170,12 @@ Ajouter un sous-titre est vraiment facile`) { const attributes = immutableAssign(baseAttributes, { - magnetUri: getMagnetURI(), + magnetUri: ImportsCommand.getMagnetURI(), description: 'this is a super torrent description', tags: [ 'tag_torrent1', 'tag_torrent2' ] }) - const res = await importVideo(servers[0].url, servers[0].accessToken, attributes) - expect(res.body.video.name).to.equal('super peertube2 video') + const { video } = await servers[0].importsCommand.importVideo({ attributes }) + expect(video.name).to.equal('super peertube2 video') } { @@ -189,8 +184,8 @@ Ajouter un sous-titre est vraiment facile`) description: 'this is a super torrent description', tags: [ 'tag_torrent1', 'tag_torrent2' ] }) - const res = await importVideo(servers[0].url, servers[0].accessToken, attributes) - expect(res.body.video.name).to.equal('你好 世界 720p.mp4') + const { video } = await servers[0].importsCommand.importVideo({ attributes }) + expect(video.name).to.equal('你好 世界 720p.mp4') } }) @@ -207,19 +202,18 @@ Ajouter un sous-titre est vraiment facile`) }) it('Should list the videos to import in my imports on server 1', async function () { - const res = await getMyVideoImports(servers[0].url, servers[0].accessToken, '-createdAt') + const { total, data: videoImports } = await servers[0].importsCommand.getMyVideoImports({ sort: '-createdAt' }) + expect(total).to.equal(3) - expect(res.body.total).to.equal(3) - const videoImports: VideoImport[] = res.body.data expect(videoImports).to.have.lengthOf(3) - expect(videoImports[2].targetUrl).to.equal(getYoutubeVideoUrl()) + expect(videoImports[2].targetUrl).to.equal(ImportsCommand.getYoutubeVideoUrl()) expect(videoImports[2].magnetUri).to.be.null expect(videoImports[2].torrentName).to.be.null expect(videoImports[2].video.name).to.equal('small video - youtube') expect(videoImports[1].targetUrl).to.be.null - expect(videoImports[1].magnetUri).to.equal(getMagnetURI()) + expect(videoImports[1].magnetUri).to.equal(ImportsCommand.getMagnetURI()) expect(videoImports[1].torrentName).to.be.null expect(videoImports[1].video.name).to.equal('super peertube2 video') @@ -248,7 +242,7 @@ Ajouter un sous-titre est vraiment facile`) this.timeout(60_000) const attributes = { - targetUrl: getYoutubeVideoUrl(), + targetUrl: ImportsCommand.getYoutubeVideoUrl(), channelId: channelIdServer2, privacy: VideoPrivacy.PUBLIC, category: 10, @@ -258,8 +252,8 @@ Ajouter un sous-titre est vraiment facile`) description: 'my super description', tags: [ 'supertag1', 'supertag2' ] } - const res = await importVideo(servers[1].url, servers[1].accessToken, attributes) - expect(res.body.video.name).to.equal('my super name') + const { video } = await servers[1].importsCommand.importVideo({ attributes }) + expect(video.name).to.equal('my super name') }) it('Should have the videos listed on the two instances', async function () { @@ -284,12 +278,12 @@ Ajouter un sous-titre est vraiment facile`) const attributes = { name: 'transcoded video', - magnetUri: getMagnetURI(), + magnetUri: ImportsCommand.getMagnetURI(), channelId: channelIdServer2, privacy: VideoPrivacy.PUBLIC } - const res = await importVideo(servers[1].url, servers[1].accessToken, attributes) - const videoUUID = res.body.video.uuid + const { video } = await servers[1].importsCommand.importVideo({ attributes }) + const videoUUID = video.uuid await waitJobs(servers) @@ -335,12 +329,12 @@ Ajouter un sous-titre est vraiment facile`) const attributes = { name: 'hdr video', - targetUrl: getYoutubeHDRVideoUrl(), + targetUrl: ImportsCommand.getYoutubeHDRVideoUrl(), channelId: channelIdServer1, privacy: VideoPrivacy.PUBLIC } - const res1 = await importVideo(servers[0].url, servers[0].accessToken, attributes) - const videoUUID = res1.body.video.uuid + const { video: videoImported } = await servers[0].importsCommand.importVideo({ attributes }) + const videoUUID = videoImported.uuid await waitJobs(servers) diff --git a/server/tests/cli/peertube.ts b/server/tests/cli/peertube.ts index 0a4f54ffa..64a93ebb5 100644 --- a/server/tests/cli/peertube.ts +++ b/server/tests/cli/peertube.ts @@ -15,6 +15,7 @@ import { getLocalIdByUUID, getVideo, getVideosList, + ImportsCommand, removeVideo, ServerInfo, setAccessTokensToServers, @@ -23,7 +24,6 @@ import { userLogin, waitJobs } from '../../../shared/extra-utils' -import { getYoutubeVideoUrl } from '../../../shared/extra-utils/videos/video-imports' describe('Test CLI wrapper', function () { let server: ServerInfo @@ -122,7 +122,7 @@ describe('Test CLI wrapper', function () { this.timeout(60000) - const params = `--target-url ${getYoutubeVideoUrl()} --channel-name user_channel` + const params = `--target-url ${ImportsCommand.getYoutubeVideoUrl()} --channel-name user_channel` await cliCommand.execWithEnv(`${cmd} import ${params}`) }) @@ -155,7 +155,8 @@ describe('Test CLI wrapper', function () { this.timeout(60000) - const params = `--target-url ${getYoutubeVideoUrl()} --channel-name user_channel --video-name toto --nsfw --support support` + const params = `--target-url ${ImportsCommand.getYoutubeVideoUrl()} ` + + `--channel-name user_channel --video-name toto --nsfw --support support` await cliCommand.execWithEnv(`${cmd} import ${params}`) await waitJobs([ server ]) diff --git a/server/tests/plugins/filter-hooks.ts b/server/tests/plugins/filter-hooks.ts index 203642d8d..a3c3c0551 100644 --- a/server/tests/plugins/filter-hooks.ts +++ b/server/tests/plugins/filter-hooks.ts @@ -18,6 +18,7 @@ import { getVideosListPagination, getVideoThreadComments, getVideoWithToken, + ImportsCommand, makeRawRequest, PluginsCommand, registerUser, @@ -30,16 +31,7 @@ import { waitJobs, waitUntilLog } from '@shared/extra-utils' -import { getGoodVideoUrl, getMyVideoImports, importVideo } from '@shared/extra-utils/videos/video-imports' -import { - VideoCommentThreadTree, - VideoDetails, - VideoImport, - VideoImportState, - VideoPlaylist, - VideoPlaylistPrivacy, - VideoPrivacy -} from '@shared/models' +import { VideoCommentThreadTree, VideoDetails, VideoImportState, VideoPlaylist, VideoPlaylistPrivacy, VideoPrivacy } from '@shared/models' const expect = chai.expect @@ -157,23 +149,23 @@ describe('Test plugin filter hooks', function () { }) it('Should run filter:api.video.pre-import-url.accept.result', async function () { - const baseAttributes = { + const attributes = { name: 'normal title', privacy: VideoPrivacy.PUBLIC, channelId: servers[0].videoChannel.id, - targetUrl: getGoodVideoUrl() + 'bad' + targetUrl: ImportsCommand.getGoodVideoUrl() + 'bad' } - await importVideo(servers[0].url, servers[0].accessToken, baseAttributes, HttpStatusCode.FORBIDDEN_403) + await servers[0].importsCommand.importVideo({ attributes, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) it('Should run filter:api.video.pre-import-torrent.accept.result', async function () { - const baseAttributes = { + const attributes = { name: 'bad torrent', privacy: VideoPrivacy.PUBLIC, channelId: servers[0].videoChannel.id, torrentfile: 'video-720p.torrent' as any } - await importVideo(servers[0].url, servers[0].accessToken, baseAttributes, HttpStatusCode.FORBIDDEN_403) + await servers[0].importsCommand.importVideo({ attributes, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) it('Should run filter:api.video.post-import-url.accept.result', async function () { @@ -182,21 +174,21 @@ describe('Test plugin filter hooks', function () { let videoImportId: number { - const baseAttributes = { + const attributes = { name: 'title with bad word', privacy: VideoPrivacy.PUBLIC, channelId: servers[0].videoChannel.id, - targetUrl: getGoodVideoUrl() + targetUrl: ImportsCommand.getGoodVideoUrl() } - const res = await importVideo(servers[0].url, servers[0].accessToken, baseAttributes) - videoImportId = res.body.id + const body = await servers[0].importsCommand.importVideo({ attributes }) + videoImportId = body.id } await waitJobs(servers) { - const res = await getMyVideoImports(servers[0].url, servers[0].accessToken) - const videoImports = res.body.data as VideoImport[] + const body = await servers[0].importsCommand.getMyVideoImports() + const videoImports = body.data const videoImport = videoImports.find(i => i.id === videoImportId) @@ -211,21 +203,20 @@ describe('Test plugin filter hooks', function () { let videoImportId: number { - const baseAttributes = { + const attributes = { name: 'title with bad word', privacy: VideoPrivacy.PUBLIC, channelId: servers[0].videoChannel.id, torrentfile: 'video-720p.torrent' as any } - const res = await importVideo(servers[0].url, servers[0].accessToken, baseAttributes) - videoImportId = res.body.id + const body = await servers[0].importsCommand.importVideo({ attributes }) + videoImportId = body.id } await waitJobs(servers) { - const res = await getMyVideoImports(servers[0].url, servers[0].accessToken) - const videoImports = res.body.data as VideoImport[] + const { data: videoImports } = await servers[0].importsCommand.getMyVideoImports() const videoImport = videoImports.find(i => i.id === videoImportId) @@ -278,17 +269,15 @@ describe('Test plugin filter hooks', function () { describe('Should run filter:video.auto-blacklist.result', function () { - async function checkIsBlacklisted (oldRes: any, value: boolean) { - const videoId = oldRes.body.video.uuid - - const res = await getVideoWithToken(servers[0].url, servers[0].accessToken, videoId) + async function checkIsBlacklisted (id: number | string, value: boolean) { + const res = await getVideoWithToken(servers[0].url, servers[0].accessToken, id) const video: VideoDetails = res.body expect(video.blacklisted).to.equal(value) } it('Should blacklist on upload', async function () { const res = await uploadVideo(servers[0].url, servers[0].accessToken, { name: 'video please blacklist me' }) - await checkIsBlacklisted(res, true) + await checkIsBlacklisted(res.body.video.uuid, true) }) it('Should blacklist on import', async function () { @@ -296,20 +285,20 @@ describe('Test plugin filter hooks', function () { const attributes = { name: 'video please blacklist me', - targetUrl: getGoodVideoUrl(), + targetUrl: ImportsCommand.getGoodVideoUrl(), channelId: servers[0].videoChannel.id } - const res = await importVideo(servers[0].url, servers[0].accessToken, attributes) - await checkIsBlacklisted(res, true) + const body = await servers[0].importsCommand.importVideo({ attributes }) + await checkIsBlacklisted(body.video.uuid, true) }) it('Should blacklist on update', async function () { const res = await uploadVideo(servers[0].url, servers[0].accessToken, { name: 'video' }) const videoId = res.body.video.uuid - await checkIsBlacklisted(res, false) + await checkIsBlacklisted(videoId, false) await updateVideo(servers[0].url, servers[0].accessToken, videoId, { name: 'please blacklist me' }) - await checkIsBlacklisted(res, true) + await checkIsBlacklisted(videoId, true) }) it('Should blacklist on remote upload', async function () { @@ -318,7 +307,7 @@ describe('Test plugin filter hooks', function () { const res = await uploadVideo(servers[1].url, servers[1].accessToken, { name: 'remote please blacklist me' }) await waitJobs(servers) - await checkIsBlacklisted(res, true) + await checkIsBlacklisted(res.body.video.uuid, true) }) it('Should blacklist on remote update', async function () { @@ -328,12 +317,12 @@ describe('Test plugin filter hooks', function () { await waitJobs(servers) const videoId = res.body.video.uuid - await checkIsBlacklisted(res, false) + await checkIsBlacklisted(videoId, false) await updateVideo(servers[1].url, servers[1].accessToken, videoId, { name: 'please blacklist me' }) await waitJobs(servers) - await checkIsBlacklisted(res, true) + await checkIsBlacklisted(videoId, true) }) }) diff --git a/shared/extra-utils/server/servers.ts b/shared/extra-utils/server/servers.ts index bd5c29e51..95c876110 100644 --- a/shared/extra-utils/server/servers.ts +++ b/shared/extra-utils/server/servers.ts @@ -18,7 +18,16 @@ import { makeGetRequest } from '../requests/requests' import { SearchCommand } from '../search' import { SocketIOCommand } from '../socket' import { AccountsCommand, BlocklistCommand, SubscriptionsCommand } from '../users' -import { BlacklistCommand, CaptionsCommand, ChangeOwnershipCommand, HistoryCommand, LiveCommand, PlaylistsCommand, ServicesCommand } from '../videos' +import { + BlacklistCommand, + CaptionsCommand, + ChangeOwnershipCommand, + HistoryCommand, + ImportsCommand, + LiveCommand, + PlaylistsCommand, + ServicesCommand +} from '../videos' import { ConfigCommand } from './config-command' import { ContactFormCommand } from './contact-form-command' import { DebugCommand } from './debug-command' @@ -107,6 +116,7 @@ interface ServerInfo { changeOwnershipCommand?: ChangeOwnershipCommand playlistsCommand?: PlaylistsCommand historyCommand?: HistoryCommand + importsCommand?: ImportsCommand } function parallelTests () { @@ -339,6 +349,7 @@ async function runServer (server: ServerInfo, configOverrideArg?: any, args = [] server.changeOwnershipCommand = new ChangeOwnershipCommand(server) server.playlistsCommand = new PlaylistsCommand(server) server.historyCommand = new HistoryCommand(server) + server.importsCommand = new ImportsCommand(server) res(server) }) diff --git a/shared/extra-utils/videos/imports-command.ts b/shared/extra-utils/videos/imports-command.ts new file mode 100644 index 000000000..024aa363f --- /dev/null +++ b/shared/extra-utils/videos/imports-command.ts @@ -0,0 +1,86 @@ + +import { ResultList } from '@shared/models' +import { HttpStatusCode } from '../../core-utils/miscs/http-error-codes' +import { VideoImport, VideoImportCreate } from '../../models/videos' +import { unwrapBody } from '../requests' +import { AbstractCommand, OverrideCommandOptions } from '../shared' + +export class ImportsCommand extends AbstractCommand { + + static getYoutubeVideoUrl () { + return 'https://www.youtube.com/watch?v=msX3jv1XdvM' + } + + static getYoutubeHDRVideoUrl () { + /** + * The video is used to check format-selection correctness wrt. HDR, + * which brings its own set of oddities outside of a MediaSource. + * FIXME: refactor once HDR is supported at playback + * + * The video needs to have the following format_ids: + * (which you can check by using `youtube-dl -F`): + * - 303 (1080p webm vp9) + * - 299 (1080p mp4 avc1) + * - 335 (1080p webm vp9.2 HDR) + * + * 15 jan. 2021: TEST VIDEO NOT CURRENTLY PROVIDING + * - 400 (1080p mp4 av01) + * - 315 (2160p webm vp9 HDR) + * - 337 (2160p webm vp9.2 HDR) + * - 401 (2160p mp4 av01 HDR) + */ + return 'https://www.youtube.com/watch?v=qR5vOXbZsI4' + } + + static getMagnetURI () { + // eslint-disable-next-line max-len + return 'magnet:?xs=https%3A%2F%2Fpeertube2.cpy.re%2Fstatic%2Ftorrents%2Fb209ca00-c8bb-4b2b-b421-1ede169f3dbc-720.torrent&xt=urn:btih:0f498834733e8057ed5c6f2ee2b4efd8d84a76ee&dn=super+peertube2+video&tr=wss%3A%2F%2Fpeertube2.cpy.re%3A443%2Ftracker%2Fsocket&tr=https%3A%2F%2Fpeertube2.cpy.re%2Ftracker%2Fannounce&ws=https%3A%2F%2Fpeertube2.cpy.re%2Fstatic%2Fwebseed%2Fb209ca00-c8bb-4b2b-b421-1ede169f3dbc-720.mp4' + } + + static getBadVideoUrl () { + return 'https://download.cpy.re/peertube/bad_video.mp4' + } + + static getGoodVideoUrl () { + return 'https://download.cpy.re/peertube/good_video.mp4' + } + + importVideo (options: OverrideCommandOptions & { + attributes: VideoImportCreate & { torrentfile?: string } + }) { + const { attributes } = options + const path = '/api/v1/videos/imports' + + let attaches: any = {} + if (attributes.torrentfile) attaches = { torrentfile: attributes.torrentfile } + + return unwrapBody(this.postUploadRequest({ + ...options, + + path, + attaches, + fields: options.attributes, + implicitToken: true, + defaultExpectedStatus: HttpStatusCode.OK_200 + })) + } + + getMyVideoImports (options: OverrideCommandOptions & { + sort?: string + } = {}) { + const { sort } = options + const path = '/api/v1/users/me/videos/imports' + + const query = {} + if (sort) query['sort'] = sort + + return this.getRequestBody>({ + ...options, + + path, + query: { sort }, + implicitToken: true, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } +} diff --git a/shared/extra-utils/videos/index.ts b/shared/extra-utils/videos/index.ts index 74667fc06..372cf7a90 100644 --- a/shared/extra-utils/videos/index.ts +++ b/shared/extra-utils/videos/index.ts @@ -3,6 +3,7 @@ export * from './captions' export * from './captions-command' export * from './change-ownership-command' export * from './history-command' +export * from './imports-command' export * from './live-command' export * from './live' export * from './playlists-command' @@ -10,6 +11,5 @@ export * from './playlists' export * from './services-command' export * from './video-channels' export * from './video-comments' -export * from './video-imports' export * from './video-streaming-playlists' export * from './videos' diff --git a/shared/extra-utils/videos/video-imports.ts b/shared/extra-utils/videos/video-imports.ts deleted file mode 100644 index 81c0163cb..000000000 --- a/shared/extra-utils/videos/video-imports.ts +++ /dev/null @@ -1,90 +0,0 @@ - -import { VideoImportCreate } from '../../models/videos' -import { makeGetRequest, makeUploadRequest } from '../requests/requests' -import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' - -function getYoutubeVideoUrl () { - return 'https://www.youtube.com/watch?v=msX3jv1XdvM' -} - -function getYoutubeHDRVideoUrl () { - /** - * The video is used to check format-selection correctness wrt. HDR, - * which brings its own set of oddities outside of a MediaSource. - * FIXME: refactor once HDR is supported at playback - * - * The video needs to have the following format_ids: - * (which you can check by using `youtube-dl -F`): - * - 303 (1080p webm vp9) - * - 299 (1080p mp4 avc1) - * - 335 (1080p webm vp9.2 HDR) - * - * 15 jan. 2021: TEST VIDEO NOT CURRENTLY PROVIDING - * - 400 (1080p mp4 av01) - * - 315 (2160p webm vp9 HDR) - * - 337 (2160p webm vp9.2 HDR) - * - 401 (2160p mp4 av01 HDR) - */ - return 'https://www.youtube.com/watch?v=qR5vOXbZsI4' -} - -function getMagnetURI () { - // eslint-disable-next-line max-len - return 'magnet:?xs=https%3A%2F%2Fpeertube2.cpy.re%2Fstatic%2Ftorrents%2Fb209ca00-c8bb-4b2b-b421-1ede169f3dbc-720.torrent&xt=urn:btih:0f498834733e8057ed5c6f2ee2b4efd8d84a76ee&dn=super+peertube2+video&tr=wss%3A%2F%2Fpeertube2.cpy.re%3A443%2Ftracker%2Fsocket&tr=https%3A%2F%2Fpeertube2.cpy.re%2Ftracker%2Fannounce&ws=https%3A%2F%2Fpeertube2.cpy.re%2Fstatic%2Fwebseed%2Fb209ca00-c8bb-4b2b-b421-1ede169f3dbc-720.mp4' -} - -function getBadVideoUrl () { - return 'https://download.cpy.re/peertube/bad_video.mp4' -} - -function getGoodVideoUrl () { - return 'https://download.cpy.re/peertube/good_video.mp4' -} - -function importVideo ( - url: string, - token: string, - attributes: VideoImportCreate & { torrentfile?: string }, - statusCodeExpected = HttpStatusCode.OK_200 -) { - const path = '/api/v1/videos/imports' - - let attaches: any = {} - if (attributes.torrentfile) attaches = { torrentfile: attributes.torrentfile } - - return makeUploadRequest({ - url, - path, - token, - attaches, - fields: attributes, - statusCodeExpected - }) -} - -function getMyVideoImports (url: string, token: string, sort?: string) { - const path = '/api/v1/users/me/videos/imports' - - const query = {} - if (sort) query['sort'] = sort - - return makeGetRequest({ - url, - query, - path, - token, - statusCodeExpected: HttpStatusCode.OK_200 - }) -} - -// --------------------------------------------------------------------------- - -export { - getBadVideoUrl, - getYoutubeVideoUrl, - getYoutubeHDRVideoUrl, - importVideo, - getMagnetURI, - getMyVideoImports, - getGoodVideoUrl -} -- cgit v1.2.3 From 57f879a540551c3b958b0991c8e1e3657a4481d8 Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Fri, 9 Jul 2021 10:21:10 +0200 Subject: Introduce streaming playlists command --- server/tests/api/live/live.ts | 16 +++-- server/tests/api/redundancy/redundancy.ts | 2 +- server/tests/api/videos/video-hls.ts | 20 ++++-- shared/extra-utils/server/servers.ts | 5 +- shared/extra-utils/shared/abstract-command.ts | 45 ++++++++++-- shared/extra-utils/videos/index.ts | 3 +- .../videos/streaming-playlists-command.ts | 45 ++++++++++++ shared/extra-utils/videos/streaming-playlists.ts | 76 ++++++++++++++++++++ .../videos/video-streaming-playlists.ts | 82 ---------------------- 9 files changed, 190 insertions(+), 104 deletions(-) create mode 100644 shared/extra-utils/videos/streaming-playlists-command.ts create mode 100644 shared/extra-utils/videos/streaming-playlists.ts delete mode 100644 shared/extra-utils/videos/video-streaming-playlists.ts diff --git a/server/tests/api/live/live.ts b/server/tests/api/live/live.ts index cb52e4431..0b06df44c 100644 --- a/server/tests/api/live/live.ts +++ b/server/tests/api/live/live.ts @@ -15,7 +15,6 @@ import { doubleFollow, flushAndRunMultipleServers, getMyVideosWithFilter, - getPlaylist, getVideo, getVideosList, getVideosWithFilters, @@ -397,20 +396,27 @@ describe('Test live', function () { // Only finite files are displayed expect(hlsPlaylist.files).to.have.lengthOf(0) - await checkResolutionsInMasterPlaylist(hlsPlaylist.playlistUrl, resolutions) + await checkResolutionsInMasterPlaylist({ server, playlistUrl: hlsPlaylist.playlistUrl, resolutions }) for (let i = 0; i < resolutions.length; i++) { const segmentNum = 3 const segmentName = `${i}-00000${segmentNum}.ts` await commands[0].waitUntilSegmentGeneration({ videoUUID: video.uuid, resolution: i, segment: segmentNum }) - const res = await getPlaylist(`${servers[0].url}/static/streaming-playlists/hls/${video.uuid}/${i}.m3u8`) - const subPlaylist = res.text + const subPlaylist = await servers[0].streamingPlaylistsCommand.get({ + url: `${servers[0].url}/static/streaming-playlists/hls/${video.uuid}/${i}.m3u8` + }) expect(subPlaylist).to.contain(segmentName) const baseUrlAndPath = servers[0].url + '/static/streaming-playlists/hls' - await checkLiveSegmentHash(baseUrlAndPath, video.uuid, segmentName, hlsPlaylist) + await checkLiveSegmentHash({ + server, + baseUrlSegment: baseUrlAndPath, + videoUUID: video.uuid, + segmentName, + hlsPlaylist + }) } } } diff --git a/server/tests/api/redundancy/redundancy.ts b/server/tests/api/redundancy/redundancy.ts index e4ea99de6..d20cb80f1 100644 --- a/server/tests/api/redundancy/redundancy.ts +++ b/server/tests/api/redundancy/redundancy.ts @@ -203,7 +203,7 @@ async function check1PlaylistRedundancies (videoUUID?: string) { const hlsPlaylist = (res.body as VideoDetails).streamingPlaylists[0] for (const resolution of [ 240, 360, 480, 720 ]) { - await checkSegmentHash(baseUrlPlaylist, baseUrlSegment, videoUUID, resolution, hlsPlaylist) + await checkSegmentHash({ server: servers[1], baseUrlPlaylist, baseUrlSegment, videoUUID, resolution, hlsPlaylist }) } const directories = [ diff --git a/server/tests/api/videos/video-hls.ts b/server/tests/api/videos/video-hls.ts index 3821cfed0..3dd8c9066 100644 --- a/server/tests/api/videos/video-hls.ts +++ b/server/tests/api/videos/video-hls.ts @@ -12,7 +12,6 @@ import { cleanupTests, doubleFollow, flushAndRunMultipleServers, - getPlaylist, getVideo, makeRawRequest, removeVideo, @@ -67,10 +66,9 @@ async function checkHlsPlaylist (servers: ServerInfo[], videoUUID: string, hlsOn } { - await checkResolutionsInMasterPlaylist(hlsPlaylist.playlistUrl, resolutions) + await checkResolutionsInMasterPlaylist({ server, playlistUrl: hlsPlaylist.playlistUrl, resolutions }) - const res = await getPlaylist(hlsPlaylist.playlistUrl) - const masterPlaylist = res.text + const masterPlaylist = await server.streamingPlaylistsCommand.get({ url: hlsPlaylist.playlistUrl }) for (const resolution of resolutions) { expect(masterPlaylist).to.contain(`${resolution}.m3u8`) @@ -80,9 +78,10 @@ async function checkHlsPlaylist (servers: ServerInfo[], videoUUID: string, hlsOn { for (const resolution of resolutions) { - const res = await getPlaylist(`${baseUrl}/static/streaming-playlists/hls/${videoUUID}/${resolution}.m3u8`) + const subPlaylist = await server.streamingPlaylistsCommand.get({ + url: `${baseUrl}/static/streaming-playlists/hls/${videoUUID}/${resolution}.m3u8` + }) - const subPlaylist = res.text expect(subPlaylist).to.contain(`${videoUUID}-${resolution}-fragmented.mp4`) } } @@ -91,7 +90,14 @@ async function checkHlsPlaylist (servers: ServerInfo[], videoUUID: string, hlsOn const baseUrlAndPath = baseUrl + '/static/streaming-playlists/hls' for (const resolution of resolutions) { - await checkSegmentHash(baseUrlAndPath, baseUrlAndPath, videoUUID, resolution, hlsPlaylist) + await checkSegmentHash({ + server, + baseUrlPlaylist: baseUrlAndPath, + baseUrlSegment: baseUrlAndPath, + videoUUID, + resolution, + hlsPlaylist + }) } } } diff --git a/shared/extra-utils/server/servers.ts b/shared/extra-utils/server/servers.ts index 95c876110..6a1dadbcc 100644 --- a/shared/extra-utils/server/servers.ts +++ b/shared/extra-utils/server/servers.ts @@ -26,7 +26,8 @@ import { ImportsCommand, LiveCommand, PlaylistsCommand, - ServicesCommand + ServicesCommand, + StreamingPlaylistsCommand } from '../videos' import { ConfigCommand } from './config-command' import { ContactFormCommand } from './contact-form-command' @@ -117,6 +118,7 @@ interface ServerInfo { playlistsCommand?: PlaylistsCommand historyCommand?: HistoryCommand importsCommand?: ImportsCommand + streamingPlaylistsCommand?: StreamingPlaylistsCommand } function parallelTests () { @@ -350,6 +352,7 @@ async function runServer (server: ServerInfo, configOverrideArg?: any, args = [] server.playlistsCommand = new PlaylistsCommand(server) server.historyCommand = new HistoryCommand(server) server.importsCommand = new ImportsCommand(server) + server.streamingPlaylistsCommand = new StreamingPlaylistsCommand(server) res(server) }) diff --git a/shared/extra-utils/shared/abstract-command.ts b/shared/extra-utils/shared/abstract-command.ts index 1e07e9469..be368376f 100644 --- a/shared/extra-utils/shared/abstract-command.ts +++ b/shared/extra-utils/shared/abstract-command.ts @@ -16,6 +16,9 @@ export interface OverrideCommandOptions { } interface InternalCommonCommandOptions extends OverrideCommandOptions { + // Default to server.url + url?: string + path: string // If we automatically send the server token if the token is not provided implicitToken: boolean @@ -27,6 +30,7 @@ interface InternalGetCommandOptions extends InternalCommonCommandOptions { contentType?: string accept?: string redirects?: number + range?: string } abstract class AbstractCommand { @@ -55,6 +59,22 @@ abstract class AbstractCommand { return unwrapText(this.getRequest(options)) } + protected getRawRequest (options: Omit) { + const { url, range } = options + const { host, protocol, pathname } = new URL(url) + + return this.getRequest({ + ...options, + + token: this.buildCommonRequestToken(options), + defaultExpectedStatus: this.buildStatusCodeExpected(options), + + url: `${protocol}//${host}`, + path: pathname, + range + }) + } + protected getRequest (options: InternalGetCommandOptions) { const { redirects, query, contentType, accept } = options @@ -127,20 +147,31 @@ abstract class AbstractCommand { } private buildCommonRequestOptions (options: InternalCommonCommandOptions) { - const { token, expectedStatus, defaultExpectedStatus, path } = options + const { path } = options + + return { + url: this.server.url, + path, + + token: this.buildCommonRequestToken(options), + statusCodeExpected: this.buildStatusCodeExpected(options) + } + } + + private buildCommonRequestToken (options: Pick) { + const { token } = options const fallbackToken = options.implicitToken ? this.server.accessToken : undefined - return { - url: this.server.url, - path, + return token !== undefined ? token : fallbackToken + } - token: token !== undefined ? token : fallbackToken, + private buildStatusCodeExpected (options: Pick) { + const { expectedStatus, defaultExpectedStatus } = options - statusCodeExpected: expectedStatus ?? this.expectedStatus ?? defaultExpectedStatus - } + return expectedStatus ?? this.expectedStatus ?? defaultExpectedStatus } } diff --git a/shared/extra-utils/videos/index.ts b/shared/extra-utils/videos/index.ts index 372cf7a90..f87ae8eea 100644 --- a/shared/extra-utils/videos/index.ts +++ b/shared/extra-utils/videos/index.ts @@ -9,7 +9,8 @@ export * from './live' export * from './playlists-command' export * from './playlists' export * from './services-command' +export * from './streaming-playlists-command' +export * from './streaming-playlists' export * from './video-channels' export * from './video-comments' -export * from './video-streaming-playlists' export * from './videos' diff --git a/shared/extra-utils/videos/streaming-playlists-command.ts b/shared/extra-utils/videos/streaming-playlists-command.ts new file mode 100644 index 000000000..4caec7137 --- /dev/null +++ b/shared/extra-utils/videos/streaming-playlists-command.ts @@ -0,0 +1,45 @@ + +import { HttpStatusCode } from '../../core-utils/miscs/http-error-codes' +import { unwrapBody, unwrapText } from '../requests' +import { AbstractCommand, OverrideCommandOptions } from '../shared' + +export class StreamingPlaylistsCommand extends AbstractCommand { + + get (options: OverrideCommandOptions & { + url: string + }) { + return unwrapText(this.getRawRequest({ + ...options, + + url: options.url, + implicitToken: false, + defaultExpectedStatus: HttpStatusCode.OK_200 + })) + } + + getSegment (options: OverrideCommandOptions & { + url: string + range?: string + }) { + return unwrapText(this.getRawRequest({ + ...options, + + url: options.url, + range: options.range, + implicitToken: false, + defaultExpectedStatus: HttpStatusCode.OK_200, + })) + } + + getSegmentSha256 (options: OverrideCommandOptions & { + url: string + }) { + return unwrapBody<{ [ id: string ]: string }>(this.getRawRequest({ + ...options, + + url: options.url, + implicitToken: false, + defaultExpectedStatus: HttpStatusCode.OK_200 + })) + } +} diff --git a/shared/extra-utils/videos/streaming-playlists.ts b/shared/extra-utils/videos/streaming-playlists.ts new file mode 100644 index 000000000..0324c739a --- /dev/null +++ b/shared/extra-utils/videos/streaming-playlists.ts @@ -0,0 +1,76 @@ +import { expect } from 'chai' +import { sha256 } from '@server/helpers/core-utils' +import { HttpStatusCode } from '@shared/core-utils' +import { VideoStreamingPlaylist } from '@shared/models' +import { ServerInfo } from '../server' + +async function checkSegmentHash (options: { + server: ServerInfo + baseUrlPlaylist: string + baseUrlSegment: string + videoUUID: string + resolution: number + hlsPlaylist: VideoStreamingPlaylist +}) { + const { server, baseUrlPlaylist, baseUrlSegment, videoUUID, resolution, hlsPlaylist } = options + const command = server.streamingPlaylistsCommand + + const playlist = await command.get({ url: `${baseUrlPlaylist}/${videoUUID}/${resolution}.m3u8` }) + + const videoName = `${videoUUID}-${resolution}-fragmented.mp4` + + const matches = /#EXT-X-BYTERANGE:(\d+)@(\d+)/.exec(playlist) + + const length = parseInt(matches[1], 10) + const offset = parseInt(matches[2], 10) + const range = `${offset}-${offset + length - 1}` + + const segmentBody = await command.getSegment({ + url: `${baseUrlSegment}/${videoUUID}/${videoName}`, + expectedStatus: HttpStatusCode.PARTIAL_CONTENT_206, + range: `bytes=${range}` + }) + + const shaBody = await command.getSegmentSha256({ url: hlsPlaylist.segmentsSha256Url }) + expect(sha256(segmentBody)).to.equal(shaBody[videoName][range]) +} + +async function checkLiveSegmentHash (options: { + server: ServerInfo + baseUrlSegment: string + videoUUID: string + segmentName: string + hlsPlaylist: VideoStreamingPlaylist +}) { + const { server, baseUrlSegment, videoUUID, segmentName, hlsPlaylist } = options + const command = server.streamingPlaylistsCommand + + const segmentBody = await command.getSegment({ url: `${baseUrlSegment}/${videoUUID}/${segmentName}` }) + const shaBody = await command.getSegmentSha256({ url: hlsPlaylist.segmentsSha256Url }) + + expect(sha256(segmentBody)).to.equal(shaBody[segmentName]) +} + +async function checkResolutionsInMasterPlaylist (options: { + server: ServerInfo + playlistUrl: string + resolutions: number[] +}) { + const { server, playlistUrl, resolutions } = options + + const masterPlaylist = await server.streamingPlaylistsCommand.get({ url: playlistUrl }) + + for (const resolution of resolutions) { + const reg = new RegExp( + '#EXT-X-STREAM-INF:BANDWIDTH=\\d+,RESOLUTION=\\d+x' + resolution + ',(FRAME-RATE=\\d+,)?CODECS="avc1.64001f,mp4a.40.2"' + ) + + expect(masterPlaylist).to.match(reg) + } +} + +export { + checkSegmentHash, + checkLiveSegmentHash, + checkResolutionsInMasterPlaylist +} diff --git a/shared/extra-utils/videos/video-streaming-playlists.ts b/shared/extra-utils/videos/video-streaming-playlists.ts deleted file mode 100644 index 99c2e1880..000000000 --- a/shared/extra-utils/videos/video-streaming-playlists.ts +++ /dev/null @@ -1,82 +0,0 @@ -import { makeRawRequest } from '../requests/requests' -import { sha256 } from '../../../server/helpers/core-utils' -import { VideoStreamingPlaylist } from '../../models/videos/video-streaming-playlist.model' -import { expect } from 'chai' -import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' - -function getPlaylist (url: string, statusCodeExpected = HttpStatusCode.OK_200) { - return makeRawRequest(url, statusCodeExpected) -} - -function getSegment (url: string, statusCodeExpected = HttpStatusCode.OK_200, range?: string) { - return makeRawRequest(url, statusCodeExpected, range) -} - -function getSegmentSha256 (url: string, statusCodeExpected = HttpStatusCode.OK_200) { - return makeRawRequest(url, statusCodeExpected) -} - -async function checkSegmentHash ( - baseUrlPlaylist: string, - baseUrlSegment: string, - videoUUID: string, - resolution: number, - hlsPlaylist: VideoStreamingPlaylist -) { - const res = await getPlaylist(`${baseUrlPlaylist}/${videoUUID}/${resolution}.m3u8`) - const playlist = res.text - - const videoName = `${videoUUID}-${resolution}-fragmented.mp4` - - const matches = /#EXT-X-BYTERANGE:(\d+)@(\d+)/.exec(playlist) - - const length = parseInt(matches[1], 10) - const offset = parseInt(matches[2], 10) - const range = `${offset}-${offset + length - 1}` - - const res2 = await getSegment(`${baseUrlSegment}/${videoUUID}/${videoName}`, HttpStatusCode.PARTIAL_CONTENT_206, `bytes=${range}`) - - const resSha = await getSegmentSha256(hlsPlaylist.segmentsSha256Url) - - const sha256Server = resSha.body[videoName][range] - expect(sha256(res2.body)).to.equal(sha256Server) -} - -async function checkLiveSegmentHash ( - baseUrlSegment: string, - videoUUID: string, - segmentName: string, - hlsPlaylist: VideoStreamingPlaylist -) { - const res2 = await getSegment(`${baseUrlSegment}/${videoUUID}/${segmentName}`) - - const resSha = await getSegmentSha256(hlsPlaylist.segmentsSha256Url) - - const sha256Server = resSha.body[segmentName] - expect(sha256(res2.body)).to.equal(sha256Server) -} - -async function checkResolutionsInMasterPlaylist (playlistUrl: string, resolutions: number[]) { - const res = await getPlaylist(playlistUrl) - - const masterPlaylist = res.text - - for (const resolution of resolutions) { - const reg = new RegExp( - '#EXT-X-STREAM-INF:BANDWIDTH=\\d+,RESOLUTION=\\d+x' + resolution + ',(FRAME-RATE=\\d+,)?CODECS="avc1.64001f,mp4a.40.2"' - ) - - expect(masterPlaylist).to.match(reg) - } -} - -// --------------------------------------------------------------------------- - -export { - getPlaylist, - getSegment, - checkResolutionsInMasterPlaylist, - getSegmentSha256, - checkLiveSegmentHash, - checkSegmentHash -} -- cgit v1.2.3 From a54618880c394ad7571f3f3222dc96ec2dd10d9a Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Fri, 9 Jul 2021 11:21:30 +0200 Subject: Introduce channels command --- server/tests/api/check-params/users.ts | 5 +- server/tests/api/check-params/video-channels.ts | 18 +- .../tests/api/notifications/user-notifications.ts | 7 +- .../tests/api/redundancy/redundancy-constraints.ts | 3 +- .../search/search-activitypub-video-channels.ts | 30 +-- .../tests/api/search/search-activitypub-videos.ts | 5 +- server/tests/api/search/search-channels.ts | 12 +- server/tests/api/server/plugins.ts | 2 + server/tests/api/server/stats.ts | 7 +- server/tests/api/users/users-multiple-servers.ts | 15 +- server/tests/api/users/users.ts | 5 +- server/tests/api/videos/multiple-servers.ts | 8 +- server/tests/api/videos/video-channels.ts | 249 ++++++++------------- server/tests/api/videos/video-playlists.ts | 9 +- server/tests/cli/peertube.ts | 5 +- server/tests/cli/update-host.ts | 10 +- server/tests/client.ts | 6 +- server/tests/misc-endpoints.ts | 7 +- shared/extra-utils/server/servers.ts | 3 + shared/extra-utils/shared/abstract-command.ts | 21 ++ shared/extra-utils/videos/channels-command.ts | 157 +++++++++++++ shared/extra-utils/videos/channels.ts | 20 ++ shared/extra-utils/videos/index.ts | 5 +- shared/extra-utils/videos/video-channels.ts | 192 ---------------- shared/models/videos/channel/index.ts | 1 + .../channel/video-channel-create-result.model.ts | 3 + 26 files changed, 364 insertions(+), 441 deletions(-) create mode 100644 shared/extra-utils/videos/channels-command.ts create mode 100644 shared/extra-utils/videos/channels.ts delete mode 100644 shared/extra-utils/videos/video-channels.ts create mode 100644 shared/models/videos/channel/video-channel-create-result.model.ts diff --git a/server/tests/api/check-params/users.ts b/server/tests/api/check-params/users.ts index da0f55bf8..88fc8e8b1 100644 --- a/server/tests/api/check-params/users.ts +++ b/server/tests/api/check-params/users.ts @@ -5,7 +5,6 @@ import { omit } from 'lodash' import { User, UserRole, VideoCreateResult } from '../../../../shared' import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' import { - addVideoChannel, blockUser, buildAbsoluteFixturePath, cleanupTests, @@ -1041,8 +1040,8 @@ describe('Test users API validators', function () { }) it('Should fail with an existing channel', async function () { - const videoChannelAttributesArg = { name: 'existing_channel', displayName: 'hello', description: 'super description' } - await addVideoChannel(server.url, server.accessToken, videoChannelAttributesArg) + const attributes = { name: 'existing_channel', displayName: 'hello', description: 'super description' } + await server.channelsCommand.create({ attributes }) const fields = immutableAssign(baseCorrectParams, { channel: { name: 'existing_channel', displayName: 'toto' } }) diff --git a/server/tests/api/check-params/video-channels.ts b/server/tests/api/check-params/video-channels.ts index 5c02afd31..d29346dc3 100644 --- a/server/tests/api/check-params/video-channels.ts +++ b/server/tests/api/check-params/video-channels.ts @@ -6,11 +6,10 @@ import { omit } from 'lodash' import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' import { buildAbsoluteFixturePath, + ChannelsCommand, cleanupTests, createUser, - deleteVideoChannel, flushAndRunServer, - getAccountVideoChannelsList, immutableAssign, makeGetRequest, makePostBodyRequest, @@ -33,6 +32,7 @@ describe('Test video channels API validator', function () { const videoChannelPath = '/api/v1/video-channels' let server: ServerInfo let accessTokenUser: string + let command: ChannelsCommand // --------------------------------------------------------------- @@ -52,6 +52,8 @@ describe('Test video channels API validator', function () { await createUser({ url: server.url, accessToken: server.accessToken, username: user.username, password: user.password }) accessTokenUser = await userLogin(server, user) } + + command = server.channelsCommand }) describe('When listing a video channels', function () { @@ -84,7 +86,7 @@ describe('Test video channels API validator', function () { }) it('Should fail with a unknown account', async function () { - await getAccountVideoChannelsList({ url: server.url, accountName: 'unknown', specialStatus: HttpStatusCode.NOT_FOUND_404 }) + await server.channelsCommand.listByAccount({ accountName: 'unknown', expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) it('Should succeed with the correct parameters', async function () { @@ -327,23 +329,23 @@ describe('Test video channels API validator', function () { describe('When deleting a video channel', function () { it('Should fail with a non authenticated user', async function () { - await deleteVideoChannel(server.url, 'coucou', 'super_channel', HttpStatusCode.UNAUTHORIZED_401) + await command.delete({ token: 'coucou', channelName: 'super_channel', expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should fail with another authenticated user', async function () { - await deleteVideoChannel(server.url, accessTokenUser, 'super_channel', HttpStatusCode.FORBIDDEN_403) + await command.delete({ token: accessTokenUser, channelName: 'super_channel', expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) it('Should fail with an unknown video channel id', async function () { - await deleteVideoChannel(server.url, server.accessToken, 'super_channel2', HttpStatusCode.NOT_FOUND_404) + await command.delete({ channelName: 'super_channel2', expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) it('Should succeed with the correct parameters', async function () { - await deleteVideoChannel(server.url, server.accessToken, 'super_channel') + await command.delete({ channelName: 'super_channel' }) }) it('Should fail to delete the last user video channel', async function () { - await deleteVideoChannel(server.url, server.accessToken, 'root_channel', HttpStatusCode.CONFLICT_409) + await command.delete({ channelName: 'root_channel', expectedStatus: HttpStatusCode.CONFLICT_409 }) }) }) diff --git a/server/tests/api/notifications/user-notifications.ts b/server/tests/api/notifications/user-notifications.ts index a9315c818..1d159c48f 100644 --- a/server/tests/api/notifications/user-notifications.ts +++ b/server/tests/api/notifications/user-notifications.ts @@ -17,7 +17,6 @@ import { ServerInfo, updateMyUser, updateVideo, - updateVideoChannel, uploadRandomVideoOnServers, wait, waitJobs @@ -404,7 +403,11 @@ describe('Test user notifications', function () { displayName: 'super root 2 name' }) - await updateVideoChannel(servers[0].url, userAccessToken, 'user_1_channel', { displayName: myChannelName }) + await servers[0].channelsCommand.update({ + token: userAccessToken, + channelName: 'user_1_channel', + attributes: { displayName: myChannelName } + }) }) it('Should notify when a local channel is following one of our channel', async function () { diff --git a/server/tests/api/redundancy/redundancy-constraints.ts b/server/tests/api/redundancy/redundancy-constraints.ts index a666976b3..500b96747 100644 --- a/server/tests/api/redundancy/redundancy-constraints.ts +++ b/server/tests/api/redundancy/redundancy-constraints.ts @@ -1,6 +1,7 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ import 'mocha' +import { expect } from 'chai' import { cleanupTests, flushAndRunServer, @@ -15,8 +16,6 @@ import { } from '@shared/extra-utils' import { VideoPrivacy } from '@shared/models' -const expect = chai.expect - describe('Test redundancy constraints', function () { let remoteServer: ServerInfo let localServer: ServerInfo diff --git a/server/tests/api/search/search-activitypub-video-channels.ts b/server/tests/api/search/search-activitypub-video-channels.ts index cf5158b66..83be9cd1e 100644 --- a/server/tests/api/search/search-activitypub-video-channels.ts +++ b/server/tests/api/search/search-activitypub-video-channels.ts @@ -3,19 +3,15 @@ import 'mocha' import * as chai from 'chai' import { - addVideoChannel, cleanupTests, createUser, - deleteVideoChannel, flushAndRunMultipleServers, - getVideoChannelsList, getVideoChannelVideos, SearchCommand, ServerInfo, setAccessTokensToServers, updateMyUser, updateVideo, - updateVideoChannel, uploadVideo, userLogin, wait, @@ -45,7 +41,7 @@ describe('Test ActivityPub video channels search', function () { name: 'channel1_server1', displayName: 'Channel 1 server 1' } - await addVideoChannel(servers[0].url, servers[0].accessToken, channel) + await servers[0].channelsCommand.create({ attributes: channel }) } { @@ -57,8 +53,8 @@ describe('Test ActivityPub video channels search', function () { name: 'channel1_server2', displayName: 'Channel 1 server 2' } - const resChannel = await addVideoChannel(servers[1].url, userServer2Token, channel) - channelIdServer2 = resChannel.body.videoChannel.id + const created = await servers[1].channelsCommand.create({ token: userServer2Token, attributes: channel }) + channelIdServer2 = created.id const res = await uploadVideo(servers[1].url, userServer2Token, { name: 'video 1 server 2', channelId: channelIdServer2 }) videoServer2UUID = res.body.video.uuid @@ -143,12 +139,12 @@ describe('Test ActivityPub video channels search', function () { }) it('Should not list this remote video channel', async function () { - const res = await getVideoChannelsList(servers[0].url, 0, 5) - expect(res.body.total).to.equal(3) - expect(res.body.data).to.have.lengthOf(3) - expect(res.body.data[0].name).to.equal('channel1_server1') - expect(res.body.data[1].name).to.equal('user1_server1_channel') - expect(res.body.data[2].name).to.equal('root_channel') + const body = await servers[0].channelsCommand.list() + expect(body.total).to.equal(3) + expect(body.data).to.have.lengthOf(3) + expect(body.data[0].name).to.equal('channel1_server1') + expect(body.data[1].name).to.equal('user1_server1_channel') + expect(body.data[2].name).to.equal('root_channel') }) it('Should list video channel videos of server 2 without token', async function () { @@ -171,7 +167,11 @@ describe('Test ActivityPub video channels search', function () { it('Should update video channel of server 2, and refresh it on server 1', async function () { this.timeout(60000) - await updateVideoChannel(servers[1].url, userServer2Token, 'channel1_server2', { displayName: 'channel updated' }) + await servers[1].channelsCommand.update({ + token: userServer2Token, + channelName: 'channel1_server2', + attributes: { displayName: 'channel updated' } + }) await updateMyUser({ url: servers[1].url, accessToken: userServer2Token, displayName: 'user updated' }) await waitJobs(servers) @@ -217,7 +217,7 @@ describe('Test ActivityPub video channels search', function () { it('Should delete video channel of server 2, and delete it on server 1', async function () { this.timeout(60000) - await deleteVideoChannel(servers[1].url, userServer2Token, 'channel1_server2') + await servers[1].channelsCommand.delete({ token: userServer2Token, channelName: 'channel1_server2' }) await waitJobs(servers) // Expire video diff --git a/server/tests/api/search/search-activitypub-videos.ts b/server/tests/api/search/search-activitypub-videos.ts index 7c6455258..403c84010 100644 --- a/server/tests/api/search/search-activitypub-videos.ts +++ b/server/tests/api/search/search-activitypub-videos.ts @@ -3,7 +3,6 @@ import 'mocha' import * as chai from 'chai' import { - addVideoChannel, cleanupTests, flushAndRunMultipleServers, getVideosList, @@ -123,8 +122,8 @@ describe('Test ActivityPub videos search', function () { name: 'super_channel', displayName: 'super channel' } - const resChannel = await addVideoChannel(servers[1].url, servers[1].accessToken, channelAttributes) - const videoChannelId = resChannel.body.videoChannel.id + const created = await servers[1].channelsCommand.create({ attributes: channelAttributes }) + const videoChannelId = created.id const attributes = { name: 'updated', diff --git a/server/tests/api/search/search-channels.ts b/server/tests/api/search/search-channels.ts index 307bc063d..6c9ee73ce 100644 --- a/server/tests/api/search/search-channels.ts +++ b/server/tests/api/search/search-channels.ts @@ -2,15 +2,7 @@ import 'mocha' import * as chai from 'chai' -import { - addVideoChannel, - cleanupTests, - createUser, - flushAndRunServer, - SearchCommand, - ServerInfo, - setAccessTokensToServers -} from '@shared/extra-utils' +import { cleanupTests, createUser, flushAndRunServer, SearchCommand, ServerInfo, setAccessTokensToServers } from '@shared/extra-utils' import { VideoChannel } from '@shared/models' const expect = chai.expect @@ -32,7 +24,7 @@ describe('Test channels search', function () { name: 'squall_channel', displayName: 'Squall channel' } - await addVideoChannel(server.url, server.accessToken, channel) + await server.channelsCommand.create({ attributes: channel }) } command = server.searchCommand diff --git a/server/tests/api/server/plugins.ts b/server/tests/api/server/plugins.ts index 528bbbe58..e22ecfad9 100644 --- a/server/tests/api/server/plugins.ts +++ b/server/tests/api/server/plugins.ts @@ -37,6 +37,8 @@ describe('Test plugins', function () { } server = await flushAndRunServer(1, configOverride) await setAccessTokensToServers([ server ]) + + command = server.pluginsCommand }) it('Should list and search available plugins and themes', async function () { diff --git a/server/tests/api/server/stats.ts b/server/tests/api/server/stats.ts index c877a65eb..9c954c347 100644 --- a/server/tests/api/server/stats.ts +++ b/server/tests/api/server/stats.ts @@ -3,7 +3,6 @@ import 'mocha' import * as chai from 'chai' import { - addVideoChannel, addVideoCommentThread, cleanupTests, createUser, @@ -143,12 +142,12 @@ describe('Test stats (excluding redundancy)', function () { } { - const channelAttributes = { + const attributes = { name: 'stats_channel', displayName: 'My stats channel' } - const resChannel = await addVideoChannel(server.url, server.accessToken, channelAttributes) - channelId = resChannel.body.videoChannel.id + const created = await server.channelsCommand.create({ attributes }) + channelId = created.id const data = await server.statsCommand.get() diff --git a/server/tests/api/users/users-multiple-servers.ts b/server/tests/api/users/users-multiple-servers.ts index 03fbfabeb..47056be78 100644 --- a/server/tests/api/users/users-multiple-servers.ts +++ b/server/tests/api/users/users-multiple-servers.ts @@ -12,7 +12,6 @@ import { flushAndRunMultipleServers, getAccountVideos, getMyUserInformation, - getVideoChannelsList, removeUser, ServerInfo, setAccessTokensToServers, @@ -23,7 +22,7 @@ import { userLogin, waitJobs } from '@shared/extra-utils' -import { User, VideoChannel } from '@shared/models' +import { User } from '@shared/models' const expect = chai.expect @@ -199,10 +198,8 @@ describe('Test users with multiple servers', function () { const accountDeleted = body.data.find(a => a.name === 'user1' && a.host === 'localhost:' + servers[0].port) expect(accountDeleted).not.to.be.undefined - const resVideoChannels = await getVideoChannelsList(server.url, 0, 10) - const videoChannelDeleted = resVideoChannels.body.data.find(a => { - return a.displayName === 'Main user1 channel' && a.host === 'localhost:' + servers[0].port - }) as VideoChannel + const { data } = await server.channelsCommand.list() + const videoChannelDeleted = data.find(a => a.displayName === 'Main user1 channel' && a.host === 'localhost:' + servers[0].port) expect(videoChannelDeleted).not.to.be.undefined } @@ -216,10 +213,8 @@ describe('Test users with multiple servers', function () { const accountDeleted = body.data.find(a => a.name === 'user1' && a.host === 'localhost:' + servers[0].port) expect(accountDeleted).to.be.undefined - const resVideoChannels = await getVideoChannelsList(server.url, 0, 10) - const videoChannelDeleted = resVideoChannels.body.data.find(a => { - return a.name === 'Main user1 channel' && a.host === 'localhost:' + servers[0].port - }) as VideoChannel + const { data } = await server.channelsCommand.list() + const videoChannelDeleted = data.find(a => a.name === 'Main user1 channel' && a.host === 'localhost:' + servers[0].port) expect(videoChannelDeleted).to.be.undefined } }) diff --git a/server/tests/api/users/users.ts b/server/tests/api/users/users.ts index 4b9056306..ed670b3c9 100644 --- a/server/tests/api/users/users.ts +++ b/server/tests/api/users/users.ts @@ -18,7 +18,6 @@ import { getUserInformation, getUsersList, getUsersListPaginationAndSort, - getVideoChannel, getVideosList, killallServers, login, @@ -864,9 +863,9 @@ describe('Test users', function () { }) it('Should have created the channel', async function () { - const res = await getVideoChannel(server.url, 'my_user_15_channel') + const { displayName } = await server.channelsCommand.get({ channelName: 'my_user_15_channel' }) - expect(res.body.displayName).to.equal('my channel rocks') + expect(displayName).to.equal('my channel rocks') }) it('Should remove me', async function () { diff --git a/server/tests/api/videos/multiple-servers.ts b/server/tests/api/videos/multiple-servers.ts index a8c8a889b..a59d5a858 100644 --- a/server/tests/api/videos/multiple-servers.ts +++ b/server/tests/api/videos/multiple-servers.ts @@ -5,7 +5,6 @@ import * as chai from 'chai' import * as request from 'supertest' import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' import { - addVideoChannel, buildAbsoluteFixturePath, checkTmpIsEmpty, checkVideoFilesWereRemoved, @@ -17,7 +16,6 @@ import { flushAndRunMultipleServers, getLocalVideos, getVideo, - getVideoChannelsList, getVideosList, rateVideo, removeVideo, @@ -64,9 +62,9 @@ describe('Test multiple servers', function () { displayName: 'my channel', description: 'super channel' } - await addVideoChannel(servers[0].url, servers[0].accessToken, videoChannel) - const channelRes = await getVideoChannelsList(servers[0].url, 0, 1) - videoChannelId = channelRes.body.data[0].id + await servers[0].channelsCommand.create({ attributes: videoChannel }) + const { data } = await servers[0].channelsCommand.list({ start: 0, count: 1 }) + videoChannelId = data[0].id } // Server 1 and server 2 follow each other diff --git a/server/tests/api/videos/video-channels.ts b/server/tests/api/videos/video-channels.ts index 865098777..daf066eb1 100644 --- a/server/tests/api/videos/video-channels.ts +++ b/server/tests/api/videos/video-channels.ts @@ -7,43 +7,29 @@ import { ACTOR_IMAGES_SIZE } from '@server/initializers/constants' import { cleanupTests, createUser, - deleteVideoChannelImage, doubleFollow, flushAndRunMultipleServers, getActorImage, getVideo, - getVideoChannel, getVideoChannelVideos, setDefaultVideoChannel, testFileExistsOrNot, testImage, updateVideo, - updateVideoChannelImage, uploadVideo, userLogin, wait } from '../../../../shared/extra-utils' -import { - addVideoChannel, - deleteVideoChannel, - getAccountVideoChannelsList, - getMyUserInformation, - getVideoChannelsList, - ServerInfo, - setAccessTokensToServers, - updateVideoChannel, - viewVideo -} from '../../../../shared/extra-utils/index' +import { getMyUserInformation, ServerInfo, setAccessTokensToServers, viewVideo } from '../../../../shared/extra-utils/index' import { waitJobs } from '../../../../shared/extra-utils/server/jobs' import { User, Video, VideoChannel, VideoDetails } from '../../../../shared/index' const expect = chai.expect async function findChannel (server: ServerInfo, channelId: number) { - const res = await getVideoChannelsList(server.url, 0, 5, '-name') - const videoChannel = res.body.data.find(c => c.id === channelId) + const body = await server.channelsCommand.list({ sort: '-name' }) - return videoChannel as VideoChannel + return body.data.find(c => c.id === channelId) } describe('Test video channels', function () { @@ -69,11 +55,11 @@ describe('Test video channels', function () { }) it('Should have one video channel (created with root)', async () => { - const res = await getVideoChannelsList(servers[0].url, 0, 2) + const body = await servers[0].channelsCommand.list({ start: 0, count: 2 }) - expect(res.body.total).to.equal(1) - expect(res.body.data).to.be.an('array') - expect(res.body.data).to.have.lengthOf(1) + expect(body.total).to.equal(1) + expect(body.data).to.be.an('array') + expect(body.data).to.have.lengthOf(1) }) it('Should create another video channel', async function () { @@ -86,8 +72,8 @@ describe('Test video channels', function () { description: 'super video channel description', support: 'super video channel support text' } - const res = await addVideoChannel(servers[0].url, servers[0].accessToken, videoChannel) - secondVideoChannelId = res.body.videoChannel.id + const created = await servers[0].channelsCommand.create({ attributes: videoChannel }) + secondVideoChannelId = created.id } // The channel is 1 is propagated to servers 2 @@ -120,16 +106,14 @@ describe('Test video channels', function () { }) it('Should have two video channels when getting account channels on server 1', async function () { - const res = await getAccountVideoChannelsList({ - url: servers[0].url, - accountName - }) + const body = await servers[0].channelsCommand.listByAccount({ accountName }) + expect(body.total).to.equal(2) - expect(res.body.total).to.equal(2) - expect(res.body.data).to.be.an('array') - expect(res.body.data).to.have.lengthOf(2) + const videoChannels = body.data + + expect(videoChannels).to.be.an('array') + expect(videoChannels).to.have.lengthOf(2) - const videoChannels = res.body.data expect(videoChannels[0].name).to.equal('root_channel') expect(videoChannels[0].displayName).to.equal('Main root channel') @@ -141,79 +125,69 @@ describe('Test video channels', function () { it('Should paginate and sort account channels', async function () { { - const res = await getAccountVideoChannelsList({ - url: servers[0].url, + const body = await servers[0].channelsCommand.listByAccount({ accountName, start: 0, count: 1, sort: 'createdAt' }) - expect(res.body.total).to.equal(2) - expect(res.body.data).to.have.lengthOf(1) + expect(body.total).to.equal(2) + expect(body.data).to.have.lengthOf(1) - const videoChannel: VideoChannel = res.body.data[0] + const videoChannel: VideoChannel = body.data[0] expect(videoChannel.name).to.equal('root_channel') } { - const res = await getAccountVideoChannelsList({ - url: servers[0].url, + const body = await servers[0].channelsCommand.listByAccount({ accountName, start: 0, count: 1, sort: '-createdAt' }) - expect(res.body.total).to.equal(2) - expect(res.body.data).to.have.lengthOf(1) - - const videoChannel: VideoChannel = res.body.data[0] - expect(videoChannel.name).to.equal('second_video_channel') + expect(body.total).to.equal(2) + expect(body.data).to.have.lengthOf(1) + expect(body.data[0].name).to.equal('second_video_channel') } { - const res = await getAccountVideoChannelsList({ - url: servers[0].url, + const body = await servers[0].channelsCommand.listByAccount({ accountName, start: 1, count: 1, sort: '-createdAt' }) - expect(res.body.total).to.equal(2) - expect(res.body.data).to.have.lengthOf(1) - - const videoChannel: VideoChannel = res.body.data[0] - expect(videoChannel.name).to.equal('root_channel') + expect(body.total).to.equal(2) + expect(body.data).to.have.lengthOf(1) + expect(body.data[0].name).to.equal('root_channel') } }) it('Should have one video channel when getting account channels on server 2', async function () { - const res = await getAccountVideoChannelsList({ - url: servers[1].url, - accountName - }) + const body = await servers[1].channelsCommand.listByAccount({ accountName }) - expect(res.body.total).to.equal(1) - expect(res.body.data).to.be.an('array') - expect(res.body.data).to.have.lengthOf(1) + expect(body.total).to.equal(1) + expect(body.data).to.be.an('array') + expect(body.data).to.have.lengthOf(1) - const videoChannels = res.body.data - expect(videoChannels[0].name).to.equal('second_video_channel') - expect(videoChannels[0].displayName).to.equal('second video channel') - expect(videoChannels[0].description).to.equal('super video channel description') - expect(videoChannels[0].support).to.equal('super video channel support text') + const videoChannel = body.data[0] + expect(videoChannel.name).to.equal('second_video_channel') + expect(videoChannel.displayName).to.equal('second video channel') + expect(videoChannel.description).to.equal('super video channel description') + expect(videoChannel.support).to.equal('super video channel support text') }) it('Should list video channels', async function () { - const res = await getVideoChannelsList(servers[0].url, 1, 1, '-name') + const body = await servers[0].channelsCommand.list({ start: 1, count: 1, sort: '-name' }) - expect(res.body.total).to.equal(2) - expect(res.body.data).to.be.an('array') - expect(res.body.data).to.have.lengthOf(1) - expect(res.body.data[0].name).to.equal('root_channel') - expect(res.body.data[0].displayName).to.equal('Main root channel') + expect(body.total).to.equal(2) + expect(body.data).to.be.an('array') + expect(body.data).to.have.lengthOf(1) + expect(body.data[0].name).to.equal('root_channel') + expect(body.data[0].displayName).to.equal('Main root channel') }) it('Should update video channel', async function () { @@ -225,22 +199,23 @@ describe('Test video channels', function () { support: 'support updated' } - await updateVideoChannel(servers[0].url, servers[0].accessToken, 'second_video_channel', videoChannelAttributes) + await servers[0].channelsCommand.update({ channelName: 'second_video_channel', attributes: videoChannelAttributes }) await waitJobs(servers) }) it('Should have video channel updated', async function () { for (const server of servers) { - const res = await getVideoChannelsList(server.url, 0, 1, '-name') - - expect(res.body.total).to.equal(2) - expect(res.body.data).to.be.an('array') - expect(res.body.data).to.have.lengthOf(1) - expect(res.body.data[0].name).to.equal('second_video_channel') - expect(res.body.data[0].displayName).to.equal('video channel updated') - expect(res.body.data[0].description).to.equal('video channel description updated') - expect(res.body.data[0].support).to.equal('support updated') + const body = await server.channelsCommand.list({ start: 0, count: 1, sort: '-name' }) + + expect(body.total).to.equal(2) + expect(body.data).to.be.an('array') + expect(body.data).to.have.lengthOf(1) + + expect(body.data[0].name).to.equal('second_video_channel') + expect(body.data[0].displayName).to.equal('video channel updated') + expect(body.data[0].description).to.equal('video channel description updated') + expect(body.data[0].support).to.equal('support updated') } }) @@ -261,7 +236,7 @@ describe('Test video channels', function () { bulkVideosSupportUpdate: true } - await updateVideoChannel(servers[0].url, servers[0].accessToken, 'second_video_channel', videoChannelAttributes) + await servers[0].channelsCommand.update({ channelName: 'second_video_channel', attributes: videoChannelAttributes }) await waitJobs(servers) @@ -278,10 +253,8 @@ describe('Test video channels', function () { const fixture = 'avatar.png' - await updateVideoChannelImage({ - url: servers[0].url, - accessToken: servers[0].accessToken, - videoChannelName: 'second_video_channel', + await servers[0].channelsCommand.updateImage({ + channelName: 'second_video_channel', fixture, type: 'avatar' }) @@ -306,10 +279,8 @@ describe('Test video channels', function () { const fixture = 'banner.jpg' - await updateVideoChannelImage({ - url: servers[0].url, - accessToken: servers[0].accessToken, - videoChannelName: 'second_video_channel', + await servers[0].channelsCommand.updateImage({ + channelName: 'second_video_channel', fixture, type: 'banner' }) @@ -317,8 +288,7 @@ describe('Test video channels', function () { await waitJobs(servers) for (const server of servers) { - const res = await getVideoChannel(server.url, 'second_video_channel@' + servers[0].host) - const videoChannel = res.body + const videoChannel = await server.channelsCommand.get({ channelName: 'second_video_channel@' + servers[0].host }) bannerPaths[server.port] = videoChannel.banner.path await testImage(server.url, 'banner-resized', bannerPaths[server.port]) @@ -333,12 +303,7 @@ describe('Test video channels', function () { it('Should delete the video channel avatar', async function () { this.timeout(15000) - await deleteVideoChannelImage({ - url: servers[0].url, - accessToken: servers[0].accessToken, - videoChannelName: 'second_video_channel', - type: 'avatar' - }) + await servers[0].channelsCommand.deleteImage({ channelName: 'second_video_channel', type: 'avatar' }) await waitJobs(servers) @@ -353,12 +318,7 @@ describe('Test video channels', function () { it('Should delete the video channel banner', async function () { this.timeout(15000) - await deleteVideoChannelImage({ - url: servers[0].url, - accessToken: servers[0].accessToken, - videoChannelName: 'second_video_channel', - type: 'banner' - }) + await servers[0].channelsCommand.deleteImage({ channelName: 'second_video_channel', type: 'banner' }) await waitJobs(servers) @@ -411,23 +371,23 @@ describe('Test video channels', function () { }) it('Should delete video channel', async function () { - await deleteVideoChannel(servers[0].url, servers[0].accessToken, 'second_video_channel') + await servers[0].channelsCommand.delete({ channelName: 'second_video_channel' }) }) it('Should have video channel deleted', async function () { - const res = await getVideoChannelsList(servers[0].url, 0, 10) + const body = await servers[0].channelsCommand.list({ start: 0, count: 10 }) - expect(res.body.total).to.equal(1) - expect(res.body.data).to.be.an('array') - expect(res.body.data).to.have.lengthOf(1) - expect(res.body.data[0].displayName).to.equal('Main root channel') + expect(body.total).to.equal(1) + expect(body.data).to.be.an('array') + expect(body.data).to.have.lengthOf(1) + expect(body.data[0].displayName).to.equal('Main root channel') }) it('Should create the main channel with an uuid if there is a conflict', async function () { { const videoChannel = { name: 'toto_channel', displayName: 'My toto channel' } - const res = await addVideoChannel(servers[0].url, servers[0].accessToken, videoChannel) - totoChannel = res.body.videoChannel.id + const created = await servers[0].channelsCommand.create({ attributes: videoChannel }) + totoChannel = created.id } { @@ -444,15 +404,9 @@ describe('Test video channels', function () { this.timeout(10000) { - const res = await getAccountVideoChannelsList({ - url: servers[0].url, - accountName, - withStats: true - }) - - const channels: VideoChannel[] = res.body.data + const { data } = await servers[0].channelsCommand.listByAccount({ accountName, withStats: true }) - for (const channel of channels) { + for (const channel of data) { expect(channel).to.haveOwnProperty('viewsPerDay') expect(channel.viewsPerDay).to.have.length(30 + 1) // daysPrior + today @@ -471,26 +425,17 @@ describe('Test video channels', function () { // Wait the repeatable job await wait(8000) - const res = await getAccountVideoChannelsList({ - url: servers[0].url, - accountName, - withStats: true - }) - const channelWithView = res.body.data.find((channel: VideoChannel) => channel.id === servers[0].videoChannel.id) + const { data } = await servers[0].channelsCommand.listByAccount({ accountName, withStats: true }) + const channelWithView = data.find(channel => channel.id === servers[0].videoChannel.id) expect(channelWithView.viewsPerDay.slice(-1)[0].views).to.equal(2) } }) it('Should report correct videos count', async function () { - const res = await getAccountVideoChannelsList({ - url: servers[0].url, - accountName, - withStats: true - }) - const channels: VideoChannel[] = res.body.data + const { data } = await servers[0].channelsCommand.listByAccount({ accountName, withStats: true }) - const totoChannel = channels.find(c => c.name === 'toto_channel') - const rootChannel = channels.find(c => c.name === 'root_channel') + const totoChannel = data.find(c => c.name === 'toto_channel') + const rootChannel = data.find(c => c.name === 'root_channel') expect(rootChannel.videosCount).to.equal(1) expect(totoChannel.videosCount).to.equal(0) @@ -498,26 +443,18 @@ describe('Test video channels', function () { it('Should search among account video channels', async function () { { - const res = await getAccountVideoChannelsList({ - url: servers[0].url, - accountName, - search: 'root' - }) - expect(res.body.total).to.equal(1) + const body = await servers[0].channelsCommand.listByAccount({ accountName, search: 'root' }) + expect(body.total).to.equal(1) - const channels = res.body.data + const channels = body.data expect(channels).to.have.lengthOf(1) } { - const res = await getAccountVideoChannelsList({ - url: servers[0].url, - accountName, - search: 'does not exist' - }) - expect(res.body.total).to.equal(0) + const body = await servers[0].channelsCommand.listByAccount({ accountName, search: 'does not exist' }) + expect(body.total).to.equal(0) - const channels = res.body.data + const channels = body.data expect(channels).to.have.lengthOf(0) } }) @@ -529,30 +466,20 @@ describe('Test video channels', function () { await waitJobs(servers) for (const server of servers) { - const res = await getAccountVideoChannelsList({ - url: server.url, - accountName, - sort: '-updatedAt' - }) + const { data } = await server.channelsCommand.listByAccount({ accountName, sort: '-updatedAt' }) - const channels: VideoChannel[] = res.body.data - expect(channels[0].name).to.equal('toto_channel') - expect(channels[1].name).to.equal('root_channel') + expect(data[0].name).to.equal('toto_channel') + expect(data[1].name).to.equal('root_channel') } await uploadVideo(servers[0].url, servers[0].accessToken, { channelId: servers[0].videoChannel.id }) await waitJobs(servers) for (const server of servers) { - const res = await getAccountVideoChannelsList({ - url: server.url, - accountName, - sort: '-updatedAt' - }) + const { data } = await server.channelsCommand.listByAccount({ accountName, sort: '-updatedAt' }) - const channels: VideoChannel[] = res.body.data - expect(channels[0].name).to.equal('root_channel') - expect(channels[1].name).to.equal('toto_channel') + expect(data[0].name).to.equal('root_channel') + expect(data[1].name).to.equal('toto_channel') } }) diff --git a/server/tests/api/videos/video-playlists.ts b/server/tests/api/videos/video-playlists.ts index 4de6b3abf..2bb019348 100644 --- a/server/tests/api/videos/video-playlists.ts +++ b/server/tests/api/videos/video-playlists.ts @@ -4,11 +4,9 @@ import 'mocha' import * as chai from 'chai' import { HttpStatusCode } from '@shared/core-utils' import { - addVideoChannel, checkPlaylistFilesWereRemoved, cleanupTests, createUser, - deleteVideoChannel, doubleFollow, flushAndRunMultipleServers, generateUserAccessToken, @@ -1096,20 +1094,19 @@ describe('Test video playlists', function () { it('Should delete a channel and put the associated playlist in private mode', async function () { this.timeout(30000) - const res = await addVideoChannel(servers[0].url, servers[0].accessToken, { name: 'super_channel', displayName: 'super channel' }) - const videoChannelId = res.body.videoChannel.id + const channel = await servers[0].channelsCommand.create({ attributes: { name: 'super_channel', displayName: 'super channel' } }) const playlistCreated = await commands[0].create({ attributes: { displayName: 'channel playlist', privacy: VideoPlaylistPrivacy.PUBLIC, - videoChannelId + videoChannelId: channel.id } }) await waitJobs(servers) - await deleteVideoChannel(servers[0].url, servers[0].accessToken, 'super_channel') + await servers[0].channelsCommand.delete({ channelName: 'super_channel' }) await waitJobs(servers) diff --git a/server/tests/cli/peertube.ts b/server/tests/cli/peertube.ts index 64a93ebb5..ef7ab5bd5 100644 --- a/server/tests/cli/peertube.ts +++ b/server/tests/cli/peertube.ts @@ -4,7 +4,6 @@ import 'mocha' import { expect } from 'chai' import { Video, VideoDetails } from '../../../shared' import { - addVideoChannel, areHttpImportTestsDisabled, buildAbsoluteFixturePath, cleanupTests, @@ -44,8 +43,8 @@ describe('Test CLI wrapper', function () { userAccessToken = await userLogin(server, { username: 'user_1', password: 'super_password' }) { - const args = { name: 'user_channel', displayName: 'User channel', support: 'super support text' } - await addVideoChannel(server.url, userAccessToken, args) + const attributes = { name: 'user_channel', displayName: 'User channel', support: 'super support text' } + await server.channelsCommand.create({ token: userAccessToken, attributes }) } cliCommand = server.cliCommand diff --git a/server/tests/cli/update-host.ts b/server/tests/cli/update-host.ts index f6131a99f..09a3dd1e7 100644 --- a/server/tests/cli/update-host.ts +++ b/server/tests/cli/update-host.ts @@ -2,13 +2,11 @@ import 'mocha' import { - addVideoChannel, addVideoCommentThread, cleanupTests, createUser, flushAndRunServer, getVideo, - getVideoChannelsList, getVideosList, killallServers, makeActivityPubGetRequest, @@ -53,7 +51,7 @@ describe('Test update host scripts', function () { displayName: 'second video channel', description: 'super video channel description' } - await addVideoChannel(server.url, server.accessToken, videoChannel) + await server.channelsCommand.create({ attributes: videoChannel }) // Create comments const text = 'my super first comment' @@ -91,10 +89,10 @@ describe('Test update host scripts', function () { }) it('Should have updated video channels url', async function () { - const res = await getVideoChannelsList(server.url, 0, 5, '-name') - expect(res.body.total).to.equal(3) + const { data, total } = await server.channelsCommand.list({ sort: '-name' }) + expect(total).to.equal(3) - for (const channel of res.body.data) { + for (const channel of data) { const { body } = await makeActivityPubGetRequest(server.url, '/video-channels/' + channel.name) expect(body.id).to.equal('http://localhost:9002/video-channels/' + channel.name) diff --git a/server/tests/client.ts b/server/tests/client.ts index 129f1e1c0..1bdb2eb64 100644 --- a/server/tests/client.ts +++ b/server/tests/client.ts @@ -16,7 +16,6 @@ import { setAccessTokensToServers, setDefaultVideoChannel, updateMyUser, - updateVideoChannel, uploadVideo, waitJobs } from '../../shared/extra-utils' @@ -63,7 +62,10 @@ describe('Test a client controllers', function () { await setDefaultVideoChannel(servers) - await updateVideoChannel(servers[0].url, servers[0].accessToken, servers[0].videoChannel.name, { description: channelDescription }) + await servers[0].channelsCommand.update({ + channelName: servers[0].videoChannel.name, + attributes: { description: channelDescription } + }) // Video diff --git a/server/tests/misc-endpoints.ts b/server/tests/misc-endpoints.ts index 09e5afcf9..4b7b2163d 100644 --- a/server/tests/misc-endpoints.ts +++ b/server/tests/misc-endpoints.ts @@ -2,8 +2,8 @@ import 'mocha' import * as chai from 'chai' +import { HttpStatusCode } from '@shared/core-utils' import { - addVideoChannel, cleanupTests, createUser, flushAndRunServer, @@ -13,7 +13,6 @@ import { uploadVideo } from '../../shared/extra-utils' import { VideoPrivacy } from '../../shared/models/videos' -import { HttpStatusCode } from '@shared/core-utils' const expect = chai.expect @@ -171,8 +170,8 @@ describe('Test misc endpoints', function () { await uploadVideo(server.url, server.accessToken, { name: 'video 2', nsfw: false }) await uploadVideo(server.url, server.accessToken, { name: 'video 3', privacy: VideoPrivacy.PRIVATE }) - await addVideoChannel(server.url, server.accessToken, { name: 'channel1', displayName: 'channel 1' }) - await addVideoChannel(server.url, server.accessToken, { name: 'channel2', displayName: 'channel 2' }) + await server.channelsCommand.create({ attributes: { name: 'channel1', displayName: 'channel 1' } }) + await server.channelsCommand.create({ attributes: { name: 'channel2', displayName: 'channel 2' } }) await createUser({ url: server.url, accessToken: server.accessToken, username: 'user1', password: 'password' }) await createUser({ url: server.url, accessToken: server.accessToken, username: 'user2', password: 'password' }) diff --git a/shared/extra-utils/server/servers.ts b/shared/extra-utils/server/servers.ts index 6a1dadbcc..68e10af5f 100644 --- a/shared/extra-utils/server/servers.ts +++ b/shared/extra-utils/server/servers.ts @@ -22,6 +22,7 @@ import { BlacklistCommand, CaptionsCommand, ChangeOwnershipCommand, + ChannelsCommand, HistoryCommand, ImportsCommand, LiveCommand, @@ -119,6 +120,7 @@ interface ServerInfo { historyCommand?: HistoryCommand importsCommand?: ImportsCommand streamingPlaylistsCommand?: StreamingPlaylistsCommand + channelsCommand?: ChannelsCommand } function parallelTests () { @@ -353,6 +355,7 @@ async function runServer (server: ServerInfo, configOverrideArg?: any, args = [] server.historyCommand = new HistoryCommand(server) server.importsCommand = new ImportsCommand(server) server.streamingPlaylistsCommand = new StreamingPlaylistsCommand(server) + server.channelsCommand = new ChannelsCommand(server) res(server) }) diff --git a/shared/extra-utils/shared/abstract-command.ts b/shared/extra-utils/shared/abstract-command.ts index be368376f..6a9ab1348 100644 --- a/shared/extra-utils/shared/abstract-command.ts +++ b/shared/extra-utils/shared/abstract-command.ts @@ -1,4 +1,6 @@ +import { isAbsolute, join } from 'path' import { HttpStatusCode } from '@shared/core-utils' +import { root } from '../miscs' import { makeDeleteRequest, makeGetRequest, @@ -146,6 +148,25 @@ abstract class AbstractCommand { }) } + protected updateImageRequest (options: InternalCommonCommandOptions & { + fixture: string + fieldname: string + }) { + let filePath = '' + if (isAbsolute(options.fixture)) { + filePath = options.fixture + } else { + filePath = join(root(), 'server', 'tests', 'fixtures', options.fixture) + } + + return this.postUploadRequest({ + ...options, + + fields: {}, + attaches: { [options.fieldname]: filePath } + }) + } + private buildCommonRequestOptions (options: InternalCommonCommandOptions) { const { path } = options diff --git a/shared/extra-utils/videos/channels-command.ts b/shared/extra-utils/videos/channels-command.ts new file mode 100644 index 000000000..a98c5cc93 --- /dev/null +++ b/shared/extra-utils/videos/channels-command.ts @@ -0,0 +1,157 @@ +import { pick } from 'lodash' +import { ResultList, VideoChannel, VideoChannelCreateResult } from '@shared/models' +import { HttpStatusCode } from '../../core-utils/miscs/http-error-codes' +import { VideoChannelCreate } from '../../models/videos/channel/video-channel-create.model' +import { VideoChannelUpdate } from '../../models/videos/channel/video-channel-update.model' +import { unwrapBody } from '../requests' +import { AbstractCommand, OverrideCommandOptions } from '../shared' + +export class ChannelsCommand extends AbstractCommand { + + list (options: OverrideCommandOptions & { + start?: number + count?: number + sort?: string + withStats?: boolean + } = {}) { + const path = '/api/v1/video-channels' + + return this.getRequestBody>({ + ...options, + + path, + query: pick(options, [ 'start', 'count', 'sort', 'withStats' ]), + implicitToken: false, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } + + listByAccount (options: OverrideCommandOptions & { + accountName: string + start?: number + count?: number + sort?: string + withStats?: boolean + search?: string + }) { + const { accountName, sort = 'createdAt' } = options + const path = '/api/v1/accounts/' + accountName + '/video-channels' + + return this.getRequestBody>({ + ...options, + + path, + query: { sort, ...pick(options, [ 'start', 'count', 'withStats', 'search' ]) }, + implicitToken: false, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } + + async create (options: OverrideCommandOptions & { + attributes: VideoChannelCreate + }) { + const path = '/api/v1/video-channels/' + + // Default attributes + const defaultAttributes = { + displayName: 'my super video channel', + description: 'my super channel description', + support: 'my super channel support' + } + const attributes = { ...defaultAttributes, ...options.attributes } + + const body = await unwrapBody<{ videoChannel: VideoChannelCreateResult }>(this.postBodyRequest({ + ...options, + + path, + fields: attributes, + implicitToken: true, + defaultExpectedStatus: HttpStatusCode.OK_200 + })) + + return body.videoChannel + } + + update (options: OverrideCommandOptions & { + channelName: string + attributes: VideoChannelUpdate + }) { + const { channelName, attributes } = options + const path = '/api/v1/video-channels/' + channelName + + return this.putBodyRequest({ + ...options, + + path, + fields: attributes, + implicitToken: true, + defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 + }) + } + + delete (options: OverrideCommandOptions & { + channelName: string + }) { + const path = '/api/v1/video-channels/' + options.channelName + + return this.deleteRequest({ + ...options, + + path, + implicitToken: true, + defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 + }) + } + + get (options: OverrideCommandOptions & { + channelName: string + }) { + const path = '/api/v1/video-channels/' + options.channelName + + return this.getRequestBody({ + ...options, + + path, + implicitToken: false, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } + + updateImage (options: OverrideCommandOptions & { + fixture: string + channelName: string | number + type: 'avatar' | 'banner' + }) { + const { channelName, fixture, type } = options + + const path = `/api/v1/video-channels/${channelName}/${type}/pick` + + return this.updateImageRequest({ + ...options, + + path, + fixture, + fieldname: type + 'file', + + implicitToken: true, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } + + deleteImage (options: OverrideCommandOptions & { + channelName: string | number + type: 'avatar' | 'banner' + }) { + const { channelName, type } = options + + const path = `/api/v1/video-channels/${channelName}/${type}` + + return this.deleteRequest({ + ...options, + + path, + implicitToken: true, + defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 + }) + } +} diff --git a/shared/extra-utils/videos/channels.ts b/shared/extra-utils/videos/channels.ts new file mode 100644 index 000000000..a77543c92 --- /dev/null +++ b/shared/extra-utils/videos/channels.ts @@ -0,0 +1,20 @@ +import { User } from '../../models/users/user.model' +import { ServerInfo } from '../server/servers' +import { getMyUserInformation } from '../users/users' + +function setDefaultVideoChannel (servers: ServerInfo[]) { + const tasks: Promise[] = [] + + for (const server of servers) { + const p = getMyUserInformation(server.url, server.accessToken) + .then(res => { server.videoChannel = (res.body as User).videoChannels[0] }) + + tasks.push(p) + } + + return Promise.all(tasks) +} + +export { + setDefaultVideoChannel +} diff --git a/shared/extra-utils/videos/index.ts b/shared/extra-utils/videos/index.ts index f87ae8eea..3bc219281 100644 --- a/shared/extra-utils/videos/index.ts +++ b/shared/extra-utils/videos/index.ts @@ -1,7 +1,9 @@ export * from './blacklist-command' -export * from './captions' export * from './captions-command' +export * from './captions' export * from './change-ownership-command' +export * from './channels' +export * from './channels-command' export * from './history-command' export * from './imports-command' export * from './live-command' @@ -11,6 +13,5 @@ export * from './playlists' export * from './services-command' export * from './streaming-playlists-command' export * from './streaming-playlists' -export * from './video-channels' export * from './video-comments' export * from './videos' diff --git a/shared/extra-utils/videos/video-channels.ts b/shared/extra-utils/videos/video-channels.ts deleted file mode 100644 index 0aab93e52..000000000 --- a/shared/extra-utils/videos/video-channels.ts +++ /dev/null @@ -1,192 +0,0 @@ -/* eslint-disable @typescript-eslint/no-floating-promises */ - -import * as request from 'supertest' -import { VideoChannelUpdate } from '../../models/videos/channel/video-channel-update.model' -import { VideoChannelCreate } from '../../models/videos/channel/video-channel-create.model' -import { makeDeleteRequest, makeGetRequest, updateImageRequest } from '../requests/requests' -import { ServerInfo } from '../server/servers' -import { MyUser, User } from '../../models/users/user.model' -import { getMyUserInformation } from '../users/users' -import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' - -function getVideoChannelsList (url: string, start: number, count: number, sort?: string, withStats?: boolean) { - const path = '/api/v1/video-channels' - - const req = request(url) - .get(path) - .query({ start: start }) - .query({ count: count }) - - if (sort) req.query({ sort }) - if (withStats) req.query({ withStats }) - - return req.set('Accept', 'application/json') - .expect(HttpStatusCode.OK_200) - .expect('Content-Type', /json/) -} - -function getAccountVideoChannelsList (parameters: { - url: string - accountName: string - start?: number - count?: number - sort?: string - specialStatus?: HttpStatusCode - withStats?: boolean - search?: string -}) { - const { - url, - accountName, - start, - count, - sort = 'createdAt', - specialStatus = HttpStatusCode.OK_200, - withStats = false, - search - } = parameters - - const path = '/api/v1/accounts/' + accountName + '/video-channels' - - return makeGetRequest({ - url, - path, - query: { - start, - count, - sort, - withStats, - search - }, - statusCodeExpected: specialStatus - }) -} - -function addVideoChannel ( - url: string, - token: string, - videoChannelAttributesArg: VideoChannelCreate, - expectedStatus = HttpStatusCode.OK_200 -) { - const path = '/api/v1/video-channels/' - - // Default attributes - let attributes = { - displayName: 'my super video channel', - description: 'my super channel description', - support: 'my super channel support' - } - attributes = Object.assign(attributes, videoChannelAttributesArg) - - return request(url) - .post(path) - .send(attributes) - .set('Accept', 'application/json') - .set('Authorization', 'Bearer ' + token) - .expect(expectedStatus) -} - -function updateVideoChannel ( - url: string, - token: string, - channelName: string, - attributes: VideoChannelUpdate, - expectedStatus = HttpStatusCode.NO_CONTENT_204 -) { - const body: any = {} - const path = '/api/v1/video-channels/' + channelName - - if (attributes.displayName) body.displayName = attributes.displayName - if (attributes.description) body.description = attributes.description - if (attributes.support) body.support = attributes.support - if (attributes.bulkVideosSupportUpdate) body.bulkVideosSupportUpdate = attributes.bulkVideosSupportUpdate - - return request(url) - .put(path) - .send(body) - .set('Accept', 'application/json') - .set('Authorization', 'Bearer ' + token) - .expect(expectedStatus) -} - -function deleteVideoChannel (url: string, token: string, channelName: string, expectedStatus = HttpStatusCode.NO_CONTENT_204) { - const path = '/api/v1/video-channels/' + channelName - - return request(url) - .delete(path) - .set('Accept', 'application/json') - .set('Authorization', 'Bearer ' + token) - .expect(expectedStatus) -} - -function getVideoChannel (url: string, channelName: string) { - const path = '/api/v1/video-channels/' + channelName - - return request(url) - .get(path) - .set('Accept', 'application/json') - .expect(HttpStatusCode.OK_200) - .expect('Content-Type', /json/) -} - -function updateVideoChannelImage (options: { - url: string - accessToken: string - fixture: string - videoChannelName: string | number - type: 'avatar' | 'banner' -}) { - const path = `/api/v1/video-channels/${options.videoChannelName}/${options.type}/pick` - - return updateImageRequest({ ...options, path, fieldname: options.type + 'file' }) -} - -function deleteVideoChannelImage (options: { - url: string - accessToken: string - videoChannelName: string | number - type: 'avatar' | 'banner' -}) { - const path = `/api/v1/video-channels/${options.videoChannelName}/${options.type}` - - return makeDeleteRequest({ - url: options.url, - token: options.accessToken, - path, - statusCodeExpected: 204 - }) -} - -function setDefaultVideoChannel (servers: ServerInfo[]) { - const tasks: Promise[] = [] - - for (const server of servers) { - const p = getMyUserInformation(server.url, server.accessToken) - .then(res => { server.videoChannel = (res.body as User).videoChannels[0] }) - - tasks.push(p) - } - - return Promise.all(tasks) -} - -async function getDefaultVideoChannel (url: string, token: string) { - const res = await getMyUserInformation(url, token) - - return (res.body as MyUser).videoChannels[0].id -} - -// --------------------------------------------------------------------------- - -export { - updateVideoChannelImage, - getVideoChannelsList, - getAccountVideoChannelsList, - addVideoChannel, - updateVideoChannel, - deleteVideoChannel, - getVideoChannel, - setDefaultVideoChannel, - deleteVideoChannelImage, - getDefaultVideoChannel -} diff --git a/shared/models/videos/channel/index.ts b/shared/models/videos/channel/index.ts index 9dbaa42da..6cdabffbd 100644 --- a/shared/models/videos/channel/index.ts +++ b/shared/models/videos/channel/index.ts @@ -1,3 +1,4 @@ +export * from './video-channel-create-result.model' export * from './video-channel-create.model' export * from './video-channel-update.model' export * from './video-channel.model' diff --git a/shared/models/videos/channel/video-channel-create-result.model.ts b/shared/models/videos/channel/video-channel-create-result.model.ts new file mode 100644 index 000000000..e3d7aeb4c --- /dev/null +++ b/shared/models/videos/channel/video-channel-create-result.model.ts @@ -0,0 +1,3 @@ +export interface VideoChannelCreateResult { + id: number +} -- cgit v1.2.3 From 12edc1495a36b2199f1bf1ba37f50c7b694be382 Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Fri, 9 Jul 2021 14:15:11 +0200 Subject: Introduce comments command --- scripts/benchmark.ts | 30 ++-- server/controllers/api/videos/comment.ts | 6 +- server/lib/moderation.ts | 2 +- server/tests/api/activitypub/cleaner.ts | 25 +-- server/tests/api/check-params/video-comments.ts | 27 ++- server/tests/api/moderation/abuses.ts | 29 ++- .../tests/api/moderation/blocklist-notification.ts | 7 +- server/tests/api/moderation/blocklist.ts | 196 ++++++++++----------- .../api/notifications/comments-notifications.ts | 123 ++++++------- .../api/notifications/moderation-notifications.ts | 20 ++- server/tests/api/server/bulk.ts | 63 ++++--- server/tests/api/server/follows.ts | 53 +++--- server/tests/api/server/handle-down.ts | 69 ++++---- server/tests/api/server/stats.ts | 3 +- server/tests/api/users/users.ts | 3 +- server/tests/api/videos/multiple-servers.ts | 99 +++++------ server/tests/api/videos/video-comments.ts | 193 +++++++++----------- server/tests/cli/update-host.ts | 3 +- server/tests/feeds/feeds.ts | 9 +- server/tests/plugins/action-hooks.ts | 11 +- server/tests/plugins/filter-hooks.ts | 50 +++--- shared/extra-utils/server/servers.ts | 3 + shared/extra-utils/videos/comments-command.ts | 132 ++++++++++++++ shared/extra-utils/videos/index.ts | 3 +- .../videos/streaming-playlists-command.ts | 2 +- shared/extra-utils/videos/video-comments.ts | 138 --------------- shared/models/videos/comment/index.ts | 1 + .../videos/comment/video-comment-create.model.ts | 3 + .../models/videos/comment/video-comment.model.ts | 7 +- 29 files changed, 613 insertions(+), 697 deletions(-) create mode 100644 shared/extra-utils/videos/comments-command.ts delete mode 100644 shared/extra-utils/videos/video-comments.ts create mode 100644 shared/models/videos/comment/video-comment-create.model.ts diff --git a/scripts/benchmark.ts b/scripts/benchmark.ts index fcfc67bf7..321b07c94 100644 --- a/scripts/benchmark.ts +++ b/scripts/benchmark.ts @@ -1,19 +1,10 @@ -import { registerTSPaths } from '../server/helpers/register-ts-paths' -registerTSPaths() - import * as autocannon from 'autocannon' -import { - addVideoCommentReply, - addVideoCommentThread, - flushAndRunServer, - getVideosList, - killallServers, - ServerInfo, - setAccessTokensToServers, - uploadVideo -} from '@shared/extra-utils' -import { Video, VideoPrivacy } from '@shared/models' import { writeJson } from 'fs-extra' +import { flushAndRunServer, getVideosList, killallServers, ServerInfo, setAccessTokensToServers, uploadVideo } from '@shared/extra-utils' +import { Video, VideoPrivacy } from '@shared/models' +import { registerTSPaths } from '../server/helpers/register-ts-paths' + +registerTSPaths() let server: ServerInfo let video: Video @@ -228,18 +219,17 @@ async function prepare () { for (let i = 0; i < 10; i++) { const text = 'my super first comment' - const res = await addVideoCommentThread(server.url, server.accessToken, video.id, text) - threadId = res.body.comment.id + const created = await server.commentsCommand.createThread({ videoId: video.id, text }) + threadId = created.id const text1 = 'my super answer to thread 1' - const childCommentRes = await addVideoCommentReply(server.url, server.accessToken, video.id, threadId, text1) - const childCommentId = childCommentRes.body.comment.id + const child = await server.commentsCommand.addReply({ videoId: video.id, toCommentId: threadId, text: text1 }) const text2 = 'my super answer to answer of thread 1' - await addVideoCommentReply(server.url, server.accessToken, video.id, childCommentId, text2) + await server.commentsCommand.addReply({ videoId: video.id, toCommentId: child.id, text: text2 }) const text3 = 'my second answer to thread 1' - await addVideoCommentReply(server.url, server.accessToken, video.id, threadId, text3) + await server.commentsCommand.addReply({ videoId: video.id, toCommentId: threadId, text: text3 }) } for (const caption of [ 'ar', 'fr', 'en', 'zh' ]) { diff --git a/server/controllers/api/videos/comment.ts b/server/controllers/api/videos/comment.ts index e6f28c1cb..6a25511e5 100644 --- a/server/controllers/api/videos/comment.ts +++ b/server/controllers/api/videos/comment.ts @@ -1,7 +1,7 @@ import * as express from 'express' import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' -import { ResultList, ThreadsResultList, UserRight } from '../../../../shared/models' -import { VideoCommentCreate } from '../../../../shared/models/videos/comment/video-comment.model' +import { ResultList, ThreadsResultList, UserRight, VideoCommentCreate } from '../../../../shared/models' +import { VideoCommentThreads } from '../../../../shared/models/videos/comment/video-comment.model' import { auditLoggerFactory, CommentAuditView, getAuditIdFromRes } from '../../../helpers/audit-logger' import { getFormattedObjects } from '../../../helpers/utils' import { sequelizeTypescript } from '../../../initializers/database' @@ -136,7 +136,7 @@ async function listVideoThreads (req: express.Request, res: express.Response) { return res.json({ ...getFormattedObjects(resultList.data, resultList.total), totalNotDeletedComments: resultList.totalNotDeletedComments - }) + } as VideoCommentThreads) } async function listVideoThreadComments (req: express.Request, res: express.Response) { diff --git a/server/lib/moderation.ts b/server/lib/moderation.ts index 14e00518e..a42ab5b7f 100644 --- a/server/lib/moderation.ts +++ b/server/lib/moderation.ts @@ -23,7 +23,7 @@ import { ActivityCreate } from '../../shared/models/activitypub' import { VideoObject } from '../../shared/models/activitypub/objects' import { VideoCommentObject } from '../../shared/models/activitypub/objects/video-comment-object' import { LiveVideoCreate, VideoCreate, VideoImportCreate } from '../../shared/models/videos' -import { VideoCommentCreate } from '../../shared/models/videos/comment/video-comment.model' +import { VideoCommentCreate } from '../../shared/models/videos/comment' import { ActorModel } from '../models/actor/actor' import { UserModel } from '../models/user/user' import { VideoModel } from '../models/video/video' diff --git a/server/tests/api/activitypub/cleaner.ts b/server/tests/api/activitypub/cleaner.ts index 75ef56ce3..27f17b4d6 100644 --- a/server/tests/api/activitypub/cleaner.ts +++ b/server/tests/api/activitypub/cleaner.ts @@ -7,16 +7,19 @@ import { closeAllSequelize, deleteAll, doubleFollow, + flushAndRunMultipleServers, getCount, + getVideo, + rateVideo, selectQuery, + ServerInfo, + setAccessTokensToServers, setVideoField, updateQuery, - wait -} from '../../../../shared/extra-utils' -import { flushAndRunMultipleServers, ServerInfo, setAccessTokensToServers } from '../../../../shared/extra-utils/index' -import { waitJobs } from '../../../../shared/extra-utils/server/jobs' -import { addVideoCommentThread, getVideoCommentThreads } from '../../../../shared/extra-utils/videos/video-comments' -import { getVideo, rateVideo, uploadVideoAndGetId } from '../../../../shared/extra-utils/videos/videos' + uploadVideoAndGetId, + wait, + waitJobs +} from '@shared/extra-utils' const expect = chai.expect @@ -63,7 +66,7 @@ describe('Test AP cleaner', function () { for (const server of servers) { for (const uuid of videoUUIDs) { await rateVideo(server.url, server.accessToken, uuid, 'like') - await addVideoCommentThread(server.url, server.accessToken, uuid, 'comment') + await server.commentsCommand.createThread({ videoId: uuid, text: 'comment' }) } } @@ -172,8 +175,8 @@ describe('Test AP cleaner', function () { this.timeout(20000) { - const res = await getVideoCommentThreads(servers[0].url, videoUUID1, 0, 5) - expect(res.body.total).to.equal(3) + const { total } = await servers[0].commentsCommand.listThreads({ videoId: videoUUID1 }) + expect(total).to.equal(3) } await deleteAll(servers[2].internalServerNumber, 'videoComment') @@ -182,8 +185,8 @@ describe('Test AP cleaner', function () { await waitJobs(servers) { - const res = await getVideoCommentThreads(servers[0].url, videoUUID1, 0, 5) - expect(res.body.total).to.equal(2) + const { total } = await servers[0].commentsCommand.listThreads({ videoId: videoUUID1 }) + expect(total).to.equal(2) } }) diff --git a/server/tests/api/check-params/video-comments.ts b/server/tests/api/check-params/video-comments.ts index a38420851..ff94645cb 100644 --- a/server/tests/api/check-params/video-comments.ts +++ b/server/tests/api/check-params/video-comments.ts @@ -2,9 +2,11 @@ import 'mocha' import * as chai from 'chai' -import { VideoCreateResult } from '@shared/models' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '@shared/core-utils' import { + checkBadCountPagination, + checkBadSortPagination, + checkBadStartPagination, cleanupTests, createUser, flushAndRunServer, @@ -15,13 +17,8 @@ import { setAccessTokensToServers, uploadVideo, userLogin -} from '../../../../shared/extra-utils' -import { - checkBadCountPagination, - checkBadSortPagination, - checkBadStartPagination -} from '../../../../shared/extra-utils/requests/check-api-params' -import { addVideoCommentThread } from '../../../../shared/extra-utils/videos/video-comments' +} from '@shared/extra-utils' +import { VideoCreateResult } from '@shared/models' const expect = chai.expect @@ -50,8 +47,8 @@ describe('Test video comments API validator', function () { } { - const res = await addVideoCommentThread(server.url, server.accessToken, video.uuid, 'coucou') - commentId = res.body.comment.id + const created = await server.commentsCommand.createThread({ videoId: video.uuid, text: 'coucou' }) + commentId = created.id pathComment = '/api/v1/videos/' + video.uuid + '/comments/' + commentId } @@ -281,8 +278,8 @@ describe('Test video comments API validator', function () { let commentToDelete: number { - const res = await addVideoCommentThread(server.url, userAccessToken, video.uuid, 'hello') - commentToDelete = res.body.comment.id + const created = await server.commentsCommand.createThread({ videoId: video.uuid, text: 'hello' }) + commentToDelete = created.id } const path = '/api/v1/videos/' + video.uuid + '/comments/' + commentToDelete @@ -301,8 +298,8 @@ describe('Test video comments API validator', function () { } { - const res = await addVideoCommentThread(server.url, server.accessToken, anotherVideoUUID, 'hello') - commentToDelete = res.body.comment.id + const created = await server.commentsCommand.createThread({ videoId: anotherVideoUUID, text: 'hello' }) + commentToDelete = created.id } const path = '/api/v1/videos/' + anotherVideoUUID + '/comments/' + commentToDelete diff --git a/server/tests/api/moderation/abuses.ts b/server/tests/api/moderation/abuses.ts index a2bd07b12..e428cf1a8 100644 --- a/server/tests/api/moderation/abuses.ts +++ b/server/tests/api/moderation/abuses.ts @@ -4,14 +4,11 @@ import 'mocha' import * as chai from 'chai' import { AbusesCommand, - addVideoCommentThread, cleanupTests, createUser, - deleteVideoComment, doubleFollow, flushAndRunMultipleServers, generateUserAccessToken, - getVideoCommentThreads, getVideoIdFromUUID, getVideosList, removeUser, @@ -23,7 +20,7 @@ import { userLogin, waitJobs } from '@shared/extra-utils' -import { AbuseMessage, AbusePredefinedReasonsString, AbuseState, AdminAbuse, UserAbuse, VideoComment } from '@shared/models' +import { AbuseMessage, AbusePredefinedReasonsString, AbuseState, AdminAbuse, UserAbuse } from '@shared/models' const expect = chai.expect @@ -399,14 +396,14 @@ describe('Test abuses', function () { describe('Comment abuses', function () { - async function getComment (url: string, videoIdArg: number | string) { + async function getComment (server: ServerInfo, videoIdArg: number | string) { const videoId = typeof videoIdArg === 'string' - ? await getVideoIdFromUUID(url, videoIdArg) + ? await getVideoIdFromUUID(server.url, videoIdArg) : videoIdArg - const res = await getVideoCommentThreads(url, videoId, 0, 5) + const { data } = await server.commentsCommand.listThreads({ videoId }) - return res.body.data[0] as VideoComment + return data[0] } before(async function () { @@ -415,8 +412,8 @@ describe('Test abuses', function () { servers[0].video = await uploadVideoAndGetId({ server: servers[0], videoName: 'server 1' }) servers[1].video = await uploadVideoAndGetId({ server: servers[1], videoName: 'server 2' }) - await addVideoCommentThread(servers[0].url, servers[0].accessToken, servers[0].video.id, 'comment server 1') - await addVideoCommentThread(servers[1].url, servers[1].accessToken, servers[1].video.id, 'comment server 2') + await servers[0].commentsCommand.createThread({ videoId: servers[0].video.id, text: 'comment server 1' }) + await servers[1].commentsCommand.createThread({ videoId: servers[1].video.id, text: 'comment server 2' }) await waitJobs(servers) }) @@ -424,7 +421,7 @@ describe('Test abuses', function () { it('Should report abuse on a comment', async function () { this.timeout(15000) - const comment = await getComment(servers[0].url, servers[0].video.id) + const comment = await getComment(servers[0], servers[0].video.id) const reason = 'it is a bad comment' await commands[0].report({ commentId: comment.id, reason }) @@ -434,7 +431,7 @@ describe('Test abuses', function () { it('Should have 1 comment abuse on server 1 and 0 on server 2', async function () { { - const comment = await getComment(servers[0].url, servers[0].video.id) + const comment = await getComment(servers[0], servers[0].video.id) const body = await commands[0].getAdminList({ filter: 'comment' }) expect(body.total).to.equal(1) @@ -469,7 +466,7 @@ describe('Test abuses', function () { it('Should report abuse on a remote comment', async function () { this.timeout(10000) - const comment = await getComment(servers[0].url, servers[1].video.uuid) + const comment = await getComment(servers[0], servers[1].video.uuid) const reason = 'it is a really bad comment' await commands[0].report({ commentId: comment.id, reason }) @@ -478,7 +475,7 @@ describe('Test abuses', function () { }) it('Should have 2 comment abuses on server 1 and 1 on server 2', async function () { - const commentServer2 = await getComment(servers[0].url, servers[1].video.id) + const commentServer2 = await getComment(servers[0], servers[1].video.id) { const body = await commands[0].getAdminList({ filter: 'comment' }) @@ -537,9 +534,9 @@ describe('Test abuses', function () { it('Should keep the comment abuse when deleting the comment', async function () { this.timeout(10000) - const commentServer2 = await getComment(servers[0].url, servers[1].video.id) + const commentServer2 = await getComment(servers[0], servers[1].video.id) - await deleteVideoComment(servers[0].url, servers[0].accessToken, servers[1].video.uuid, commentServer2.id) + await servers[0].commentsCommand.delete({ videoId: servers[1].video.uuid, commentId: commentServer2.id }) await waitJobs(servers) diff --git a/server/tests/api/moderation/blocklist-notification.ts b/server/tests/api/moderation/blocklist-notification.ts index 5b9699816..a077d8739 100644 --- a/server/tests/api/moderation/blocklist-notification.ts +++ b/server/tests/api/moderation/blocklist-notification.ts @@ -3,7 +3,6 @@ import 'mocha' import * as chai from 'chai' import { - addVideoCommentThread, cleanupTests, createUser, doubleFollow, @@ -59,7 +58,11 @@ describe('Test blocklist', function () { } { - await addVideoCommentThread(servers[1].url, remoteUserToken, videoUUID, '@user2@' + servers[0].host + ' hello') + await servers[1].commentsCommand.createThread({ + token: remoteUserToken, + videoId: videoUUID, + text: '@user2@' + servers[0].host + ' hello' + }) } { diff --git a/server/tests/api/moderation/blocklist.ts b/server/tests/api/moderation/blocklist.ts index 1b8860571..00cb6c65c 100644 --- a/server/tests/api/moderation/blocklist.ts +++ b/server/tests/api/moderation/blocklist.ts @@ -3,55 +3,47 @@ import 'mocha' import * as chai from 'chai' import { - addVideoCommentReply, - addVideoCommentThread, BlocklistCommand, cleanupTests, + CommentsCommand, createUser, - deleteVideoComment, doubleFollow, - findCommentId, flushAndRunMultipleServers, getUserNotifications, - getVideoCommentThreads, getVideosList, getVideosListWithToken, - getVideoThreadComments, ServerInfo, setAccessTokensToServers, uploadVideo, userLogin, waitJobs } from '@shared/extra-utils' -import { UserNotification, UserNotificationType, Video, VideoComment, VideoCommentThreadTree } from '@shared/models' +import { UserNotification, UserNotificationType, Video } from '@shared/models' const expect = chai.expect -async function checkAllVideos (url: string, token: string) { +async function checkAllVideos (server: ServerInfo, token: string) { { - const res = await getVideosListWithToken(url, token) + const res = await getVideosListWithToken(server.url, token) expect(res.body.data).to.have.lengthOf(5) } { - const res = await getVideosList(url) + const res = await getVideosList(server.url) expect(res.body.data).to.have.lengthOf(5) } } -async function checkAllComments (url: string, token: string, videoUUID: string) { - const resThreads = await getVideoCommentThreads(url, videoUUID, 0, 25, '-createdAt', token) +async function checkAllComments (server: ServerInfo, token: string, videoUUID: string) { + const { data } = await server.commentsCommand.listThreads({ videoId: videoUUID, start: 0, count: 25, sort: '-createdAt', token }) - const allThreads: VideoComment[] = resThreads.body.data - const threads = allThreads.filter(t => t.isDeleted === false) + const threads = data.filter(t => t.isDeleted === false) expect(threads).to.have.lengthOf(2) for (const thread of threads) { - const res = await getVideoThreadComments(url, videoUUID, thread.id, token) - - const tree: VideoCommentThreadTree = res.body + const tree = await server.commentsCommand.getThread({ videoId: videoUUID, threadId: thread.id, token }) expect(tree.children).to.have.lengthOf(1) } } @@ -61,10 +53,9 @@ async function checkCommentNotification ( comment: { server: ServerInfo, token: string, videoUUID: string, text: string }, check: 'presence' | 'absence' ) { - const resComment = await addVideoCommentThread(comment.server.url, comment.token, comment.videoUUID, comment.text) - const created = resComment.body.comment as VideoComment - const threadId = created.id - const createdAt = created.createdAt + const command = comment.server.commentsCommand + + const { threadId, createdAt } = await command.createThread({ token: comment.token, videoId: comment.videoUUID, text: comment.text }) await waitJobs([ mainServer, comment.server ]) @@ -75,7 +66,7 @@ async function checkCommentNotification ( if (check === 'presence') expect(commentNotifications).to.have.lengthOf(1) else expect(commentNotifications).to.have.lengthOf(0) - await deleteVideoComment(comment.server.url, comment.token, comment.videoUUID, threadId) + await command.delete({ token: comment.token, videoId: comment.videoUUID, commentId: threadId }) await waitJobs([ mainServer, comment.server ]) } @@ -90,6 +81,7 @@ describe('Test blocklist', function () { let userToken2: string let command: BlocklistCommand + let commentsCommand: CommentsCommand[] before(async function () { this.timeout(120000) @@ -97,6 +89,9 @@ describe('Test blocklist', function () { servers = await flushAndRunMultipleServers(3) await setAccessTokensToServers(servers) + command = servers[0].blocklistCommand + commentsCommand = servers.map(s => s.commentsCommand) + { const user = { username: 'user1', password: 'password' } await createUser({ url: servers[0].url, accessToken: servers[0].accessToken, username: user.username, password: user.password }) @@ -139,30 +134,33 @@ describe('Test blocklist', function () { await doubleFollow(servers[0], servers[2]) { - const resComment = await addVideoCommentThread(servers[0].url, servers[0].accessToken, videoUUID1, 'comment root 1') - const resReply = await addVideoCommentReply(servers[0].url, userToken1, videoUUID1, resComment.body.comment.id, 'comment user 1') - await addVideoCommentReply(servers[0].url, servers[0].accessToken, videoUUID1, resReply.body.comment.id, 'comment root 1') + const created = await commentsCommand[0].createThread({ videoId: videoUUID1, text: 'comment root 1' }) + const reply = await commentsCommand[0].addReply({ + token: userToken1, + videoId: videoUUID1, + toCommentId: created.id, + text: 'comment user 1' + }) + await commentsCommand[0].addReply({ videoId: videoUUID1, toCommentId: reply.id, text: 'comment root 1' }) } { - const resComment = await addVideoCommentThread(servers[0].url, userToken1, videoUUID1, 'comment user 1') - await addVideoCommentReply(servers[0].url, servers[0].accessToken, videoUUID1, resComment.body.comment.id, 'comment root 1') + const created = await commentsCommand[0].createThread({ token: userToken1, videoId: videoUUID1, text: 'comment user 1' }) + await commentsCommand[0].addReply({ videoId: videoUUID1, toCommentId: created.id, text: 'comment root 1' }) } await waitJobs(servers) - - command = servers[0].blocklistCommand }) describe('User blocklist', function () { describe('When managing account blocklist', function () { it('Should list all videos', function () { - return checkAllVideos(servers[0].url, servers[0].accessToken) + return checkAllVideos(servers[0], servers[0].accessToken) }) it('Should list the comments', function () { - return checkAllComments(servers[0].url, servers[0].accessToken, videoUUID1) + return checkAllComments(servers[0], servers[0].accessToken, videoUUID1) }) it('Should block a remote account', async function () { @@ -194,19 +192,26 @@ describe('Test blocklist', function () { }) it('Should hide its comments', async function () { - const resThreads = await getVideoCommentThreads(servers[0].url, videoUUID1, 0, 25, '-createdAt', servers[0].accessToken) - - const threads: VideoComment[] = resThreads.body.data - expect(threads).to.have.lengthOf(1) - expect(threads[0].totalReplies).to.equal(1) - - const t = threads.find(t => t.text === 'comment user 1') + const { data } = await commentsCommand[0].listThreads({ + token: servers[0].accessToken, + videoId: videoUUID1, + start: 0, + count: 25, + sort: '-createdAt' + }) + + expect(data).to.have.lengthOf(1) + expect(data[0].totalReplies).to.equal(1) + + const t = data.find(t => t.text === 'comment user 1') expect(t).to.be.undefined - for (const thread of threads) { - const res = await getVideoThreadComments(servers[0].url, videoUUID1, thread.id, servers[0].accessToken) - - const tree: VideoCommentThreadTree = res.body + for (const thread of data) { + const tree = await commentsCommand[0].getThread({ + videoId: videoUUID1, + threadId: thread.id, + token: servers[0].accessToken + }) expect(tree.children).to.have.lengthOf(0) } }) @@ -231,7 +236,7 @@ describe('Test blocklist', function () { }) it('Should list all the videos with another user', async function () { - return checkAllVideos(servers[0].url, userToken1) + return checkAllVideos(servers[0], userToken1) }) it('Should list blocked accounts', async function () { @@ -264,32 +269,29 @@ describe('Test blocklist', function () { this.timeout(60000) { - await addVideoCommentThread(servers[1].url, userToken2, videoUUID3, 'comment user 2') + await commentsCommand[1].createThread({ token: userToken2, videoId: videoUUID3, text: 'comment user 2' }) await waitJobs(servers) - await addVideoCommentThread(servers[0].url, servers[0].accessToken, videoUUID3, 'uploader') + await commentsCommand[0].createThread({ token: servers[0].accessToken, videoId: videoUUID3, text: 'uploader' }) await waitJobs(servers) - const commentId = await findCommentId(servers[1].url, videoUUID3, 'uploader') + const commentId = await commentsCommand[1].findCommentId({ videoId: videoUUID3, text: 'uploader' }) const message = 'reply by user 2' - const resReply = await addVideoCommentReply(servers[1].url, userToken2, videoUUID3, commentId, message) - await addVideoCommentReply(servers[1].url, servers[1].accessToken, videoUUID3, resReply.body.comment.id, 'another reply') + const reply = await commentsCommand[1].addReply({ token: userToken2, videoId: videoUUID3, toCommentId: commentId, text: message }) + await commentsCommand[1].addReply({ videoId: videoUUID3, toCommentId: reply.id, text: 'another reply' }) await waitJobs(servers) } // Server 2 has all the comments { - const resThreads = await getVideoCommentThreads(servers[1].url, videoUUID3, 0, 25, '-createdAt') - const threads: VideoComment[] = resThreads.body.data - - expect(threads).to.have.lengthOf(2) - expect(threads[0].text).to.equal('uploader') - expect(threads[1].text).to.equal('comment user 2') + const { data } = await commentsCommand[1].listThreads({ videoId: videoUUID3, count: 25, sort: '-createdAt' }) - const resReplies = await getVideoThreadComments(servers[1].url, videoUUID3, threads[0].id) + expect(data).to.have.lengthOf(2) + expect(data[0].text).to.equal('uploader') + expect(data[1].text).to.equal('comment user 2') - const tree: VideoCommentThreadTree = resReplies.body + const tree = await commentsCommand[1].getThread({ videoId: videoUUID3, threadId: data[0].id }) expect(tree.children).to.have.lengthOf(1) expect(tree.children[0].comment.text).to.equal('reply by user 2') expect(tree.children[0].children).to.have.lengthOf(1) @@ -298,20 +300,15 @@ describe('Test blocklist', function () { // Server 1 and 3 should only have uploader comments for (const server of [ servers[0], servers[2] ]) { - const resThreads = await getVideoCommentThreads(server.url, videoUUID3, 0, 25, '-createdAt') - const threads: VideoComment[] = resThreads.body.data + const { data } = await server.commentsCommand.listThreads({ videoId: videoUUID3, count: 25, sort: '-createdAt' }) - expect(threads).to.have.lengthOf(1) - expect(threads[0].text).to.equal('uploader') + expect(data).to.have.lengthOf(1) + expect(data[0].text).to.equal('uploader') - const resReplies = await getVideoThreadComments(server.url, videoUUID3, threads[0].id) + const tree = await server.commentsCommand.getThread({ videoId: videoUUID3, threadId: data[0].id }) - const tree: VideoCommentThreadTree = resReplies.body - if (server.serverNumber === 1) { - expect(tree.children).to.have.lengthOf(0) - } else { - expect(tree.children).to.have.lengthOf(1) - } + if (server.serverNumber === 1) expect(tree.children).to.have.lengthOf(0) + else expect(tree.children).to.have.lengthOf(1) } }) @@ -331,22 +328,19 @@ describe('Test blocklist', function () { it('Should display its comments on my video', async function () { for (const server of servers) { - const resThreads = await getVideoCommentThreads(server.url, videoUUID3, 0, 25, '-createdAt') - const threads: VideoComment[] = resThreads.body.data + const { data } = await server.commentsCommand.listThreads({ videoId: videoUUID3, count: 25, sort: '-createdAt' }) // Server 3 should not have 2 comment threads, because server 1 did not forward the server 2 comment if (server.serverNumber === 3) { - expect(threads).to.have.lengthOf(1) + expect(data).to.have.lengthOf(1) continue } - expect(threads).to.have.lengthOf(2) - expect(threads[0].text).to.equal('uploader') - expect(threads[1].text).to.equal('comment user 2') - - const resReplies = await getVideoThreadComments(server.url, videoUUID3, threads[0].id) + expect(data).to.have.lengthOf(2) + expect(data[0].text).to.equal('uploader') + expect(data[1].text).to.equal('comment user 2') - const tree: VideoCommentThreadTree = resReplies.body + const tree = await server.commentsCommand.getThread({ videoId: videoUUID3, threadId: data[0].id }) expect(tree.children).to.have.lengthOf(1) expect(tree.children[0].comment.text).to.equal('reply by user 2') expect(tree.children[0].children).to.have.lengthOf(1) @@ -359,7 +353,7 @@ describe('Test blocklist', function () { }) it('Should display its comments', function () { - return checkAllComments(servers[0].url, servers[0].accessToken, videoUUID1) + return checkAllComments(servers[0], servers[0].accessToken, videoUUID1) }) it('Should have a notification from a non blocked account', async function () { @@ -385,11 +379,11 @@ describe('Test blocklist', function () { describe('When managing server blocklist', function () { it('Should list all videos', function () { - return checkAllVideos(servers[0].url, servers[0].accessToken) + return checkAllVideos(servers[0], servers[0].accessToken) }) it('Should list the comments', function () { - return checkAllComments(servers[0].url, servers[0].accessToken, videoUUID1) + return checkAllComments(servers[0], servers[0].accessToken, videoUUID1) }) it('Should block a remote server', async function () { @@ -410,20 +404,19 @@ describe('Test blocklist', function () { }) it('Should list all the videos with another user', async function () { - return checkAllVideos(servers[0].url, userToken1) + return checkAllVideos(servers[0], userToken1) }) it('Should hide its comments', async function () { this.timeout(10000) - const resThreads = await addVideoCommentThread(servers[1].url, userToken2, videoUUID1, 'hidden comment 2') - const threadId = resThreads.body.comment.id + const { id } = await commentsCommand[1].createThread({ token: userToken2, videoId: videoUUID1, text: 'hidden comment 2' }) await waitJobs(servers) - await checkAllComments(servers[0].url, servers[0].accessToken, videoUUID1) + await checkAllComments(servers[0], servers[0].accessToken, videoUUID1) - await deleteVideoComment(servers[1].url, userToken2, videoUUID1, threadId) + await commentsCommand[1].delete({ token: userToken2, videoId: videoUUID1, commentId: id }) }) it('Should not have notifications from blocked server', async function () { @@ -460,11 +453,11 @@ describe('Test blocklist', function () { }) it('Should display its videos', function () { - return checkAllVideos(servers[0].url, servers[0].accessToken) + return checkAllVideos(servers[0], servers[0].accessToken) }) it('Should display its comments', function () { - return checkAllComments(servers[0].url, servers[0].accessToken, videoUUID1) + return checkAllComments(servers[0], servers[0].accessToken, videoUUID1) }) it('Should have notification from unblocked server', async function () { @@ -493,13 +486,13 @@ describe('Test blocklist', function () { describe('When managing account blocklist', function () { it('Should list all videos', async function () { for (const token of [ userModeratorToken, servers[0].accessToken ]) { - await checkAllVideos(servers[0].url, token) + await checkAllVideos(servers[0], token) } }) it('Should list the comments', async function () { for (const token of [ userModeratorToken, servers[0].accessToken ]) { - await checkAllComments(servers[0].url, token, videoUUID1) + await checkAllComments(servers[0], token, videoUUID1) } }) @@ -537,10 +530,8 @@ describe('Test blocklist', function () { it('Should hide its comments', async function () { for (const token of [ userModeratorToken, servers[0].accessToken ]) { - const resThreads = await getVideoCommentThreads(servers[0].url, videoUUID1, 0, 20, '-createdAt', token) - - let threads: VideoComment[] = resThreads.body.data - threads = threads.filter(t => t.isDeleted === false) + const { data } = await commentsCommand[0].listThreads({ videoId: videoUUID1, count: 20, sort: '-createdAt', token }) + const threads = data.filter(t => t.isDeleted === false) expect(threads).to.have.lengthOf(1) expect(threads[0].totalReplies).to.equal(1) @@ -549,9 +540,7 @@ describe('Test blocklist', function () { expect(t).to.be.undefined for (const thread of threads) { - const res = await getVideoThreadComments(servers[0].url, videoUUID1, thread.id, token) - - const tree: VideoCommentThreadTree = res.body + const tree = await commentsCommand[0].getThread({ videoId: videoUUID1, threadId: thread.id, token }) expect(tree.children).to.have.lengthOf(0) } } @@ -624,7 +613,7 @@ describe('Test blocklist', function () { it('Should display its comments', async function () { for (const token of [ userModeratorToken, servers[0].accessToken ]) { - await checkAllComments(servers[0].url, token, videoUUID1) + await checkAllComments(servers[0], token, videoUUID1) } }) @@ -651,13 +640,13 @@ describe('Test blocklist', function () { describe('When managing server blocklist', function () { it('Should list all videos', async function () { for (const token of [ userModeratorToken, servers[0].accessToken ]) { - await checkAllVideos(servers[0].url, token) + await checkAllVideos(servers[0], token) } }) it('Should list the comments', async function () { for (const token of [ userModeratorToken, servers[0].accessToken ]) { - await checkAllComments(servers[0].url, token, videoUUID1) + await checkAllComments(servers[0], token, videoUUID1) } }) @@ -686,14 +675,13 @@ describe('Test blocklist', function () { it('Should hide its comments', async function () { this.timeout(10000) - const resThreads = await addVideoCommentThread(servers[1].url, userToken2, videoUUID1, 'hidden comment 2') - const threadId = resThreads.body.comment.id + const { id } = await commentsCommand[1].createThread({ token: userToken2, videoId: videoUUID1, text: 'hidden comment 2' }) await waitJobs(servers) - await checkAllComments(servers[0].url, servers[0].accessToken, videoUUID1) + await checkAllComments(servers[0], servers[0].accessToken, videoUUID1) - await deleteVideoComment(servers[1].url, userToken2, videoUUID1, threadId) + await commentsCommand[1].delete({ token: userToken2, videoId: videoUUID1, commentId: id }) }) it('Should not have notification from blocked instances by instance', async function () { @@ -749,13 +737,13 @@ describe('Test blocklist', function () { it('Should list all videos', async function () { for (const token of [ userModeratorToken, servers[0].accessToken ]) { - await checkAllVideos(servers[0].url, token) + await checkAllVideos(servers[0], token) } }) it('Should list the comments', async function () { for (const token of [ userModeratorToken, servers[0].accessToken ]) { - await checkAllComments(servers[0].url, token, videoUUID1) + await checkAllComments(servers[0], token, videoUUID1) } }) diff --git a/server/tests/api/notifications/comments-notifications.ts b/server/tests/api/notifications/comments-notifications.ts index 13fcee843..ea6055386 100644 --- a/server/tests/api/notifications/comments-notifications.ts +++ b/server/tests/api/notifications/comments-notifications.ts @@ -3,14 +3,10 @@ import 'mocha' import * as chai from 'chai' import { - addVideoCommentReply, - addVideoCommentThread, checkCommentMention, CheckerBaseParams, checkNewCommentOnMyVideo, cleanupTests, - getVideoCommentThreads, - getVideoThreadComments, MockSmtpServer, prepareNotificationsTest, ServerInfo, @@ -18,13 +14,13 @@ import { uploadVideo, waitJobs } from '@shared/extra-utils' -import { UserNotification, VideoCommentThreadTree } from '@shared/models' +import { UserNotification } from '@shared/models' const expect = chai.expect describe('Test comments notifications', function () { let servers: ServerInfo[] = [] - let userAccessToken: string + let userToken: string let userNotifications: UserNotification[] = [] let emails: object[] = [] @@ -38,7 +34,7 @@ describe('Test comments notifications', function () { const res = await prepareNotificationsTest(2) emails = res.emails - userAccessToken = res.userAccessToken + userToken = res.userAccessToken servers = res.servers userNotifications = res.userNotifications }) @@ -51,7 +47,7 @@ describe('Test comments notifications', function () { server: servers[0], emails, socketNotifications: userNotifications, - token: userAccessToken + token: userToken } }) @@ -61,8 +57,8 @@ describe('Test comments notifications', function () { const resVideo = await uploadVideo(servers[0].url, servers[0].accessToken, { name: 'super video' }) const uuid = resVideo.body.video.uuid - const resComment = await addVideoCommentThread(servers[0].url, servers[0].accessToken, uuid, 'comment') - const commentId = resComment.body.comment.id + const created = await servers[0].commentsCommand.createThread({ videoId: uuid, text: 'comment' }) + const commentId = created.id await waitJobs(servers) await checkNewCommentOnMyVideo(baseParams, uuid, commentId, commentId, 'absence') @@ -71,11 +67,11 @@ describe('Test comments notifications', function () { it('Should not send a new comment notification if I comment my own video', async function () { this.timeout(20000) - const resVideo = await uploadVideo(servers[0].url, userAccessToken, { name: 'super video' }) + const resVideo = await uploadVideo(servers[0].url, userToken, { name: 'super video' }) const uuid = resVideo.body.video.uuid - const resComment = await addVideoCommentThread(servers[0].url, userAccessToken, uuid, 'comment') - const commentId = resComment.body.comment.id + const created = await servers[0].commentsCommand.createThread({ token: userToken, videoId: uuid, text: 'comment' }) + const commentId = created.id await waitJobs(servers) await checkNewCommentOnMyVideo(baseParams, uuid, commentId, commentId, 'absence') @@ -84,28 +80,28 @@ describe('Test comments notifications', function () { it('Should not send a new comment notification if the account is muted', async function () { this.timeout(20000) - await servers[0].blocklistCommand.addToMyBlocklist({ token: userAccessToken, account: 'root' }) + await servers[0].blocklistCommand.addToMyBlocklist({ token: userToken, account: 'root' }) - const resVideo = await uploadVideo(servers[0].url, userAccessToken, { name: 'super video' }) + const resVideo = await uploadVideo(servers[0].url, userToken, { name: 'super video' }) const uuid = resVideo.body.video.uuid - const resComment = await addVideoCommentThread(servers[0].url, servers[0].accessToken, uuid, 'comment') - const commentId = resComment.body.comment.id + const created = await servers[0].commentsCommand.createThread({ videoId: uuid, text: 'comment' }) + const commentId = created.id await waitJobs(servers) await checkNewCommentOnMyVideo(baseParams, uuid, commentId, commentId, 'absence') - await servers[0].blocklistCommand.removeFromMyBlocklist({ token: userAccessToken, account: 'root' }) + await servers[0].blocklistCommand.removeFromMyBlocklist({ token: userToken, account: 'root' }) }) it('Should send a new comment notification after a local comment on my video', async function () { this.timeout(20000) - const resVideo = await uploadVideo(servers[0].url, userAccessToken, { name: 'super video' }) + const resVideo = await uploadVideo(servers[0].url, userToken, { name: 'super video' }) const uuid = resVideo.body.video.uuid - const resComment = await addVideoCommentThread(servers[0].url, servers[0].accessToken, uuid, 'comment') - const commentId = resComment.body.comment.id + const created = await servers[0].commentsCommand.createThread({ videoId: uuid, text: 'comment' }) + const commentId = created.id await waitJobs(servers) await checkNewCommentOnMyVideo(baseParams, uuid, commentId, commentId, 'presence') @@ -114,33 +110,31 @@ describe('Test comments notifications', function () { it('Should send a new comment notification after a remote comment on my video', async function () { this.timeout(20000) - const resVideo = await uploadVideo(servers[0].url, userAccessToken, { name: 'super video' }) + const resVideo = await uploadVideo(servers[0].url, userToken, { name: 'super video' }) const uuid = resVideo.body.video.uuid await waitJobs(servers) - await addVideoCommentThread(servers[1].url, servers[1].accessToken, uuid, 'comment') + await servers[1].commentsCommand.createThread({ videoId: uuid, text: 'comment' }) await waitJobs(servers) - const resComment = await getVideoCommentThreads(servers[0].url, uuid, 0, 5) - expect(resComment.body.data).to.have.lengthOf(1) - const commentId = resComment.body.data[0].id + const { data } = await servers[0].commentsCommand.listThreads({ videoId: uuid }) + expect(data).to.have.lengthOf(1) + const commentId = data[0].id await checkNewCommentOnMyVideo(baseParams, uuid, commentId, commentId, 'presence') }) it('Should send a new comment notification after a local reply on my video', async function () { this.timeout(20000) - const resVideo = await uploadVideo(servers[0].url, userAccessToken, { name: 'super video' }) + const resVideo = await uploadVideo(servers[0].url, userToken, { name: 'super video' }) const uuid = resVideo.body.video.uuid - const resThread = await addVideoCommentThread(servers[0].url, servers[0].accessToken, uuid, 'comment') - const threadId = resThread.body.comment.id + const { id: threadId } = await servers[0].commentsCommand.createThread({ videoId: uuid, text: 'comment' }) - const resComment = await addVideoCommentReply(servers[0].url, servers[0].accessToken, uuid, threadId, 'reply') - const commentId = resComment.body.comment.id + const { id: commentId } = await servers[0].commentsCommand.addReply({ videoId: uuid, toCommentId: threadId, text: 'reply' }) await waitJobs(servers) await checkNewCommentOnMyVideo(baseParams, uuid, commentId, threadId, 'presence') @@ -149,24 +143,23 @@ describe('Test comments notifications', function () { it('Should send a new comment notification after a remote reply on my video', async function () { this.timeout(20000) - const resVideo = await uploadVideo(servers[0].url, userAccessToken, { name: 'super video' }) + const resVideo = await uploadVideo(servers[0].url, userToken, { name: 'super video' }) const uuid = resVideo.body.video.uuid await waitJobs(servers) { - const resThread = await addVideoCommentThread(servers[1].url, servers[1].accessToken, uuid, 'comment') - const threadId = resThread.body.comment.id - await addVideoCommentReply(servers[1].url, servers[1].accessToken, uuid, threadId, 'reply') + const created = await servers[1].commentsCommand.createThread({ videoId: uuid, text: 'comment' }) + const threadId = created.id + await servers[1].commentsCommand.addReply({ videoId: uuid, toCommentId: threadId, text: 'reply' }) } await waitJobs(servers) - const resThread = await getVideoCommentThreads(servers[0].url, uuid, 0, 5) - expect(resThread.body.data).to.have.lengthOf(1) - const threadId = resThread.body.data[0].id + const { data } = await servers[0].commentsCommand.listThreads({ videoId: uuid }) + expect(data).to.have.lengthOf(1) - const resComments = await getVideoThreadComments(servers[0].url, uuid, threadId) - const tree = resComments.body as VideoCommentThreadTree + const threadId = data[0].id + const tree = await servers[0].commentsCommand.getThread({ videoId: uuid, threadId }) expect(tree.children).to.have.lengthOf(1) const commentId = tree.children[0].comment.id @@ -177,10 +170,10 @@ describe('Test comments notifications', function () { it('Should convert markdown in comment to html', async function () { this.timeout(20000) - const resVideo = await uploadVideo(servers[0].url, userAccessToken, { name: 'cool video' }) + const resVideo = await uploadVideo(servers[0].url, userToken, { name: 'cool video' }) const uuid = resVideo.body.video.uuid - await addVideoCommentThread(servers[0].url, servers[0].accessToken, uuid, commentText) + await servers[0].commentsCommand.createThread({ videoId: uuid, text: commentText }) await waitJobs(servers) @@ -197,7 +190,7 @@ describe('Test comments notifications', function () { server: servers[0], emails, socketNotifications: userNotifications, - token: userAccessToken + token: userToken } await updateMyUser({ @@ -216,11 +209,10 @@ describe('Test comments notifications', function () { it('Should not send a new mention comment notification if I mention the video owner', async function () { this.timeout(10000) - const resVideo = await uploadVideo(servers[0].url, userAccessToken, { name: 'super video' }) + const resVideo = await uploadVideo(servers[0].url, userToken, { name: 'super video' }) const uuid = resVideo.body.video.uuid - const resComment = await addVideoCommentThread(servers[0].url, servers[0].accessToken, uuid, '@user_1 hello') - const commentId = resComment.body.comment.id + const { id: commentId } = await servers[0].commentsCommand.createThread({ videoId: uuid, text: '@user_1 hello' }) await waitJobs(servers) await checkCommentMention(baseParams, uuid, commentId, commentId, 'super root name', 'absence') @@ -232,8 +224,7 @@ describe('Test comments notifications', function () { const resVideo = await uploadVideo(servers[0].url, servers[0].accessToken, { name: 'super video' }) const uuid = resVideo.body.video.uuid - const resComment = await addVideoCommentThread(servers[0].url, userAccessToken, uuid, '@user_1 hello') - const commentId = resComment.body.comment.id + const { id: commentId } = await servers[0].commentsCommand.createThread({ token: userToken, videoId: uuid, text: '@user_1 hello' }) await waitJobs(servers) await checkCommentMention(baseParams, uuid, commentId, commentId, 'super root name', 'absence') @@ -242,18 +233,17 @@ describe('Test comments notifications', function () { it('Should not send a new mention notification if the account is muted', async function () { this.timeout(10000) - await servers[0].blocklistCommand.addToMyBlocklist({ token: userAccessToken, account: 'root' }) + await servers[0].blocklistCommand.addToMyBlocklist({ token: userToken, account: 'root' }) const resVideo = await uploadVideo(servers[0].url, servers[0].accessToken, { name: 'super video' }) const uuid = resVideo.body.video.uuid - const resComment = await addVideoCommentThread(servers[0].url, servers[0].accessToken, uuid, '@user_1 hello') - const commentId = resComment.body.comment.id + const { id: commentId } = await servers[0].commentsCommand.createThread({ videoId: uuid, text: '@user_1 hello' }) await waitJobs(servers) await checkCommentMention(baseParams, uuid, commentId, commentId, 'super root name', 'absence') - await servers[0].blocklistCommand.removeFromMyBlocklist({ token: userAccessToken, account: 'root' }) + await servers[0].blocklistCommand.removeFromMyBlocklist({ token: userToken, account: 'root' }) }) it('Should not send a new mention notification if the remote account mention a local account', async function () { @@ -263,8 +253,7 @@ describe('Test comments notifications', function () { const uuid = resVideo.body.video.uuid await waitJobs(servers) - const resThread = await addVideoCommentThread(servers[1].url, servers[1].accessToken, uuid, '@user_1 hello') - const threadId = resThread.body.comment.id + const { id: threadId } = await servers[1].commentsCommand.createThread({ videoId: uuid, text: '@user_1 hello' }) await waitJobs(servers) await checkCommentMention(baseParams, uuid, threadId, threadId, 'super root 2 name', 'absence') @@ -276,14 +265,12 @@ describe('Test comments notifications', function () { const resVideo = await uploadVideo(servers[0].url, servers[0].accessToken, { name: 'super video' }) const uuid = resVideo.body.video.uuid - const resThread = await addVideoCommentThread(servers[0].url, servers[0].accessToken, uuid, '@user_1 hello 1') - const threadId = resThread.body.comment.id + const { id: threadId } = await servers[0].commentsCommand.createThread({ videoId: uuid, text: '@user_1 hellotext: 1' }) await waitJobs(servers) await checkCommentMention(baseParams, uuid, threadId, threadId, 'super root name', 'presence') - const resComment = await addVideoCommentReply(servers[0].url, servers[0].accessToken, uuid, threadId, 'hello 2 @user_1') - const commentId = resComment.body.comment.id + const { id: commentId } = await servers[0].commentsCommand.addReply({ videoId: uuid, toCommentId: threadId, text: 'hello 2 @user_1' }) await waitJobs(servers) await checkCommentMention(baseParams, uuid, commentId, threadId, 'super root name', 'presence') @@ -298,23 +285,22 @@ describe('Test comments notifications', function () { await waitJobs(servers) const text1 = `hello @user_1@localhost:${servers[0].port} 1` - const resThread = await addVideoCommentThread(servers[1].url, servers[1].accessToken, uuid, text1) - const server2ThreadId = resThread.body.comment.id + const { id: server2ThreadId } = await servers[1].commentsCommand.createThread({ videoId: uuid, text: text1 }) await waitJobs(servers) - const resThread2 = await getVideoCommentThreads(servers[0].url, uuid, 0, 5) - expect(resThread2.body.data).to.have.lengthOf(1) - const server1ThreadId = resThread2.body.data[0].id + const { data } = await servers[0].commentsCommand.listThreads({ videoId: uuid }) + expect(data).to.have.lengthOf(1) + + const server1ThreadId = data[0].id await checkCommentMention(baseParams, uuid, server1ThreadId, server1ThreadId, 'super root 2 name', 'presence') const text2 = `@user_1@localhost:${servers[0].port} hello 2 @root@localhost:${servers[0].port}` - await addVideoCommentReply(servers[1].url, servers[1].accessToken, uuid, server2ThreadId, text2) + await servers[1].commentsCommand.addReply({ videoId: uuid, toCommentId: server2ThreadId, text: text2 }) await waitJobs(servers) - const resComments = await getVideoThreadComments(servers[0].url, uuid, server1ThreadId) - const tree = resComments.body as VideoCommentThreadTree + const tree = await servers[0].commentsCommand.getThread({ videoId: uuid, threadId: server1ThreadId }) expect(tree.children).to.have.lengthOf(1) const commentId = tree.children[0].comment.id @@ -328,10 +314,9 @@ describe('Test comments notifications', function () { const resVideo = await uploadVideo(servers[0].url, servers[0].accessToken, { name: 'super video' }) const uuid = resVideo.body.video.uuid - const resThread = await addVideoCommentThread(servers[0].url, servers[0].accessToken, uuid, '@user_1 hello 1') - const threadId = resThread.body.comment.id + const { id: threadId } = await servers[0].commentsCommand.createThread({ videoId: uuid, text: '@user_1 hello 1' }) - await addVideoCommentReply(servers[0].url, servers[0].accessToken, uuid, threadId, '@user_1 ' + commentText) + await servers[0].commentsCommand.addReply({ videoId: uuid, toCommentId: threadId, text: '@user_1 ' + commentText }) await waitJobs(servers) diff --git a/server/tests/api/notifications/moderation-notifications.ts b/server/tests/api/notifications/moderation-notifications.ts index 52ade0548..229f78811 100644 --- a/server/tests/api/notifications/moderation-notifications.ts +++ b/server/tests/api/notifications/moderation-notifications.ts @@ -3,7 +3,6 @@ import 'mocha' import { buildUUID } from '@server/helpers/uuid' import { - addVideoCommentThread, checkAbuseStateChange, checkAutoInstanceFollowing, CheckerBaseParams, @@ -20,7 +19,6 @@ import { cleanupTests, createUser, generateUserAccessToken, - getVideoCommentThreads, getVideoIdFromUUID, immutableAssign, MockInstancesIndex, @@ -101,8 +99,11 @@ describe('Test moderation notifications', function () { const name = 'video for abuse ' + buildUUID() const resVideo = await uploadVideo(servers[0].url, userAccessToken, { name }) const video = resVideo.body.video - const resComment = await addVideoCommentThread(servers[0].url, userAccessToken, video.id, 'comment abuse ' + buildUUID()) - const comment = resComment.body.comment + const comment = await servers[0].commentsCommand.createThread({ + token: userAccessToken, + videoId: video.id, + text: 'comment abuse ' + buildUUID() + }) await waitJobs(servers) @@ -118,12 +119,17 @@ describe('Test moderation notifications', function () { const name = 'video for abuse ' + buildUUID() const resVideo = await uploadVideo(servers[0].url, userAccessToken, { name }) const video = resVideo.body.video - await addVideoCommentThread(servers[0].url, userAccessToken, video.id, 'comment abuse ' + buildUUID()) + + await servers[0].commentsCommand.createThread({ + token: userAccessToken, + videoId: video.id, + text: 'comment abuse ' + buildUUID() + }) await waitJobs(servers) - const resComments = await getVideoCommentThreads(servers[1].url, video.uuid, 0, 5) - const commentId = resComments.body.data[0].id + const { data } = await servers[1].commentsCommand.listThreads({ videoId: video.uuid }) + const commentId = data[0].id await servers[1].abusesCommand.report({ commentId, reason: 'super reason' }) await waitJobs(servers) diff --git a/server/tests/api/server/bulk.ts b/server/tests/api/server/bulk.ts index ca98a2eb2..5c8673e00 100644 --- a/server/tests/api/server/bulk.ts +++ b/server/tests/api/server/bulk.ts @@ -2,16 +2,13 @@ import 'mocha' import * as chai from 'chai' -import { Video, VideoComment } from '@shared/models' +import { Video } from '@shared/models' import { - addVideoCommentReply, - addVideoCommentThread, BulkCommand, cleanupTests, createUser, doubleFollow, flushAndRunMultipleServers, - getVideoCommentThreads, getVideosList, ServerInfo, setAccessTokensToServers, @@ -26,9 +23,9 @@ describe('Test bulk actions', function () { const commentsUser3: { videoId: number, commentId: number }[] = [] let servers: ServerInfo[] = [] - let user1AccessToken: string - let user2AccessToken: string - let user3AccessToken: string + let user1Token: string + let user2Token: string + let user3Token: string let bulkCommand: BulkCommand @@ -44,21 +41,21 @@ describe('Test bulk actions', function () { const user = { username: 'user1', password: 'password' } await createUser({ url: servers[0].url, accessToken: servers[0].accessToken, username: user.username, password: user.password }) - user1AccessToken = await userLogin(servers[0], user) + user1Token = await userLogin(servers[0], user) } { const user = { username: 'user2', password: 'password' } await createUser({ url: servers[0].url, accessToken: servers[0].accessToken, username: user.username, password: user.password }) - user2AccessToken = await userLogin(servers[0], user) + user2Token = await userLogin(servers[0], user) } { const user = { username: 'user3', password: 'password' } await createUser({ url: servers[1].url, accessToken: servers[1].accessToken, username: user.username, password: user.password }) - user3AccessToken = await userLogin(servers[1], user) + user3Token = await userLogin(servers[1], user) } await doubleFollow(servers[0], servers[1]) @@ -74,9 +71,8 @@ describe('Test bulk actions', function () { // Server 1 should not have these comments anymore for (const video of videos) { - const resThreads = await getVideoCommentThreads(servers[0].url, video.id, 0, 10) - const comments = resThreads.body.data as VideoComment[] - const comment = comments.find(c => c.text === 'comment by user 3') + const { data } = await servers[0].commentsCommand.listThreads({ videoId: video.id }) + const comment = data.find(c => c.text === 'comment by user 3') expect(comment).to.not.exist } @@ -88,9 +84,8 @@ describe('Test bulk actions', function () { // Server 1 should not have these comments on videos of server 1 for (const video of videos) { - const resThreads = await getVideoCommentThreads(servers[1].url, video.id, 0, 10) - const comments = resThreads.body.data as VideoComment[] - const comment = comments.find(c => c.text === 'comment by user 3') + const { data } = await servers[1].commentsCommand.listThreads({ videoId: video.id }) + const comment = data.find(c => c.text === 'comment by user 3') if (video.account.host === 'localhost:' + servers[0].port) { expect(comment).to.not.exist @@ -106,7 +101,7 @@ describe('Test bulk actions', function () { await uploadVideo(servers[0].url, servers[0].accessToken, { name: 'video 1 server 1' }) await uploadVideo(servers[0].url, servers[0].accessToken, { name: 'video 2 server 1' }) - await uploadVideo(servers[0].url, user1AccessToken, { name: 'video 3 server 1' }) + await uploadVideo(servers[0].url, user1Token, { name: 'video 3 server 1' }) await uploadVideo(servers[1].url, servers[1].accessToken, { name: 'video 1 server 2' }) @@ -115,19 +110,20 @@ describe('Test bulk actions', function () { { const res = await getVideosList(servers[0].url) for (const video of res.body.data) { - await addVideoCommentThread(servers[0].url, servers[0].accessToken, video.id, 'comment by root server 1') - await addVideoCommentThread(servers[0].url, user1AccessToken, video.id, 'comment by user 1') - await addVideoCommentThread(servers[0].url, user2AccessToken, video.id, 'comment by user 2') + await servers[0].commentsCommand.createThread({ videoId: video.id, text: 'comment by root server 1' }) + await servers[0].commentsCommand.createThread({ token: user1Token, videoId: video.id, text: 'comment by user 1' }) + await servers[0].commentsCommand.createThread({ token: user2Token, videoId: video.id, text: 'comment by user 2' }) } } { const res = await getVideosList(servers[1].url) + for (const video of res.body.data) { - await addVideoCommentThread(servers[1].url, servers[1].accessToken, video.id, 'comment by root server 2') + await servers[1].commentsCommand.createThread({ videoId: video.id, text: 'comment by root server 2' }) - const res = await addVideoCommentThread(servers[1].url, user3AccessToken, video.id, 'comment by user 3') - commentsUser3.push({ videoId: video.id, commentId: res.body.comment.id }) + const comment = await servers[1].commentsCommand.createThread({ token: user3Token, videoId: video.id, text: 'comment by user 3' }) + commentsUser3.push({ videoId: video.id, commentId: comment.id }) } } @@ -138,7 +134,7 @@ describe('Test bulk actions', function () { this.timeout(60000) await bulkCommand.removeCommentsOf({ - token: user1AccessToken, + token: user1Token, attributes: { accountName: 'user2', scope: 'my-videos' @@ -151,15 +147,11 @@ describe('Test bulk actions', function () { const res = await getVideosList(server.url) for (const video of res.body.data) { - const resThreads = await getVideoCommentThreads(server.url, video.id, 0, 10) - const comments = resThreads.body.data as VideoComment[] - const comment = comments.find(c => c.text === 'comment by user 2') + const { data } = await server.commentsCommand.listThreads({ videoId: video.id }) + const comment = data.find(c => c.text === 'comment by user 2') - if (video.name === 'video 3 server 1') { - expect(comment).to.not.exist - } else { - expect(comment).to.exist - } + if (video.name === 'video 3 server 1') expect(comment).to.not.exist + else expect(comment).to.exist } } }) @@ -183,7 +175,12 @@ describe('Test bulk actions', function () { this.timeout(60000) for (const obj of commentsUser3) { - await addVideoCommentReply(servers[1].url, user3AccessToken, obj.videoId, obj.commentId, 'comment by user 3 bis') + await servers[1].commentsCommand.addReply({ + token: user3Token, + videoId: obj.videoId, + toCommentId: obj.commentId, + text: 'comment by user 3 bis' + }) } await waitJobs(servers) diff --git a/server/tests/api/server/follows.ts b/server/tests/api/server/follows.ts index 520442c6e..4a9ed2d05 100644 --- a/server/tests/api/server/follows.ts +++ b/server/tests/api/server/follows.ts @@ -3,19 +3,14 @@ import 'mocha' import * as chai from 'chai' import { - addVideoCommentReply, - addVideoCommentThread, cleanupTests, completeVideoCheck, createUser, dateIsValid, - deleteVideoComment, expectAccountFollows, flushAndRunMultipleServers, FollowsCommand, - getVideoCommentThreads, getVideosList, - getVideoThreadComments, rateVideo, ServerInfo, setAccessTokensToServers, @@ -24,7 +19,7 @@ import { userLogin, waitJobs } from '@shared/extra-utils' -import { Video, VideoComment, VideoCommentThreadTree, VideoPrivacy } from '@shared/models' +import { Video, VideoPrivacy } from '@shared/models' const expect = chai.expect @@ -348,37 +343,35 @@ describe('Test follows', function () { { { const text = 'my super first comment' - const res = await addVideoCommentThread(servers[2].url, servers[2].accessToken, video4.id, text) - const threadId = res.body.comment.id + const created = await servers[2].commentsCommand.createThread({ videoId: video4.id, text }) + const threadId = created.id const text1 = 'my super answer to thread 1' - const childCommentRes = await addVideoCommentReply(servers[2].url, servers[2].accessToken, video4.id, threadId, text1) - const childCommentId = childCommentRes.body.comment.id + const childComment = await servers[2].commentsCommand.addReply({ videoId: video4.id, toCommentId: threadId, text: text1 }) const text2 = 'my super answer to answer of thread 1' - await addVideoCommentReply(servers[2].url, servers[2].accessToken, video4.id, childCommentId, text2) + await servers[2].commentsCommand.addReply({ videoId: video4.id, toCommentId: childComment.id, text: text2 }) const text3 = 'my second answer to thread 1' - await addVideoCommentReply(servers[2].url, servers[2].accessToken, video4.id, threadId, text3) + await servers[2].commentsCommand.addReply({ videoId: video4.id, toCommentId: threadId, text: text3 }) } { const text = 'will be deleted' - const res = await addVideoCommentThread(servers[2].url, servers[2].accessToken, video4.id, text) - const threadId = res.body.comment.id + const created = await servers[2].commentsCommand.createThread({ videoId: video4.id, text }) + const threadId = created.id const text1 = 'answer to deleted' - await addVideoCommentReply(servers[2].url, servers[2].accessToken, video4.id, threadId, text1) + await servers[2].commentsCommand.addReply({ videoId: video4.id, toCommentId: threadId, text: text1 }) const text2 = 'will also be deleted' - const childCommentRes = await addVideoCommentReply(servers[2].url, servers[2].accessToken, video4.id, threadId, text2) - const childCommentId = childCommentRes.body.comment.id + const childComment = await servers[2].commentsCommand.addReply({ videoId: video4.id, toCommentId: threadId, text: text2 }) const text3 = 'my second answer to deleted' - await addVideoCommentReply(servers[2].url, servers[2].accessToken, video4.id, childCommentId, text3) + await servers[2].commentsCommand.addReply({ videoId: video4.id, toCommentId: childComment.id, text: text3 }) - await deleteVideoComment(servers[2].url, servers[2].accessToken, video4.id, threadId) - await deleteVideoComment(servers[2].url, servers[2].accessToken, video4.id, childCommentId) + await servers[2].commentsCommand.delete({ videoId: video4.id, commentId: threadId }) + await servers[2].commentsCommand.delete({ videoId: video4.id, commentId: childComment.id }) } } @@ -462,14 +455,14 @@ describe('Test follows', function () { }) it('Should have propagated comments', async function () { - const res1 = await getVideoCommentThreads(servers[0].url, video4.id, 0, 5, 'createdAt') + const { total, data } = await servers[0].commentsCommand.listThreads({ videoId: video4.id, sort: 'createdAt' }) - expect(res1.body.total).to.equal(2) - expect(res1.body.data).to.be.an('array') - expect(res1.body.data).to.have.lengthOf(2) + expect(total).to.equal(2) + expect(data).to.be.an('array') + expect(data).to.have.lengthOf(2) { - const comment: VideoComment = res1.body.data[0] + const comment = data[0] expect(comment.inReplyToCommentId).to.be.null expect(comment.text).equal('my super first comment') expect(comment.videoId).to.equal(video4.id) @@ -482,9 +475,7 @@ describe('Test follows', function () { const threadId = comment.threadId - const res2 = await getVideoThreadComments(servers[0].url, video4.id, threadId) - - const tree: VideoCommentThreadTree = res2.body + const tree = await servers[0].commentsCommand.getThread({ videoId: video4.id, threadId }) expect(tree.comment.text).equal('my super first comment') expect(tree.children).to.have.lengthOf(2) @@ -502,7 +493,7 @@ describe('Test follows', function () { } { - const deletedComment: VideoComment = res1.body.data[1] + const deletedComment = data[1] expect(deletedComment).to.not.be.undefined expect(deletedComment.isDeleted).to.be.true expect(deletedComment.deletedAt).to.not.be.null @@ -512,9 +503,7 @@ describe('Test follows', function () { expect(deletedComment.totalReplies).to.equal(2) expect(dateIsValid(deletedComment.deletedAt as string)).to.be.true - const res2 = await getVideoThreadComments(servers[0].url, video4.id, deletedComment.threadId) - - const tree: VideoCommentThreadTree = res2.body + const tree = await servers[0].commentsCommand.getThread({ videoId: video4.id, threadId: deletedComment.threadId }) const [ commentRoot, deletedChildRoot ] = tree.children expect(deletedChildRoot).to.not.be.undefined diff --git a/server/tests/api/server/handle-down.ts b/server/tests/api/server/handle-down.ts index c6202fdaa..94496a159 100644 --- a/server/tests/api/server/handle-down.ts +++ b/server/tests/api/server/handle-down.ts @@ -4,16 +4,13 @@ import 'mocha' import * as chai from 'chai' import { HttpStatusCode } from '@shared/core-utils' import { - addVideoCommentReply, - addVideoCommentThread, cleanupTests, closeAllSequelize, + CommentsCommand, completeVideoCheck, flushAndRunMultipleServers, getVideo, - getVideoCommentThreads, getVideosList, - getVideoThreadComments, immutableAssign, killallServers, reRunServer, @@ -26,7 +23,7 @@ import { wait, waitJobs } from '@shared/extra-utils' -import { JobState, Video, VideoCommentThreadTree, VideoPrivacy } from '@shared/models' +import { JobState, Video, VideoPrivacy } from '@shared/models' const expect = chai.expect @@ -62,10 +59,13 @@ describe('Test handle downs', function () { let checkAttributes: any let unlistedCheckAttributes: any + let commentCommands: CommentsCommand[] + before(async function () { this.timeout(30000) servers = await flushAndRunMultipleServers(3) + commentCommands = servers.map(s => s.commentsCommand) checkAttributes = { name: 'my super name for server 1', @@ -154,15 +154,13 @@ describe('Test handle downs', function () { // Add comments to video 2 { const text = 'thread 1' - let resComment = await addVideoCommentThread(servers[0].url, servers[0].accessToken, missedVideo2.uuid, text) - let comment = resComment.body.comment + let comment = await commentCommands[0].createThread({ videoId: missedVideo2.uuid, text }) threadIdServer1 = comment.id - resComment = await addVideoCommentReply(servers[0].url, servers[0].accessToken, missedVideo2.uuid, comment.id, 'comment 1-1') - comment = resComment.body.comment + comment = await commentCommands[0].addReply({ videoId: missedVideo2.uuid, toCommentId: comment.id, text: 'comment 1-1' }) - resComment = await addVideoCommentReply(servers[0].url, servers[0].accessToken, missedVideo2.uuid, comment.id, 'comment 1-2') - commentIdServer1 = resComment.body.comment.id + const created = await commentCommands[0].addReply({ videoId: missedVideo2.uuid, toCommentId: comment.id, text: 'comment 1-2' }) + commentIdServer1 = created.id } await waitJobs(servers[0]) @@ -235,7 +233,7 @@ describe('Test handle downs', function () { it('Should send comments on a video to server 3, and automatically fetch the video', async function () { this.timeout(25000) - await addVideoCommentReply(servers[0].url, servers[0].accessToken, missedVideo2.uuid, commentIdServer1, 'comment 1-3') + await commentCommands[0].addReply({ videoId: missedVideo2.uuid, toCommentId: commentIdServer1, text: 'comment 1-3' }) await waitJobs(servers) @@ -243,15 +241,13 @@ describe('Test handle downs', function () { expect(resVideo.body).not.to.be.undefined { - let resComment = await getVideoCommentThreads(servers[2].url, missedVideo2.uuid, 0, 5) - expect(resComment.body.data).to.be.an('array') - expect(resComment.body.data).to.have.lengthOf(1) - - threadIdServer2 = resComment.body.data[0].id + const { data } = await servers[2].commentsCommand.listThreads({ videoId: missedVideo2.uuid }) + expect(data).to.be.an('array') + expect(data).to.have.lengthOf(1) - resComment = await getVideoThreadComments(servers[2].url, missedVideo2.uuid, threadIdServer2) + threadIdServer2 = data[0].id - const tree: VideoCommentThreadTree = resComment.body + const tree = await servers[2].commentsCommand.getThread({ videoId: missedVideo2.uuid, threadId: threadIdServer2 }) expect(tree.comment.text).equal('thread 1') expect(tree.children).to.have.lengthOf(1) @@ -274,33 +270,30 @@ describe('Test handle downs', function () { it('Should correctly reply to the comment', async function () { this.timeout(15000) - await addVideoCommentReply(servers[2].url, servers[2].accessToken, missedVideo2.uuid, commentIdServer2, 'comment 1-4') + await servers[2].commentsCommand.addReply({ videoId: missedVideo2.uuid, toCommentId: commentIdServer2, text: 'comment 1-4' }) await waitJobs(servers) - { - const resComment = await getVideoThreadComments(servers[0].url, missedVideo2.uuid, threadIdServer1) + const tree = await commentCommands[0].getThread({ videoId: missedVideo2.uuid, threadId: threadIdServer1 }) - const tree: VideoCommentThreadTree = resComment.body - expect(tree.comment.text).equal('thread 1') - expect(tree.children).to.have.lengthOf(1) + expect(tree.comment.text).equal('thread 1') + expect(tree.children).to.have.lengthOf(1) - const firstChild = tree.children[0] - expect(firstChild.comment.text).to.equal('comment 1-1') - expect(firstChild.children).to.have.lengthOf(1) + const firstChild = tree.children[0] + expect(firstChild.comment.text).to.equal('comment 1-1') + expect(firstChild.children).to.have.lengthOf(1) - const childOfFirstChild = firstChild.children[0] - expect(childOfFirstChild.comment.text).to.equal('comment 1-2') - expect(childOfFirstChild.children).to.have.lengthOf(1) + const childOfFirstChild = firstChild.children[0] + expect(childOfFirstChild.comment.text).to.equal('comment 1-2') + expect(childOfFirstChild.children).to.have.lengthOf(1) - const childOfChildFirstChild = childOfFirstChild.children[0] - expect(childOfChildFirstChild.comment.text).to.equal('comment 1-3') - expect(childOfChildFirstChild.children).to.have.lengthOf(1) + const childOfChildFirstChild = childOfFirstChild.children[0] + expect(childOfChildFirstChild.comment.text).to.equal('comment 1-3') + expect(childOfChildFirstChild.children).to.have.lengthOf(1) - const childOfChildOfChildOfFirstChild = childOfChildFirstChild.children[0] - expect(childOfChildOfChildOfFirstChild.comment.text).to.equal('comment 1-4') - expect(childOfChildOfChildOfFirstChild.children).to.have.lengthOf(0) - } + const childOfChildOfChildOfFirstChild = childOfChildFirstChild.children[0] + expect(childOfChildOfChildOfFirstChild.comment.text).to.equal('comment 1-4') + expect(childOfChildOfChildOfFirstChild.children).to.have.lengthOf(0) }) it('Should upload many videos on server 1', async function () { diff --git a/server/tests/api/server/stats.ts b/server/tests/api/server/stats.ts index 9c954c347..ded305899 100644 --- a/server/tests/api/server/stats.ts +++ b/server/tests/api/server/stats.ts @@ -3,7 +3,6 @@ import 'mocha' import * as chai from 'chai' import { - addVideoCommentThread, cleanupTests, createUser, doubleFollow, @@ -42,7 +41,7 @@ describe('Test stats (excluding redundancy)', function () { const resVideo = await uploadVideo(servers[0].url, servers[0].accessToken, { fixture: 'video_short.webm' }) const videoUUID = resVideo.body.video.uuid - await addVideoCommentThread(servers[0].url, servers[0].accessToken, videoUUID, 'comment') + await servers[0].commentsCommand.createThread({ videoId: videoUUID, text: 'comment' }) await viewVideo(servers[0].url, videoUUID) diff --git a/server/tests/api/users/users.ts b/server/tests/api/users/users.ts index ed670b3c9..4d255f340 100644 --- a/server/tests/api/users/users.ts +++ b/server/tests/api/users/users.ts @@ -4,7 +4,6 @@ import 'mocha' import * as chai from 'chai' import { HttpStatusCode } from '@shared/core-utils' import { - addVideoCommentThread, blockUser, cleanupTests, closeAllSequelize, @@ -983,7 +982,7 @@ describe('Test users', function () { it('Should report correct video comments for user', async function () { const text = 'super comment' - await addVideoCommentThread(server.url, user17AccessToken, videoId, text) + await server.commentsCommand.createThread({ token: user17AccessToken, videoId, text }) const res = await getUserInformation(server.url, server.accessToken, user17Id, true) const user: User = res.body diff --git a/server/tests/api/videos/multiple-servers.ts b/server/tests/api/videos/multiple-servers.ts index a59d5a858..2148d8e1c 100644 --- a/server/tests/api/videos/multiple-servers.ts +++ b/server/tests/api/videos/multiple-servers.ts @@ -3,7 +3,7 @@ import 'mocha' import * as chai from 'chai' import * as request from 'supertest' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '@shared/core-utils' import { buildAbsoluteFixturePath, checkTmpIsEmpty, @@ -27,18 +27,10 @@ import { userLogin, viewVideo, wait, + waitJobs, webtorrentAdd -} from '../../../../shared/extra-utils' -import { waitJobs } from '../../../../shared/extra-utils/server/jobs' -import { - addVideoCommentReply, - addVideoCommentThread, - deleteVideoComment, - findCommentId, - getVideoCommentThreads, - getVideoThreadComments -} from '../../../../shared/extra-utils/videos/video-comments' -import { VideoComment, VideoCommentThreadTree, VideoPrivacy } from '../../../../shared/models/videos' +} from '@shared/extra-utils' +import { VideoCommentThreadTree, VideoPrivacy } from '@shared/models' const expect = chai.expect @@ -762,36 +754,36 @@ describe('Test multiple servers', function () { { const text = 'my super first comment' - await addVideoCommentThread(servers[0].url, servers[0].accessToken, videoUUID, text) + await servers[0].commentsCommand.createThread({ videoId: videoUUID, text }) } { const text = 'my super second comment' - await addVideoCommentThread(servers[2].url, servers[2].accessToken, videoUUID, text) + await servers[2].commentsCommand.createThread({ videoId: videoUUID, text }) } await waitJobs(servers) { - const threadId = await findCommentId(servers[1].url, videoUUID, 'my super first comment') + const threadId = await servers[1].commentsCommand.findCommentId({ videoId: videoUUID, text: 'my super first comment' }) const text = 'my super answer to thread 1' - await addVideoCommentReply(servers[1].url, servers[1].accessToken, videoUUID, threadId, text) + await servers[1].commentsCommand.addReply({ videoId: videoUUID, toCommentId: threadId, text }) } await waitJobs(servers) { - const threadId = await findCommentId(servers[2].url, videoUUID, 'my super first comment') + const threadId = await servers[2].commentsCommand.findCommentId({ videoId: videoUUID, text: 'my super first comment' }) - const res2 = await getVideoThreadComments(servers[2].url, videoUUID, threadId) - const childCommentId = res2.body.children[0].comment.id + const body = await servers[2].commentsCommand.getThread({ videoId: videoUUID, threadId }) + const childCommentId = body.children[0].comment.id const text3 = 'my second answer to thread 1' - await addVideoCommentReply(servers[2].url, servers[2].accessToken, videoUUID, threadId, text3) + await servers[2].commentsCommand.addReply({ videoId: videoUUID, toCommentId: threadId, text: text3 }) const text2 = 'my super answer to answer of thread 1' - await addVideoCommentReply(servers[2].url, servers[2].accessToken, videoUUID, childCommentId, text2) + await servers[2].commentsCommand.addReply({ videoId: videoUUID, toCommentId: childCommentId, text: text2 }) } await waitJobs(servers) @@ -799,14 +791,14 @@ describe('Test multiple servers', function () { it('Should have these threads', async function () { for (const server of servers) { - const res = await getVideoCommentThreads(server.url, videoUUID, 0, 5) + const body = await server.commentsCommand.listThreads({ videoId: videoUUID }) - expect(res.body.total).to.equal(2) - expect(res.body.data).to.be.an('array') - expect(res.body.data).to.have.lengthOf(2) + expect(body.total).to.equal(2) + expect(body.data).to.be.an('array') + expect(body.data).to.have.lengthOf(2) { - const comment: VideoComment = res.body.data.find(c => c.text === 'my super first comment') + const comment = body.data.find(c => c.text === 'my super first comment') expect(comment).to.not.be.undefined expect(comment.inReplyToCommentId).to.be.null expect(comment.account.name).to.equal('root') @@ -817,7 +809,7 @@ describe('Test multiple servers', function () { } { - const comment: VideoComment = res.body.data.find(c => c.text === 'my super second comment') + const comment = body.data.find(c => c.text === 'my super second comment') expect(comment).to.not.be.undefined expect(comment.inReplyToCommentId).to.be.null expect(comment.account.name).to.equal('root') @@ -831,12 +823,11 @@ describe('Test multiple servers', function () { it('Should have these comments', async function () { for (const server of servers) { - const res1 = await getVideoCommentThreads(server.url, videoUUID, 0, 5) - const threadId = res1.body.data.find(c => c.text === 'my super first comment').id + const body = await server.commentsCommand.listThreads({ videoId: videoUUID }) + const threadId = body.data.find(c => c.text === 'my super first comment').id - const res2 = await getVideoThreadComments(server.url, videoUUID, threadId) + const tree = await server.commentsCommand.getThread({ videoId: videoUUID, threadId }) - const tree: VideoCommentThreadTree = res2.body expect(tree.comment.text).equal('my super first comment') expect(tree.comment.account.name).equal('root') expect(tree.comment.account.host).equal('localhost:' + servers[0].port) @@ -865,19 +856,17 @@ describe('Test multiple servers', function () { it('Should delete a reply', async function () { this.timeout(10000) - await deleteVideoComment(servers[2].url, servers[2].accessToken, videoUUID, childOfFirstChild.comment.id) + await servers[2].commentsCommand.delete({ videoId: videoUUID, commentId: childOfFirstChild.comment.id }) await waitJobs(servers) }) it('Should have this comment marked as deleted', async function () { for (const server of servers) { - const res1 = await getVideoCommentThreads(server.url, videoUUID, 0, 5) - const threadId = res1.body.data.find(c => c.text === 'my super first comment').id - - const res2 = await getVideoThreadComments(server.url, videoUUID, threadId) + const { data } = await server.commentsCommand.listThreads({ videoId: videoUUID }) + const threadId = data.find(c => c.text === 'my super first comment').id - const tree: VideoCommentThreadTree = res2.body + const tree = await server.commentsCommand.getThread({ videoId: videoUUID, threadId }) expect(tree.comment.text).equal('my super first comment') const firstChild = tree.children[0] @@ -898,23 +887,23 @@ describe('Test multiple servers', function () { it('Should delete the thread comments', async function () { this.timeout(10000) - const res = await getVideoCommentThreads(servers[0].url, videoUUID, 0, 5) - const threadId = res.body.data.find(c => c.text === 'my super first comment').id - await deleteVideoComment(servers[0].url, servers[0].accessToken, videoUUID, threadId) + const { data } = await servers[0].commentsCommand.listThreads({ videoId: videoUUID }) + const commentId = data.find(c => c.text === 'my super first comment').id + await servers[0].commentsCommand.delete({ videoId: videoUUID, commentId }) await waitJobs(servers) }) it('Should have the threads marked as deleted on other servers too', async function () { for (const server of servers) { - const res = await getVideoCommentThreads(server.url, videoUUID, 0, 5) + const body = await server.commentsCommand.listThreads({ videoId: videoUUID }) - expect(res.body.total).to.equal(2) - expect(res.body.data).to.be.an('array') - expect(res.body.data).to.have.lengthOf(2) + expect(body.total).to.equal(2) + expect(body.data).to.be.an('array') + expect(body.data).to.have.lengthOf(2) { - const comment: VideoComment = res.body.data[0] + const comment = body.data[0] expect(comment).to.not.be.undefined expect(comment.inReplyToCommentId).to.be.null expect(comment.account.name).to.equal('root') @@ -925,7 +914,7 @@ describe('Test multiple servers', function () { } { - const deletedComment: VideoComment = res.body.data[1] + const deletedComment = body.data[1] expect(deletedComment).to.not.be.undefined expect(deletedComment.isDeleted).to.be.true expect(deletedComment.deletedAt).to.not.be.null @@ -943,22 +932,22 @@ describe('Test multiple servers', function () { it('Should delete a remote thread by the origin server', async function () { this.timeout(5000) - const res = await getVideoCommentThreads(servers[0].url, videoUUID, 0, 5) - const threadId = res.body.data.find(c => c.text === 'my super second comment').id - await deleteVideoComment(servers[0].url, servers[0].accessToken, videoUUID, threadId) + const { data } = await servers[0].commentsCommand.listThreads({ videoId: videoUUID }) + const commentId = data.find(c => c.text === 'my super second comment').id + await servers[0].commentsCommand.delete({ videoId: videoUUID, commentId }) await waitJobs(servers) }) it('Should have the threads marked as deleted on other servers too', async function () { for (const server of servers) { - const res = await getVideoCommentThreads(server.url, videoUUID, 0, 5) + const body = await server.commentsCommand.listThreads({ videoId: videoUUID }) - expect(res.body.total).to.equal(2) - expect(res.body.data).to.have.lengthOf(2) + expect(body.total).to.equal(2) + expect(body.data).to.have.lengthOf(2) { - const comment: VideoComment = res.body.data[0] + const comment = body.data[0] expect(comment.text).to.equal('') expect(comment.isDeleted).to.be.true expect(comment.createdAt).to.not.be.null @@ -968,7 +957,7 @@ describe('Test multiple servers', function () { } { - const comment: VideoComment = res.body.data[1] + const comment = body.data[1] expect(comment.text).to.equal('') expect(comment.isDeleted).to.be.true expect(comment.createdAt).to.not.be.null @@ -997,7 +986,7 @@ describe('Test multiple servers', function () { expect(res.body.downloadEnabled).to.be.false const text = 'my super forbidden comment' - await addVideoCommentThread(server.url, server.accessToken, videoUUID, text, HttpStatusCode.CONFLICT_409) + await server.commentsCommand.createThread({ videoId: videoUUID, text, expectedStatus: HttpStatusCode.CONFLICT_409 }) } }) }) diff --git a/server/tests/api/videos/video-comments.ts b/server/tests/api/videos/video-comments.ts index b6b002307..548d9fbf5 100644 --- a/server/tests/api/videos/video-comments.ts +++ b/server/tests/api/videos/video-comments.ts @@ -2,38 +2,33 @@ import 'mocha' import * as chai from 'chai' -import { VideoComment, VideoCommentAdmin, VideoCommentThreadTree } from '@shared/models' -import { cleanupTests, testImage } from '../../../../shared/extra-utils' import { + cleanupTests, + CommentsCommand, createUser, dateIsValid, flushAndRunServer, getAccessToken, ServerInfo, setAccessTokensToServers, + testImage, updateMyAvatar, uploadVideo -} from '../../../../shared/extra-utils/index' -import { - addVideoCommentReply, - addVideoCommentThread, - deleteVideoComment, - getAdminVideoComments, - getVideoCommentThreads, - getVideoThreadComments -} from '../../../../shared/extra-utils/videos/video-comments' +} from '@shared/extra-utils' const expect = chai.expect describe('Test video comments', function () { let server: ServerInfo - let videoId - let videoUUID - let threadId + let videoId: number + let videoUUID: string + let threadId: number let replyToDeleteId: number let userAccessTokenServer1: string + let command: CommentsCommand + before(async function () { this.timeout(30000) @@ -58,24 +53,25 @@ describe('Test video comments', function () { password: 'password' }) userAccessTokenServer1 = await getAccessToken(server.url, 'user1', 'password') + + command = server.commentsCommand }) describe('User comments', function () { it('Should not have threads on this video', async function () { - const res = await getVideoCommentThreads(server.url, videoUUID, 0, 5) + const body = await command.listThreads({ videoId: videoUUID }) - expect(res.body.total).to.equal(0) - expect(res.body.totalNotDeletedComments).to.equal(0) - expect(res.body.data).to.be.an('array') - expect(res.body.data).to.have.lengthOf(0) + expect(body.total).to.equal(0) + expect(body.totalNotDeletedComments).to.equal(0) + expect(body.data).to.be.an('array') + expect(body.data).to.have.lengthOf(0) }) it('Should create a thread in this video', async function () { const text = 'my super first comment' - const res = await addVideoCommentThread(server.url, server.accessToken, videoUUID, text) - const comment = res.body.comment + const comment = await command.createThread({ videoId: videoUUID, text }) expect(comment.inReplyToCommentId).to.be.null expect(comment.text).equal('my super first comment') @@ -91,14 +87,14 @@ describe('Test video comments', function () { }) it('Should list threads of this video', async function () { - const res = await getVideoCommentThreads(server.url, videoUUID, 0, 5) + const body = await command.listThreads({ videoId: videoUUID }) - expect(res.body.total).to.equal(1) - expect(res.body.totalNotDeletedComments).to.equal(1) - expect(res.body.data).to.be.an('array') - expect(res.body.data).to.have.lengthOf(1) + expect(body.total).to.equal(1) + expect(body.totalNotDeletedComments).to.equal(1) + expect(body.data).to.be.an('array') + expect(body.data).to.have.lengthOf(1) - const comment: VideoComment = res.body.data[0] + const comment = body.data[0] expect(comment.inReplyToCommentId).to.be.null expect(comment.text).equal('my super first comment') expect(comment.videoId).to.equal(videoId) @@ -117,9 +113,9 @@ describe('Test video comments', function () { }) it('Should get all the thread created', async function () { - const res = await getVideoThreadComments(server.url, videoUUID, threadId) + const body = await command.getThread({ videoId: videoUUID, threadId }) - const rootComment = res.body.comment + const rootComment = body.comment expect(rootComment.inReplyToCommentId).to.be.null expect(rootComment.text).equal('my super first comment') expect(rootComment.videoId).to.equal(videoId) @@ -129,20 +125,19 @@ describe('Test video comments', function () { it('Should create multiple replies in this thread', async function () { const text1 = 'my super answer to thread 1' - const childCommentRes = await addVideoCommentReply(server.url, server.accessToken, videoId, threadId, text1) - const childCommentId = childCommentRes.body.comment.id + const created = await command.addReply({ videoId, toCommentId: threadId, text: text1 }) + const childCommentId = created.id const text2 = 'my super answer to answer of thread 1' - await addVideoCommentReply(server.url, server.accessToken, videoId, childCommentId, text2) + await command.addReply({ videoId, toCommentId: childCommentId, text: text2 }) const text3 = 'my second answer to thread 1' - await addVideoCommentReply(server.url, server.accessToken, videoId, threadId, text3) + await command.addReply({ videoId, toCommentId: threadId, text: text3 }) }) it('Should get correctly the replies', async function () { - const res = await getVideoThreadComments(server.url, videoUUID, threadId) + const tree = await command.getThread({ videoId: videoUUID, threadId }) - const tree: VideoCommentThreadTree = res.body expect(tree.comment.text).equal('my super first comment') expect(tree.children).to.have.lengthOf(2) @@ -163,42 +158,41 @@ describe('Test video comments', function () { it('Should create other threads', async function () { const text1 = 'super thread 2' - await addVideoCommentThread(server.url, server.accessToken, videoUUID, text1) + await command.createThread({ videoId: videoUUID, text: text1 }) const text2 = 'super thread 3' - await addVideoCommentThread(server.url, server.accessToken, videoUUID, text2) + await command.createThread({ videoId: videoUUID, text: text2 }) }) it('Should list the threads', async function () { - const res = await getVideoCommentThreads(server.url, videoUUID, 0, 5, 'createdAt') - - expect(res.body.total).to.equal(3) - expect(res.body.totalNotDeletedComments).to.equal(6) - expect(res.body.data).to.be.an('array') - expect(res.body.data).to.have.lengthOf(3) - - expect(res.body.data[0].text).to.equal('my super first comment') - expect(res.body.data[0].totalReplies).to.equal(3) - expect(res.body.data[1].text).to.equal('super thread 2') - expect(res.body.data[1].totalReplies).to.equal(0) - expect(res.body.data[2].text).to.equal('super thread 3') - expect(res.body.data[2].totalReplies).to.equal(0) + const body = await command.listThreads({ videoId: videoUUID, sort: 'createdAt' }) + + expect(body.total).to.equal(3) + expect(body.totalNotDeletedComments).to.equal(6) + expect(body.data).to.be.an('array') + expect(body.data).to.have.lengthOf(3) + + expect(body.data[0].text).to.equal('my super first comment') + expect(body.data[0].totalReplies).to.equal(3) + expect(body.data[1].text).to.equal('super thread 2') + expect(body.data[1].totalReplies).to.equal(0) + expect(body.data[2].text).to.equal('super thread 3') + expect(body.data[2].totalReplies).to.equal(0) }) it('Should delete a reply', async function () { - await deleteVideoComment(server.url, server.accessToken, videoId, replyToDeleteId) + await command.delete({ videoId, commentId: replyToDeleteId }) { - const res = await getVideoCommentThreads(server.url, videoUUID, 0, 5, 'createdAt') + const body = await command.listThreads({ videoId: videoUUID, sort: 'createdAt' }) - expect(res.body.total).to.equal(3) - expect(res.body.totalNotDeletedComments).to.equal(5) + expect(body.total).to.equal(3) + expect(body.totalNotDeletedComments).to.equal(5) } { - const res = await getVideoThreadComments(server.url, videoUUID, threadId) + const tree = await command.getThread({ videoId: videoUUID, threadId }) - const tree: VideoCommentThreadTree = res.body expect(tree.comment.text).equal('my super first comment') expect(tree.children).to.have.lengthOf(2) @@ -220,99 +214,88 @@ describe('Test video comments', function () { }) it('Should delete a complete thread', async function () { - await deleteVideoComment(server.url, server.accessToken, videoId, threadId) - - const res = await getVideoCommentThreads(server.url, videoUUID, 0, 5, 'createdAt') - expect(res.body.total).to.equal(3) - expect(res.body.data).to.be.an('array') - expect(res.body.data).to.have.lengthOf(3) - - expect(res.body.data[0].text).to.equal('') - expect(res.body.data[0].isDeleted).to.be.true - expect(res.body.data[0].deletedAt).to.not.be.null - expect(res.body.data[0].account).to.be.null - expect(res.body.data[0].totalReplies).to.equal(2) - expect(res.body.data[1].text).to.equal('super thread 2') - expect(res.body.data[1].totalReplies).to.equal(0) - expect(res.body.data[2].text).to.equal('super thread 3') - expect(res.body.data[2].totalReplies).to.equal(0) + await command.delete({ videoId, commentId: threadId }) + + const body = await command.listThreads({ videoId: videoUUID, sort: 'createdAt' }) + expect(body.total).to.equal(3) + expect(body.data).to.be.an('array') + expect(body.data).to.have.lengthOf(3) + + expect(body.data[0].text).to.equal('') + expect(body.data[0].isDeleted).to.be.true + expect(body.data[0].deletedAt).to.not.be.null + expect(body.data[0].account).to.be.null + expect(body.data[0].totalReplies).to.equal(2) + expect(body.data[1].text).to.equal('super thread 2') + expect(body.data[1].totalReplies).to.equal(0) + expect(body.data[2].text).to.equal('super thread 3') + expect(body.data[2].totalReplies).to.equal(0) }) it('Should count replies from the video author correctly', async function () { - const text = 'my super first comment' - await addVideoCommentThread(server.url, server.accessToken, videoUUID, text) - let res = await getVideoCommentThreads(server.url, videoUUID, 0, 5) - const comment: VideoComment = res.body.data[0] - const threadId2 = comment.threadId + await command.createThread({ videoId: videoUUID, text: 'my super first comment' }) + + const { data } = await command.listThreads({ videoId: videoUUID }) + const threadId2 = data[0].threadId const text2 = 'a first answer to thread 4 by a third party' - await addVideoCommentReply(server.url, userAccessTokenServer1, videoId, threadId2, text2) + await command.addReply({ token: userAccessTokenServer1, videoId, toCommentId: threadId2, text: text2 }) const text3 = 'my second answer to thread 4' - await addVideoCommentReply(server.url, server.accessToken, videoId, threadId2, text3) + await command.addReply({ videoId, toCommentId: threadId2, text: text3 }) - res = await getVideoThreadComments(server.url, videoUUID, threadId2) - const tree: VideoCommentThreadTree = res.body + const tree = await command.getThread({ videoId: videoUUID, threadId: threadId2 }) expect(tree.comment.totalReplies).to.equal(tree.comment.totalRepliesFromVideoAuthor + 1) }) }) describe('All instance comments', function () { - async function getComments (options: any = {}) { - const res = await getAdminVideoComments(Object.assign({ - url: server.url, - token: server.accessToken, - start: 0, - count: 10 - }, options)) - - return { comments: res.body.data as VideoCommentAdmin[], total: res.body.total as number } - } it('Should list instance comments as admin', async function () { - const { comments } = await getComments({ start: 0, count: 1 }) + const { data } = await command.listForAdmin({ start: 0, count: 1 }) - expect(comments[0].text).to.equal('my second answer to thread 4') + expect(data[0].text).to.equal('my second answer to thread 4') }) it('Should filter instance comments by isLocal', async function () { - const { total, comments } = await getComments({ isLocal: false }) + const { total, data } = await command.listForAdmin({ isLocal: false }) - expect(comments).to.have.lengthOf(0) + expect(data).to.have.lengthOf(0) expect(total).to.equal(0) }) it('Should search instance comments by account', async function () { - const { total, comments } = await getComments({ searchAccount: 'user' }) + const { total, data } = await command.listForAdmin({ searchAccount: 'user' }) - expect(comments).to.have.lengthOf(1) + expect(data).to.have.lengthOf(1) expect(total).to.equal(1) - expect(comments[0].text).to.equal('a first answer to thread 4 by a third party') + expect(data[0].text).to.equal('a first answer to thread 4 by a third party') }) it('Should search instance comments by video', async function () { { - const { total, comments } = await getComments({ searchVideo: 'video' }) + const { total, data } = await command.listForAdmin({ searchVideo: 'video' }) - expect(comments).to.have.lengthOf(7) + expect(data).to.have.lengthOf(7) expect(total).to.equal(7) } { - const { total, comments } = await getComments({ searchVideo: 'hello' }) + const { total, data } = await command.listForAdmin({ searchVideo: 'hello' }) - expect(comments).to.have.lengthOf(0) + expect(data).to.have.lengthOf(0) expect(total).to.equal(0) } }) it('Should search instance comments', async function () { - const { total, comments } = await getComments({ search: 'super thread 3' }) + const { total, data } = await command.listForAdmin({ search: 'super thread 3' }) - expect(comments).to.have.lengthOf(1) expect(total).to.equal(1) - expect(comments[0].text).to.equal('super thread 3') + + expect(data).to.have.lengthOf(1) + expect(data[0].text).to.equal('super thread 3') }) }) diff --git a/server/tests/cli/update-host.ts b/server/tests/cli/update-host.ts index 09a3dd1e7..61a6c403a 100644 --- a/server/tests/cli/update-host.ts +++ b/server/tests/cli/update-host.ts @@ -2,7 +2,6 @@ import 'mocha' import { - addVideoCommentThread, cleanupTests, createUser, flushAndRunServer, @@ -55,7 +54,7 @@ describe('Test update host scripts', function () { // Create comments const text = 'my super first comment' - await addVideoCommentThread(server.url, server.accessToken, video1UUID, text) + await server.commentsCommand.createThread({ videoId: video1UUID, text }) await waitJobs(server) }) diff --git a/server/tests/feeds/feeds.ts b/server/tests/feeds/feeds.ts index 6ee22340b..610849105 100644 --- a/server/tests/feeds/feeds.ts +++ b/server/tests/feeds/feeds.ts @@ -5,7 +5,6 @@ import * as chai from 'chai' import * as xmlParser from 'fast-xml-parser' import { HttpStatusCode } from '@shared/core-utils' import { - addVideoCommentThread, cleanupTests, createUser, doubleFollow, @@ -90,8 +89,8 @@ describe('Test syndication feeds', () => { const res = await uploadVideo(servers[0].url, servers[0].accessToken, videoAttributes) const videoId = res.body.video.id - await addVideoCommentThread(servers[0].url, servers[0].accessToken, videoId, 'super comment 1') - await addVideoCommentThread(servers[0].url, servers[0].accessToken, videoId, 'super comment 2') + await servers[0].commentsCommand.createThread({ videoId, text: 'super comment 1' }) + await servers[0].commentsCommand.createThread({ videoId, text: 'super comment 2' }) } { @@ -99,7 +98,7 @@ describe('Test syndication feeds', () => { const res = await uploadVideo(servers[0].url, servers[0].accessToken, videoAttributes) const videoId = res.body.video.id - await addVideoCommentThread(servers[0].url, servers[0].accessToken, videoId, 'comment on unlisted video') + await servers[0].commentsCommand.createThread({ videoId, text: 'comment on unlisted video' }) } await waitJobs(servers) @@ -277,7 +276,7 @@ describe('Test syndication feeds', () => { { const videoUUID = (await uploadVideoAndGetId({ server: servers[1], videoName: 'server 2' })).uuid await waitJobs(servers) - await addVideoCommentThread(servers[0].url, servers[0].accessToken, videoUUID, 'super comment') + await servers[0].commentsCommand.createThread({ videoId: videoUUID, text: 'super comment' }) await waitJobs(servers) const json = await servers[1].feedCommand.getJSON({ feed: 'video-comments', query: { version: 3 } }) diff --git a/server/tests/plugins/action-hooks.ts b/server/tests/plugins/action-hooks.ts index fd83bf2ac..6975ca4bb 100644 --- a/server/tests/plugins/action-hooks.ts +++ b/server/tests/plugins/action-hooks.ts @@ -3,11 +3,8 @@ import 'mocha' import { ServerHookName, VideoPlaylistPrivacy, VideoPrivacy } from '@shared/models' import { - addVideoCommentReply, - addVideoCommentThread, blockUser, createUser, - deleteVideoComment, PluginsCommand, registerUser, removeUser, @@ -101,20 +98,20 @@ describe('Test plugin action hooks', function () { describe('Comments hooks', function () { it('Should run action:api.video-thread.created', async function () { - const res = await addVideoCommentThread(servers[0].url, servers[0].accessToken, videoUUID, 'thread') - threadId = res.body.comment.id + const created = await servers[0].commentsCommand.createThread({ videoId: videoUUID, text: 'thread' }) + threadId = created.id await checkHook('action:api.video-thread.created') }) it('Should run action:api.video-comment-reply.created', async function () { - await addVideoCommentReply(servers[0].url, servers[0].accessToken, videoUUID, threadId, 'reply') + await servers[0].commentsCommand.addReply({ videoId: videoUUID, toCommentId: threadId, text: 'reply' }) await checkHook('action:api.video-comment-reply.created') }) it('Should run action:api.video-comment.deleted', async function () { - await deleteVideoComment(servers[0].url, servers[0].accessToken, videoUUID, threadId) + await servers[0].commentsCommand.delete({ videoId: videoUUID, commentId: threadId }) await checkHook('action:api.video-comment.deleted') }) diff --git a/server/tests/plugins/filter-hooks.ts b/server/tests/plugins/filter-hooks.ts index a3c3c0551..c235508e8 100644 --- a/server/tests/plugins/filter-hooks.ts +++ b/server/tests/plugins/filter-hooks.ts @@ -4,8 +4,6 @@ import 'mocha' import * as chai from 'chai' import { HttpStatusCode } from '@shared/core-utils' import { - addVideoCommentReply, - addVideoCommentThread, cleanupTests, doubleFollow, flushAndRunMultipleServers, @@ -13,10 +11,8 @@ import { getMyVideos, getVideo, getVideoChannelVideos, - getVideoCommentThreads, getVideosList, getVideosListPagination, - getVideoThreadComments, getVideoWithToken, ImportsCommand, makeRawRequest, @@ -31,7 +27,7 @@ import { waitJobs, waitUntilLog } from '@shared/extra-utils' -import { VideoCommentThreadTree, VideoDetails, VideoImportState, VideoPlaylist, VideoPlaylistPrivacy, VideoPrivacy } from '@shared/models' +import { VideoDetails, VideoImportState, VideoPlaylist, VideoPlaylistPrivacy, VideoPrivacy } from '@shared/models' const expect = chai.expect @@ -226,44 +222,50 @@ describe('Test plugin filter hooks', function () { }) it('Should run filter:api.video-thread.create.accept.result', async function () { - await addVideoCommentThread(servers[0].url, servers[0].accessToken, videoUUID, 'comment with bad word', HttpStatusCode.FORBIDDEN_403) + await servers[0].commentsCommand.createThread({ + videoId: videoUUID, + text: 'comment with bad word', + expectedStatus: HttpStatusCode.FORBIDDEN_403 + }) }) it('Should run filter:api.video-comment-reply.create.accept.result', async function () { - const res = await addVideoCommentThread(servers[0].url, servers[0].accessToken, videoUUID, 'thread') - threadId = res.body.comment.id - - await addVideoCommentReply( - servers[0].url, - servers[0].accessToken, - videoUUID, - threadId, - 'comment with bad word', - HttpStatusCode.FORBIDDEN_403 - ) - await addVideoCommentReply(servers[0].url, servers[0].accessToken, videoUUID, threadId, 'comment with good word', HttpStatusCode.OK_200) + const created = await servers[0].commentsCommand.createThread({ videoId: videoUUID, text: 'thread' }) + threadId = created.id + + await servers[0].commentsCommand.addReply({ + videoId: videoUUID, + toCommentId: threadId, + text: 'comment with bad word', + expectedStatus: HttpStatusCode.FORBIDDEN_403 + }) + await servers[0].commentsCommand.addReply({ + videoId: videoUUID, + toCommentId: threadId, + text: 'comment with good word', + expectedStatus: HttpStatusCode.OK_200 + }) }) it('Should run filter:api.video-threads.list.params', async function () { - const res = await getVideoCommentThreads(servers[0].url, videoUUID, 0, 0) + const { data } = await servers[0].commentsCommand.listThreads({ videoId: videoUUID, start: 0, count: 0 }) // our plugin do +1 to the count parameter - expect(res.body.data).to.have.lengthOf(1) + expect(data).to.have.lengthOf(1) }) it('Should run filter:api.video-threads.list.result', async function () { - const res = await getVideoCommentThreads(servers[0].url, videoUUID, 0, 0) + const { total } = await servers[0].commentsCommand.listThreads({ videoId: videoUUID, start: 0, count: 0 }) // Plugin do +1 to the total result - expect(res.body.total).to.equal(2) + expect(total).to.equal(2) }) it('Should run filter:api.video-thread-comments.list.params') it('Should run filter:api.video-thread-comments.list.result', async function () { - const res = await getVideoThreadComments(servers[0].url, videoUUID, threadId) + const thread = await servers[0].commentsCommand.getThread({ videoId: videoUUID, threadId }) - const thread = res.body as VideoCommentThreadTree expect(thread.comment.text.endsWith(' <3')).to.be.true }) diff --git a/shared/extra-utils/server/servers.ts b/shared/extra-utils/server/servers.ts index 68e10af5f..8e80a9842 100644 --- a/shared/extra-utils/server/servers.ts +++ b/shared/extra-utils/server/servers.ts @@ -30,6 +30,7 @@ import { ServicesCommand, StreamingPlaylistsCommand } from '../videos' +import { CommentsCommand } from '../videos/comments-command' import { ConfigCommand } from './config-command' import { ContactFormCommand } from './contact-form-command' import { DebugCommand } from './debug-command' @@ -121,6 +122,7 @@ interface ServerInfo { importsCommand?: ImportsCommand streamingPlaylistsCommand?: StreamingPlaylistsCommand channelsCommand?: ChannelsCommand + commentsCommand?: CommentsCommand } function parallelTests () { @@ -356,6 +358,7 @@ async function runServer (server: ServerInfo, configOverrideArg?: any, args = [] server.importsCommand = new ImportsCommand(server) server.streamingPlaylistsCommand = new StreamingPlaylistsCommand(server) server.channelsCommand = new ChannelsCommand(server) + server.commentsCommand = new CommentsCommand(server) res(server) }) diff --git a/shared/extra-utils/videos/comments-command.ts b/shared/extra-utils/videos/comments-command.ts new file mode 100644 index 000000000..b31f3e2dd --- /dev/null +++ b/shared/extra-utils/videos/comments-command.ts @@ -0,0 +1,132 @@ +import { pick } from 'lodash' +import { ResultList, VideoComment, VideoCommentThreads, VideoCommentThreadTree } from '@shared/models' +import { HttpStatusCode } from '../../core-utils/miscs/http-error-codes' +import { unwrapBody } from '../requests' +import { AbstractCommand, OverrideCommandOptions } from '../shared' + +export class CommentsCommand extends AbstractCommand { + + listForAdmin (options: OverrideCommandOptions & { + start?: number + count?: number + sort?: string + isLocal?: boolean + search?: string + searchAccount?: string + searchVideo?: string + } = {}) { + const { sort = '-createdAt' } = options + const path = '/api/v1/videos/comments' + + const query = { sort, ...pick(options, [ 'start', 'count', 'isLocal', 'search', 'searchAccount', 'searchVideo' ]) } + + return this.getRequestBody>({ + ...options, + + path, + query, + implicitToken: true, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } + + listThreads (options: OverrideCommandOptions & { + videoId: number | string + start?: number + count?: number + sort?: string + }) { + const { start, count, sort, videoId } = options + const path = '/api/v1/videos/' + videoId + '/comment-threads' + + return this.getRequestBody({ + ...options, + + path, + query: { start, count, sort }, + implicitToken: false, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } + + getThread (options: OverrideCommandOptions & { + videoId: number | string + threadId: number + }) { + const { videoId, threadId } = options + const path = '/api/v1/videos/' + videoId + '/comment-threads/' + threadId + + return this.getRequestBody({ + ...options, + + path, + implicitToken: false, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } + + async createThread (options: OverrideCommandOptions & { + videoId: number | string + text: string + }) { + const { videoId, text } = options + const path = '/api/v1/videos/' + videoId + '/comment-threads' + + const body = await unwrapBody<{ comment: VideoComment }>(this.postBodyRequest({ + ...options, + + path, + fields: { text }, + implicitToken: true, + defaultExpectedStatus: HttpStatusCode.OK_200 + })) + + return body.comment + } + + async addReply (options: OverrideCommandOptions & { + videoId: number | string + toCommentId: number + text: string + }) { + const { videoId, toCommentId, text } = options + const path = '/api/v1/videos/' + videoId + '/comments/' + toCommentId + + const body = await unwrapBody<{ comment: VideoComment }>(this.postBodyRequest({ + ...options, + + path, + fields: { text }, + implicitToken: true, + defaultExpectedStatus: HttpStatusCode.OK_200 + })) + + return body.comment + } + + async findCommentId (options: OverrideCommandOptions & { + videoId: number | string + text: string + }) { + const { videoId, text } = options + const { data } = await this.listThreads({ videoId, count: 25, sort: '-createdAt' }) + + return data.find(c => c.text === text).id + } + + delete (options: OverrideCommandOptions & { + videoId: number | string + commentId: number + }) { + const { videoId, commentId } = options + const path = '/api/v1/videos/' + videoId + '/comments/' + commentId + + return this.deleteRequest({ + ...options, + + path, + implicitToken: true, + defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 + }) + } +} diff --git a/shared/extra-utils/videos/index.ts b/shared/extra-utils/videos/index.ts index 3bc219281..652d82842 100644 --- a/shared/extra-utils/videos/index.ts +++ b/shared/extra-utils/videos/index.ts @@ -4,6 +4,7 @@ export * from './captions' export * from './change-ownership-command' export * from './channels' export * from './channels-command' +export * from './comments-command' export * from './history-command' export * from './imports-command' export * from './live-command' @@ -13,5 +14,5 @@ export * from './playlists' export * from './services-command' export * from './streaming-playlists-command' export * from './streaming-playlists' -export * from './video-comments' +export * from './comments-command' export * from './videos' diff --git a/shared/extra-utils/videos/streaming-playlists-command.ts b/shared/extra-utils/videos/streaming-playlists-command.ts index 4caec7137..b109597c9 100644 --- a/shared/extra-utils/videos/streaming-playlists-command.ts +++ b/shared/extra-utils/videos/streaming-playlists-command.ts @@ -27,7 +27,7 @@ export class StreamingPlaylistsCommand extends AbstractCommand { url: options.url, range: options.range, implicitToken: false, - defaultExpectedStatus: HttpStatusCode.OK_200, + defaultExpectedStatus: HttpStatusCode.OK_200 })) } diff --git a/shared/extra-utils/videos/video-comments.ts b/shared/extra-utils/videos/video-comments.ts deleted file mode 100644 index 71b9f875a..000000000 --- a/shared/extra-utils/videos/video-comments.ts +++ /dev/null @@ -1,138 +0,0 @@ -/* eslint-disable @typescript-eslint/no-floating-promises */ - -import * as request from 'supertest' -import { makeDeleteRequest, makeGetRequest } from '../requests/requests' -import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' - -function getAdminVideoComments (options: { - url: string - token: string - start: number - count: number - sort?: string - isLocal?: boolean - search?: string - searchAccount?: string - searchVideo?: string -}) { - const { url, token, start, count, sort, isLocal, search, searchAccount, searchVideo } = options - const path = '/api/v1/videos/comments' - - const query = { - start, - count, - sort: sort || '-createdAt' - } - - if (isLocal !== undefined) Object.assign(query, { isLocal }) - if (search !== undefined) Object.assign(query, { search }) - if (searchAccount !== undefined) Object.assign(query, { searchAccount }) - if (searchVideo !== undefined) Object.assign(query, { searchVideo }) - - return makeGetRequest({ - url, - path, - token, - query, - statusCodeExpected: HttpStatusCode.OK_200 - }) -} - -function getVideoCommentThreads (url: string, videoId: number | string, start: number, count: number, sort?: string, token?: string) { - const path = '/api/v1/videos/' + videoId + '/comment-threads' - - const req = request(url) - .get(path) - .query({ start: start }) - .query({ count: count }) - - if (sort) req.query({ sort }) - if (token) req.set('Authorization', 'Bearer ' + token) - - return req.set('Accept', 'application/json') - .expect(HttpStatusCode.OK_200) - .expect('Content-Type', /json/) -} - -function getVideoThreadComments (url: string, videoId: number | string, threadId: number, token?: string) { - const path = '/api/v1/videos/' + videoId + '/comment-threads/' + threadId - - const req = request(url) - .get(path) - .set('Accept', 'application/json') - - if (token) req.set('Authorization', 'Bearer ' + token) - - return req.expect(HttpStatusCode.OK_200) - .expect('Content-Type', /json/) -} - -function addVideoCommentThread ( - url: string, - token: string, - videoId: number | string, - text: string, - expectedStatus = HttpStatusCode.OK_200 -) { - const path = '/api/v1/videos/' + videoId + '/comment-threads' - - return request(url) - .post(path) - .send({ text }) - .set('Accept', 'application/json') - .set('Authorization', 'Bearer ' + token) - .expect(expectedStatus) -} - -function addVideoCommentReply ( - url: string, - token: string, - videoId: number | string, - inReplyToCommentId: number, - text: string, - expectedStatus = HttpStatusCode.OK_200 -) { - const path = '/api/v1/videos/' + videoId + '/comments/' + inReplyToCommentId - - return request(url) - .post(path) - .send({ text }) - .set('Accept', 'application/json') - .set('Authorization', 'Bearer ' + token) - .expect(expectedStatus) -} - -async function findCommentId (url: string, videoId: number | string, text: string) { - const res = await getVideoCommentThreads(url, videoId, 0, 25, '-createdAt') - - return res.body.data.find(c => c.text === text).id as number -} - -function deleteVideoComment ( - url: string, - token: string, - videoId: number | string, - commentId: number, - statusCodeExpected = HttpStatusCode.NO_CONTENT_204 -) { - const path = '/api/v1/videos/' + videoId + '/comments/' + commentId - - return makeDeleteRequest({ - url, - path, - token, - statusCodeExpected - }) -} - -// --------------------------------------------------------------------------- - -export { - getVideoCommentThreads, - getAdminVideoComments, - getVideoThreadComments, - addVideoCommentThread, - addVideoCommentReply, - findCommentId, - deleteVideoComment -} diff --git a/shared/models/videos/comment/index.ts b/shared/models/videos/comment/index.ts index 7b9261a36..80c6c0724 100644 --- a/shared/models/videos/comment/index.ts +++ b/shared/models/videos/comment/index.ts @@ -1 +1,2 @@ +export * from './video-comment-create.model' export * from './video-comment.model' diff --git a/shared/models/videos/comment/video-comment-create.model.ts b/shared/models/videos/comment/video-comment-create.model.ts new file mode 100644 index 000000000..1f0135405 --- /dev/null +++ b/shared/models/videos/comment/video-comment-create.model.ts @@ -0,0 +1,3 @@ +export interface VideoCommentCreate { + text: string +} diff --git a/shared/models/videos/comment/video-comment.model.ts b/shared/models/videos/comment/video-comment.model.ts index 79c0e4c0a..5a96f9d4a 100644 --- a/shared/models/videos/comment/video-comment.model.ts +++ b/shared/models/videos/comment/video-comment.model.ts @@ -1,3 +1,4 @@ +import { ResultList } from '@shared/models/common' import { Account } from '../../actors' export interface VideoComment { @@ -36,11 +37,9 @@ export interface VideoCommentAdmin { } } +export type VideoCommentThreads = ResultList & { totalNotDeletedComments: number } + export interface VideoCommentThreadTree { comment: VideoComment children: VideoCommentThreadTree[] } - -export interface VideoCommentCreate { - text: string -} -- cgit v1.2.3 From 078f17e6d90376050f43ce639e88e11869b49ee7 Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Fri, 9 Jul 2021 15:03:44 +0200 Subject: Fix CLI tools --- server/tests/cli/peertube.ts | 9 +++ server/tests/cli/update-host.ts | 3 +- server/tools/cli.ts | 32 ++++++--- server/tools/peertube-get-access-token.ts | 19 +----- server/tools/peertube-import-videos.ts | 89 ++++++++++++------------- server/tools/peertube-plugins.ts | 49 +++++--------- server/tools/peertube-redundancy.ts | 61 ++++++----------- server/tools/peertube-upload.ts | 9 +-- server/tools/test-live.ts | 102 +++++++++++++++++++++++++++++ server/tools/test.ts | 105 ------------------------------ shared/extra-utils/server/servers.ts | 89 +++++++++++++------------ shared/extra-utils/users/login.ts | 4 +- 12 files changed, 267 insertions(+), 304 deletions(-) create mode 100644 server/tools/test-live.ts delete mode 100644 server/tools/test.ts diff --git a/server/tests/cli/peertube.ts b/server/tests/cli/peertube.ts index ef7ab5bd5..5ab07edb0 100644 --- a/server/tests/cli/peertube.ts +++ b/server/tests/cli/peertube.ts @@ -12,6 +12,7 @@ import { doubleFollow, flushAndRunServer, getLocalIdByUUID, + getMyUserInformation, getVideo, getVideosList, ImportsCommand, @@ -52,6 +53,14 @@ describe('Test CLI wrapper', function () { describe('Authentication and instance selection', function () { + it('Should get an access token', async function () { + const stdout = await cliCommand.execWithEnv(`${cmd} token --url ${server.url} --username user_1 --password super_password`) + const token = stdout.trim() + + const res = await getMyUserInformation(server.url, token) + expect(res.body.username).to.equal('user_1') + }) + it('Should display no selected instance', async function () { this.timeout(60000) diff --git a/server/tests/cli/update-host.ts b/server/tests/cli/update-host.ts index 61a6c403a..d3a1520cf 100644 --- a/server/tests/cli/update-host.ts +++ b/server/tests/cli/update-host.ts @@ -1,6 +1,7 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ import 'mocha' +import { expect } from 'chai' import { cleanupTests, createUser, @@ -18,8 +19,6 @@ import { } from '@shared/extra-utils' import { VideoDetails } from '@shared/models' -const expect = chai.expect - describe('Test update host scripts', function () { let server: ServerInfo diff --git a/server/tools/cli.ts b/server/tools/cli.ts index 7b94306cd..0528859a4 100644 --- a/server/tools/cli.ts +++ b/server/tools/cli.ts @@ -1,14 +1,14 @@ +import { Command } from 'commander' import { Netrc } from 'netrc-parser' -import { getAppNumber, isTestInstance } from '../helpers/core-utils' import { join } from 'path' -import { root } from '../../shared/extra-utils/miscs/miscs' -import { getVideoChannel } from '../../shared/extra-utils/videos/video-channels' -import { VideoChannel, VideoPrivacy } from '../../shared/models/videos' import { createLogger, format, transports } from 'winston' +import { assignCommands, ServerInfo } from '@shared/extra-utils' +import { getAccessToken } from '@shared/extra-utils/users/login' import { getMyUserInformation } from '@shared/extra-utils/users/users' import { User, UserRole } from '@shared/models' -import { getAccessToken } from '@shared/extra-utils/users/login' -import { Command } from 'commander' +import { root } from '../../shared/extra-utils/miscs/miscs' +import { VideoPrivacy } from '../../shared/models/videos' +import { getAppNumber, isTestInstance } from '../helpers/core-utils' let configName = 'PeerTube/CLI' if (isTestInstance()) configName += `-${getAppNumber()}` @@ -30,6 +30,10 @@ async function getAdminTokenOrDie (url: string, username: string, password: stri return accessToken } +async function getAccessTokenOrDie (url: string, username: string, password: string) { + return getAccessToken(url, username, password) +} + interface Settings { remotes: any[] default: number @@ -128,7 +132,7 @@ function buildCommonVideoOptions (command: Command) { .option('-v, --verbose ', 'Verbosity, from 0/\'error\' to 4/\'debug\'', 'info') } -async function buildVideoAttributesFromCommander (url: string, command: Command, defaultAttributes: any = {}) { +async function buildVideoAttributesFromCommander (server: ServerInfo, command: Command, defaultAttributes: any = {}) { const options = command.opts() const defaultBooleanAttributes = { @@ -164,8 +168,7 @@ async function buildVideoAttributesFromCommander (url: string, command: Command, Object.assign(videoAttributes, booleanAttributes) if (options.channelName) { - const res = await getVideoChannel(url, options.channelName) - const videoChannel: VideoChannel = res.body + const videoChannel = await server.channelsCommand.get({ channelName: options.channelName }) Object.assign(videoAttributes, { channelId: videoChannel.id }) @@ -184,6 +187,13 @@ function getServerCredentials (program: Command) { }) } +function buildServer (url: string, accessToken?: string): ServerInfo { + const server = { url, accessToken, internalServerNumber: undefined } + assignCommands(server) + + return server +} + function getLogger (logLevel = 'info') { const logLevels = { 0: 0, @@ -230,5 +240,7 @@ export { buildCommonVideoOptions, buildVideoAttributesFromCommander, - getAdminTokenOrDie + getAdminTokenOrDie, + getAccessTokenOrDie, + buildServer } diff --git a/server/tools/peertube-get-access-token.ts b/server/tools/peertube-get-access-token.ts index 9488eba0e..5868d0548 100644 --- a/server/tools/peertube-get-access-token.ts +++ b/server/tools/peertube-get-access-token.ts @@ -2,7 +2,7 @@ import { registerTSPaths } from '../helpers/register-ts-paths' registerTSPaths() import { program } from 'commander' -import { getClient, Server, serverLogin } from '../../shared/extra-utils' +import { getAccessToken } from '../../shared/extra-utils' program .option('-u, --url ', 'Server url') @@ -24,22 +24,7 @@ if ( process.exit(-1) } -getClient(options.url) - .then(res => { - const server = { - url: options.url, - user: { - username: options.username, - password: options.password - }, - client: { - id: res.body.client_id, - secret: res.body.client_secret - } - } as Server - - return serverLogin(server) - }) +getAccessToken(options.url, options.username, options.password) .then(accessToken => { console.log(accessToken) process.exit(0) diff --git a/server/tools/peertube-import-videos.ts b/server/tools/peertube-import-videos.ts index 101a95b2a..a546a8dbe 100644 --- a/server/tools/peertube-import-videos.ts +++ b/server/tools/peertube-import-videos.ts @@ -8,17 +8,19 @@ import { truncate } from 'lodash' import { join } from 'path' import * as prompt from 'prompt' import { promisify } from 'util' -import { advancedVideosSearch, getClient, getVideoCategories, login, uploadVideo } from '../../shared/extra-utils/index' +import { YoutubeDL } from '@server/helpers/youtube-dl' +import { getVideoCategories, uploadVideo } from '../../shared/extra-utils/index' import { sha256 } from '../helpers/core-utils' import { doRequestAndSaveToFile } from '../helpers/requests' import { CONSTRAINTS_FIELDS } from '../initializers/constants' -import { buildCommonVideoOptions, buildVideoAttributesFromCommander, getLogger, getServerCredentials } from './cli' -import { YoutubeDL } from '@server/helpers/youtube-dl' - -type UserInfo = { - username: string - password: string -} +import { + buildCommonVideoOptions, + buildServer, + buildVideoAttributesFromCommander, + getAccessTokenOrDie, + getLogger, + getServerCredentials +} from './cli' const processOptions = { maxBuffer: Infinity @@ -62,17 +64,13 @@ getServerCredentials(command) url = normalizeTargetUrl(url) options.targetUrl = normalizeTargetUrl(options.targetUrl) - const user = { username, password } - - run(url, user) + run(url, username, password) .catch(err => exitError(err)) }) .catch(err => console.error(err)) -async function run (url: string, user: UserInfo) { - if (!user.password) { - user.password = await promptPassword() - } +async function run (url: string, username: string, password: string) { + if (!password) password = await promptPassword() const youtubeDLBinary = await YoutubeDL.safeGetYoutubeDL() @@ -111,7 +109,8 @@ async function run (url: string, user: UserInfo) { await processVideo({ cwd: options.tmpdir, url, - user, + username, + password, youtubeInfo: info }) } catch (err) { @@ -119,17 +118,18 @@ async function run (url: string, user: UserInfo) { } } - log.info('Video/s for user %s imported: %s', user.username, options.targetUrl) + log.info('Video/s for user %s imported: %s', username, options.targetUrl) process.exit(0) } async function processVideo (parameters: { cwd: string url: string - user: { username: string, password: string } + username: string + password: string youtubeInfo: any }) { - const { youtubeInfo, cwd, url, user } = parameters + const { youtubeInfo, cwd, url, username, password } = parameters const youtubeDL = new YoutubeDL('', []) log.debug('Fetching object.', youtubeInfo) @@ -138,22 +138,29 @@ async function processVideo (parameters: { log.debug('Fetched object.', videoInfo) const originallyPublishedAt = youtubeDL.buildOriginallyPublishedAt(videoInfo) + if (options.since && originallyPublishedAt && originallyPublishedAt.getTime() < options.since.getTime()) { - log.info('Video "%s" has been published before "%s", don\'t upload it.\n', - videoInfo.title, formatDate(options.since)) + log.info('Video "%s" has been published before "%s", don\'t upload it.\n', videoInfo.title, formatDate(options.since)) return } + if (options.until && originallyPublishedAt && originallyPublishedAt.getTime() > options.until.getTime()) { - log.info('Video "%s" has been published after "%s", don\'t upload it.\n', - videoInfo.title, formatDate(options.until)) + log.info('Video "%s" has been published after "%s", don\'t upload it.\n', videoInfo.title, formatDate(options.until)) return } - const result = await advancedVideosSearch(url, { search: videoInfo.title, sort: '-match', searchTarget: 'local' }) + const server = buildServer(url) + const { data } = await server.searchCommand.advancedVideoSearch({ + search: { + search: videoInfo.title, + sort: '-match', + searchTarget: 'local' + } + }) log.info('############################################################\n') - if (result.body.data.find(v => v.name === videoInfo.title)) { + if (data.find(v => v.name === videoInfo.title)) { log.info('Video "%s" already exists, don\'t reupload it.\n', videoInfo.title) return } @@ -172,7 +179,8 @@ async function processVideo (parameters: { youtubeDL, cwd, url, - user, + username, + password, videoInfo: normalizeObject(videoInfo), videoPath: path }) @@ -187,9 +195,10 @@ async function uploadVideoOnPeerTube (parameters: { videoPath: string cwd: string url: string - user: { username: string, password: string } + username: string + password: string }) { - const { youtubeDL, videoInfo, videoPath, cwd, url, user } = parameters + const { youtubeDL, videoInfo, videoPath, cwd, url, username, password } = parameters const category = await getCategory(videoInfo.categories, url) const licence = getLicence(videoInfo.license) @@ -223,7 +232,10 @@ async function uploadVideoOnPeerTube (parameters: { tags } - const videoAttributes = await buildVideoAttributesFromCommander(url, program, defaultAttributes) + let accessToken = await getAccessTokenOrDie(url, username, password) + const server = buildServer(url, accessToken) + + const videoAttributes = await buildVideoAttributesFromCommander(server, program, defaultAttributes) Object.assign(videoAttributes, { originallyPublishedAt: originallyPublishedAt ? originallyPublishedAt.toISOString() : null, @@ -234,15 +246,13 @@ async function uploadVideoOnPeerTube (parameters: { log.info('\nUploading on PeerTube video "%s".', videoAttributes.name) - let accessToken = await getAccessTokenOrDie(url, user) - try { await uploadVideo(url, accessToken, videoAttributes) } catch (err) { if (err.message.indexOf('401') !== -1) { log.info('Got 401 Unauthorized, token may have expired, renewing token and retry.') - accessToken = await getAccessTokenOrDie(url, user) + accessToken = await getAccessTokenOrDie(url, username, password) await uploadVideo(url, accessToken, videoAttributes) } else { @@ -362,21 +372,6 @@ async function promptPassword () { }) } -async function getAccessTokenOrDie (url: string, user: UserInfo) { - const resClient = await getClient(url) - const client = { - id: resClient.body.client_id, - secret: resClient.body.client_secret - } - - try { - const res = await login(url, client, user) - return res.body.access_token - } catch (err) { - exitError('Cannot authenticate. Please check your username/password.') - } -} - function parseDate (dateAsStr: string): Date { if (!/\d{4}-\d{2}-\d{2}/.test(dateAsStr)) { exitError(`Invalid date passed: ${dateAsStr}. Expected format: YYYY-MM-DD. See help for usage.`) diff --git a/server/tools/peertube-plugins.ts b/server/tools/peertube-plugins.ts index 54ea1264d..63541bf2c 100644 --- a/server/tools/peertube-plugins.ts +++ b/server/tools/peertube-plugins.ts @@ -4,9 +4,8 @@ import { registerTSPaths } from '../helpers/register-ts-paths' registerTSPaths() import { program, Command, OptionValues } from 'commander' -import { installPlugin, listPlugins, uninstallPlugin, updatePlugin } from '../../shared/extra-utils/server/plugins' -import { getAdminTokenOrDie, getServerCredentials } from './cli' -import { PeerTubePlugin, PluginType } from '../../shared/models' +import { buildServer, getAdminTokenOrDie, getServerCredentials } from './cli' +import { PluginType } from '../../shared/models' import { isAbsolute } from 'path' import * as CliTable3 from 'cli-table3' @@ -63,28 +62,21 @@ program.parse(process.argv) async function pluginsListCLI (command: Command, options: OptionValues) { const { url, username, password } = await getServerCredentials(command) - const accessToken = await getAdminTokenOrDie(url, username, password) + const token = await getAdminTokenOrDie(url, username, password) + const server = buildServer(url, token) let pluginType: PluginType if (options.onlyThemes) pluginType = PluginType.THEME if (options.onlyPlugins) pluginType = PluginType.PLUGIN - const res = await listPlugins({ - url, - accessToken, - start: 0, - count: 100, - sort: 'name', - pluginType - }) - const plugins: PeerTubePlugin[] = res.body.data + const { data } = await server.pluginsCommand.list({ start: 0, count: 100, sort: 'name', pluginType }) const table = new CliTable3({ head: [ 'name', 'version', 'homepage' ], colWidths: [ 50, 10, 50 ] }) as any - for (const plugin of plugins) { + for (const plugin of data) { const npmName = plugin.type === PluginType.PLUGIN ? 'peertube-plugin-' + plugin.name : 'peertube-theme-' + plugin.name @@ -113,15 +105,11 @@ async function installPluginCLI (command: Command, options: OptionValues) { } const { url, username, password } = await getServerCredentials(command) - const accessToken = await getAdminTokenOrDie(url, username, password) + const token = await getAdminTokenOrDie(url, username, password) + const server = buildServer(url, token) try { - await installPlugin({ - url, - accessToken, - npmName: options.npmName, - path: options.path - }) + await server.pluginsCommand.install({ npmName: options.npmName, path: options.path }) } catch (err) { console.error('Cannot install plugin.', err) process.exit(-1) @@ -144,15 +132,11 @@ async function updatePluginCLI (command: Command, options: OptionValues) { } const { url, username, password } = await getServerCredentials(command) - const accessToken = await getAdminTokenOrDie(url, username, password) + const token = await getAdminTokenOrDie(url, username, password) + const server = buildServer(url, token) try { - await updatePlugin({ - url, - accessToken, - npmName: options.npmName, - path: options.path - }) + await server.pluginsCommand.update({ npmName: options.npmName, path: options.path }) } catch (err) { console.error('Cannot update plugin.', err) process.exit(-1) @@ -170,14 +154,11 @@ async function uninstallPluginCLI (command: Command, options: OptionValues) { } const { url, username, password } = await getServerCredentials(command) - const accessToken = await getAdminTokenOrDie(url, username, password) + const token = await getAdminTokenOrDie(url, username, password) + const server = buildServer(url, token) try { - await uninstallPlugin({ - url, - accessToken, - npmName: options.npmName - }) + await server.pluginsCommand.uninstall({ npmName: options.npmName }) } catch (err) { console.error('Cannot uninstall plugin.', err) process.exit(-1) diff --git a/server/tools/peertube-redundancy.ts b/server/tools/peertube-redundancy.ts index 4810deee0..76d633f9e 100644 --- a/server/tools/peertube-redundancy.ts +++ b/server/tools/peertube-redundancy.ts @@ -1,17 +1,14 @@ -// eslint-disable @typescript-eslint/no-unnecessary-type-assertion - import { registerTSPaths } from '../helpers/register-ts-paths' registerTSPaths() -import { program, Command } from 'commander' -import { getAdminTokenOrDie, getServerCredentials } from './cli' -import { VideoRedundanciesTarget, VideoRedundancy } from '@shared/models' -import { addVideoRedundancy, listVideoRedundancies, removeVideoRedundancy } from '@shared/extra-utils/server/redundancy' -import { HttpStatusCode } from '@shared/core-utils/miscs/http-error-codes' -import validator from 'validator' import * as CliTable3 from 'cli-table3' -import { URL } from 'url' +import { Command, program } from 'commander' import { uniq } from 'lodash' +import { URL } from 'url' +import validator from 'validator' +import { HttpStatusCode } from '@shared/core-utils/miscs/http-error-codes' +import { VideoRedundanciesTarget } from '@shared/models' +import { buildServer, getAdminTokenOrDie, getServerCredentials } from './cli' import bytes = require('bytes') @@ -63,15 +60,16 @@ program.parse(process.argv) async function listRedundanciesCLI (target: VideoRedundanciesTarget) { const { url, username, password } = await getServerCredentials(program) - const accessToken = await getAdminTokenOrDie(url, username, password) + const token = await getAdminTokenOrDie(url, username, password) + const server = buildServer(url, token) - const redundancies = await listVideoRedundanciesData(url, accessToken, target) + const { data } = await server.redundancyCommand.listVideos({ start: 0, count: 100, sort: 'name', target }) const table = new CliTable3({ head: [ 'video id', 'video name', 'video url', 'files', 'playlists', 'by instances', 'total size' ] }) as any - for (const redundancy of redundancies) { + for (const redundancy of data) { const webtorrentFiles = redundancy.redundancies.files const streamingPlaylists = redundancy.redundancies.streamingPlaylists @@ -106,7 +104,8 @@ async function listRedundanciesCLI (target: VideoRedundanciesTarget) { async function addRedundancyCLI (options: { video: number }, command: Command) { const { url, username, password } = await getServerCredentials(command) - const accessToken = await getAdminTokenOrDie(url, username, password) + const token = await getAdminTokenOrDie(url, username, password) + const server = buildServer(url, token) if (!options.video || validator.isInt('' + options.video) === false) { console.error('You need to specify the video id to duplicate and it should be a number.\n') @@ -115,11 +114,7 @@ async function addRedundancyCLI (options: { video: number }, command: Command) { } try { - await addVideoRedundancy({ - url, - accessToken, - videoId: options.video - }) + await server.redundancyCommand.addVideo({ videoId: options.video }) console.log('Video will be duplicated by your instance!') @@ -139,7 +134,8 @@ async function addRedundancyCLI (options: { video: number }, command: Command) { async function removeRedundancyCLI (options: { video: number }, command: Command) { const { url, username, password } = await getServerCredentials(command) - const accessToken = await getAdminTokenOrDie(url, username, password) + const token = await getAdminTokenOrDie(url, username, password) + const server = buildServer(url, token) if (!options.video || validator.isInt('' + options.video) === false) { console.error('You need to specify the video id to remove from your redundancies.\n') @@ -149,12 +145,12 @@ async function removeRedundancyCLI (options: { video: number }, command: Command const videoId = parseInt(options.video + '', 10) - let redundancies = await listVideoRedundanciesData(url, accessToken, 'my-videos') - let videoRedundancy = redundancies.find(r => videoId === r.id) + const myVideoRedundancies = await server.redundancyCommand.listVideos({ target: 'my-videos' }) + let videoRedundancy = myVideoRedundancies.data.find(r => videoId === r.id) if (!videoRedundancy) { - redundancies = await listVideoRedundanciesData(url, accessToken, 'remote-videos') - videoRedundancy = redundancies.find(r => videoId === r.id) + const remoteVideoRedundancies = await server.redundancyCommand.listVideos({ target: 'remote-videos' }) + videoRedundancy = remoteVideoRedundancies.data.find(r => videoId === r.id) } if (!videoRedundancy) { @@ -168,11 +164,7 @@ async function removeRedundancyCLI (options: { video: number }, command: Command .map(r => r.id) for (const id of ids) { - await removeVideoRedundancy({ - url, - accessToken, - redundancyId: id - }) + await server.redundancyCommand.removeVideo({ redundancyId: id }) } console.log('Video redundancy removed!') @@ -183,16 +175,3 @@ async function removeRedundancyCLI (options: { video: number }, command: Command process.exit(-1) } } - -async function listVideoRedundanciesData (url: string, accessToken: string, target: VideoRedundanciesTarget) { - const res = await listVideoRedundancies({ - url, - accessToken, - start: 0, - count: 100, - sort: 'name', - target - }) - - return res.body.data as VideoRedundancy[] -} diff --git a/server/tools/peertube-upload.ts b/server/tools/peertube-upload.ts index 02edbd809..d1c5348d1 100644 --- a/server/tools/peertube-upload.ts +++ b/server/tools/peertube-upload.ts @@ -6,7 +6,7 @@ import { access, constants } from 'fs-extra' import { isAbsolute } from 'path' import { getAccessToken } from '../../shared/extra-utils' import { uploadVideo } from '../../shared/extra-utils/' -import { buildCommonVideoOptions, buildVideoAttributesFromCommander, getServerCredentials } from './cli' +import { buildCommonVideoOptions, buildServer, buildVideoAttributesFromCommander, getServerCredentials } from './cli' let command = program .name('upload') @@ -46,13 +46,14 @@ getServerCredentials(command) .catch(err => console.error(err)) async function run (url: string, username: string, password: string) { - const accessToken = await getAccessToken(url, username, password) + const token = await getAccessToken(url, username, password) + const server = buildServer(url, token) await access(options.file, constants.F_OK) console.log('Uploading %s video...', options.videoName) - const videoAttributes = await buildVideoAttributesFromCommander(url, program) + const videoAttributes = await buildVideoAttributesFromCommander(server, program) Object.assign(videoAttributes, { fixture: options.file, @@ -61,7 +62,7 @@ async function run (url: string, username: string, password: string) { }) try { - await uploadVideo(url, accessToken, videoAttributes) + await uploadVideo(url, token, videoAttributes) console.log(`Video ${options.videoName} uploaded.`) process.exit(0) } catch (err) { diff --git a/server/tools/test-live.ts b/server/tools/test-live.ts new file mode 100644 index 000000000..76fd69435 --- /dev/null +++ b/server/tools/test-live.ts @@ -0,0 +1,102 @@ +import { program } from 'commander' +import { LiveVideoCreate, VideoPrivacy } from '@shared/models' +import { + flushAndRunServer, + killallServers, + sendRTMPStream, + ServerInfo, + setAccessTokensToServers, + setDefaultVideoChannel +} from '../../shared/extra-utils' +import { registerTSPaths } from '../helpers/register-ts-paths' + +registerTSPaths() + +type CommandType = 'live-mux' | 'live-transcoding' + +registerTSPaths() + +const command = program + .name('test-live') + .option('-t, --type ', 'live-muxing|live-transcoding') + .parse(process.argv) + +run() + .catch(err => { + console.error(err) + process.exit(-1) + }) + +async function run () { + const commandType: CommandType = command['type'] + if (!commandType) { + console.error('Miss command type') + process.exit(-1) + } + + console.log('Starting server.') + + const server = await flushAndRunServer(1, {}, [], { hideLogs: false, execArgv: [ '--inspect' ] }) + + const cleanup = () => { + console.log('Killing server') + killallServers([ server ]) + } + + process.on('exit', cleanup) + process.on('SIGINT', cleanup) + + await setAccessTokensToServers([ server ]) + await setDefaultVideoChannel([ server ]) + + await buildConfig(server, commandType) + + const attributes: LiveVideoCreate = { + name: 'live', + saveReplay: true, + channelId: server.videoChannel.id, + privacy: VideoPrivacy.PUBLIC + } + + console.log('Creating live.') + + const { uuid: liveVideoUUID } = await server.liveCommand.create({ fields: attributes }) + + const live = await server.liveCommand.get({ videoId: liveVideoUUID }) + + console.log('Sending RTMP stream.') + + const ffmpegCommand = sendRTMPStream(live.rtmpUrl, live.streamKey) + + ffmpegCommand.on('error', err => { + console.error(err) + process.exit(-1) + }) + + ffmpegCommand.on('end', () => { + console.log('ffmpeg ended') + process.exit(0) + }) +} + +// ---------------------------------------------------------------------------- + +async function buildConfig (server: ServerInfo, commandType: CommandType) { + await server.configCommand.updateCustomSubConfig({ + newConfig: { + instance: { + customizations: { + javascript: '', + css: '' + } + }, + live: { + enabled: true, + allowReplay: true, + transcoding: { + enabled: commandType === 'live-transcoding' + } + } + } + }) +} diff --git a/server/tools/test.ts b/server/tools/test.ts deleted file mode 100644 index fbdbae0b0..000000000 --- a/server/tools/test.ts +++ /dev/null @@ -1,105 +0,0 @@ -import { registerTSPaths } from '../helpers/register-ts-paths' -registerTSPaths() - -import { LiveVideo, LiveVideoCreate, VideoPrivacy } from '@shared/models' -import { program } from 'commander' -import { - createLive, - flushAndRunServer, - getLive, - killallServers, - sendRTMPStream, - ServerInfo, - setAccessTokensToServers, - setDefaultVideoChannel, - updateCustomSubConfig -} from '../../shared/extra-utils' - -type CommandType = 'live-mux' | 'live-transcoding' - -registerTSPaths() - -const command = program - .name('test') - .option('-t, --type ', 'live-muxing|live-transcoding') - .parse(process.argv) - -run() - .catch(err => { - console.error(err) - process.exit(-1) - }) - -async function run () { - const commandType: CommandType = command['type'] - if (!commandType) { - console.error('Miss command type') - process.exit(-1) - } - - console.log('Starting server.') - - const server = await flushAndRunServer(1, {}, [], { hideLogs: false, execArgv: [ '--inspect' ] }) - - const cleanup = () => { - console.log('Killing server') - killallServers([ server ]) - } - - process.on('exit', cleanup) - process.on('SIGINT', cleanup) - - await setAccessTokensToServers([ server ]) - await setDefaultVideoChannel([ server ]) - - await buildConfig(server, commandType) - - const attributes: LiveVideoCreate = { - name: 'live', - saveReplay: true, - channelId: server.videoChannel.id, - privacy: VideoPrivacy.PUBLIC - } - - console.log('Creating live.') - - const res = await createLive(server.url, server.accessToken, attributes) - const liveVideoUUID = res.body.video.uuid - - const resLive = await getLive(server.url, server.accessToken, liveVideoUUID) - const live: LiveVideo = resLive.body - - console.log('Sending RTMP stream.') - - const ffmpegCommand = sendRTMPStream(live.rtmpUrl, live.streamKey) - - ffmpegCommand.on('error', err => { - console.error(err) - process.exit(-1) - }) - - ffmpegCommand.on('end', () => { - console.log('ffmpeg ended') - process.exit(0) - }) -} - -// ---------------------------------------------------------------------------- - -async function buildConfig (server: ServerInfo, commandType: CommandType) { - await updateCustomSubConfig(server.url, server.accessToken, { - instance: { - customizations: { - javascript: '', - css: '' - } - }, - live: { - enabled: true, - allowReplay: true, - transcoding: { - enabled: commandType === 'live-transcoding' - } - } - }) -} diff --git a/shared/extra-utils/server/servers.ts b/shared/extra-utils/server/servers.ts index 8e80a9842..41b48a8ee 100644 --- a/shared/extra-utils/server/servers.ts +++ b/shared/extra-utils/server/servers.ts @@ -41,25 +41,25 @@ import { RedundancyCommand } from './redundancy-command' import { StatsCommand } from './stats-command' interface ServerInfo { - app: ChildProcess + app?: ChildProcess url: string - host: string - hostname: string - port: number + host?: string + hostname?: string + port?: number - rtmpPort: number + rtmpPort?: number - parallel: boolean + parallel?: boolean internalServerNumber: number - serverNumber: number + serverNumber?: number - client: { - id: string - secret: string + client?: { + id?: string + secret?: string } - user: { + user?: { username: string password: string email?: string @@ -328,43 +328,47 @@ async function runServer (server: ServerInfo, configOverrideArg?: any, args = [] } catch { /* empty */ } }) - server.bulkCommand = new BulkCommand(server) - server.cliCommand = new CLICommand(server) - server.customPageCommand = new CustomPagesCommand(server) - server.feedCommand = new FeedCommand(server) - server.logsCommand = new LogsCommand(server) - server.abusesCommand = new AbusesCommand(server) - server.overviewsCommand = new OverviewsCommand(server) - server.searchCommand = new SearchCommand(server) - server.contactFormCommand = new ContactFormCommand(server) - server.debugCommand = new DebugCommand(server) - server.followsCommand = new FollowsCommand(server) - server.jobsCommand = new JobsCommand(server) - server.pluginsCommand = new PluginsCommand(server) - server.redundancyCommand = new RedundancyCommand(server) - server.statsCommand = new StatsCommand(server) - server.configCommand = new ConfigCommand(server) - server.socketIOCommand = new SocketIOCommand(server) - server.accountsCommand = new AccountsCommand(server) - server.blocklistCommand = new BlocklistCommand(server) - server.subscriptionsCommand = new SubscriptionsCommand(server) - server.liveCommand = new LiveCommand(server) - server.servicesCommand = new ServicesCommand(server) - server.blacklistCommand = new BlacklistCommand(server) - server.captionsCommand = new CaptionsCommand(server) - server.changeOwnershipCommand = new ChangeOwnershipCommand(server) - server.playlistsCommand = new PlaylistsCommand(server) - server.historyCommand = new HistoryCommand(server) - server.importsCommand = new ImportsCommand(server) - server.streamingPlaylistsCommand = new StreamingPlaylistsCommand(server) - server.channelsCommand = new ChannelsCommand(server) - server.commentsCommand = new CommentsCommand(server) + assignCommands(server) res(server) }) }) } +function assignCommands (server: ServerInfo) { + server.bulkCommand = new BulkCommand(server) + server.cliCommand = new CLICommand(server) + server.customPageCommand = new CustomPagesCommand(server) + server.feedCommand = new FeedCommand(server) + server.logsCommand = new LogsCommand(server) + server.abusesCommand = new AbusesCommand(server) + server.overviewsCommand = new OverviewsCommand(server) + server.searchCommand = new SearchCommand(server) + server.contactFormCommand = new ContactFormCommand(server) + server.debugCommand = new DebugCommand(server) + server.followsCommand = new FollowsCommand(server) + server.jobsCommand = new JobsCommand(server) + server.pluginsCommand = new PluginsCommand(server) + server.redundancyCommand = new RedundancyCommand(server) + server.statsCommand = new StatsCommand(server) + server.configCommand = new ConfigCommand(server) + server.socketIOCommand = new SocketIOCommand(server) + server.accountsCommand = new AccountsCommand(server) + server.blocklistCommand = new BlocklistCommand(server) + server.subscriptionsCommand = new SubscriptionsCommand(server) + server.liveCommand = new LiveCommand(server) + server.servicesCommand = new ServicesCommand(server) + server.blacklistCommand = new BlacklistCommand(server) + server.captionsCommand = new CaptionsCommand(server) + server.changeOwnershipCommand = new ChangeOwnershipCommand(server) + server.playlistsCommand = new PlaylistsCommand(server) + server.historyCommand = new HistoryCommand(server) + server.importsCommand = new ImportsCommand(server) + server.streamingPlaylistsCommand = new StreamingPlaylistsCommand(server) + server.channelsCommand = new ChannelsCommand(server) + server.commentsCommand = new CommentsCommand(server) +} + async function reRunServer (server: ServerInfo, configOverride?: any) { const newServer = await runServer(server, configOverride) server.app = newServer.app @@ -475,5 +479,6 @@ export { flushAndRunServer, killallServers, reRunServer, + assignCommands, waitUntilLog } diff --git a/shared/extra-utils/users/login.ts b/shared/extra-utils/users/login.ts index 39e1a2747..c14367542 100644 --- a/shared/extra-utils/users/login.ts +++ b/shared/extra-utils/users/login.ts @@ -4,9 +4,9 @@ import { ServerInfo } from '../server/servers' import { getClient } from '../server/clients' import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' -type Client = { id: string, secret: string } +type Client = { id?: string, secret?: string } type User = { username: string, password: string } -type Server = { url: string, client: Client, user: User } +type Server = { url?: string, client?: Client, user?: User } function login (url: string, client: Client, user: User, expectedStatus = HttpStatusCode.OK_200) { const path = '/api/v1/users/token' -- cgit v1.2.3 From 9293139fde7091e9badcafa9b570b83cea9a10ad Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Fri, 9 Jul 2021 15:37:43 +0200 Subject: Introduce sql command --- scripts/benchmark.ts | 2 +- server/tests/api/activitypub/cleaner.ts | 32 ++-- server/tests/api/activitypub/fetch.ts | 12 +- server/tests/api/activitypub/refresher.ts | 16 +- server/tests/api/activitypub/security.ts | 14 +- server/tests/api/check-params/contact-form.ts | 4 +- server/tests/api/check-params/users.ts | 2 +- server/tests/api/live/live.ts | 2 +- server/tests/api/moderation/video-blacklist.ts | 2 +- .../tests/api/notifications/admin-notifications.ts | 10 +- .../tests/api/redundancy/redundancy-constraints.ts | 4 +- server/tests/api/redundancy/redundancy.ts | 4 +- server/tests/api/server/config.ts | 4 +- server/tests/api/server/handle-down.ts | 12 +- server/tests/api/server/homepage.ts | 2 +- server/tests/api/server/logs.ts | 2 +- server/tests/api/server/plugins.ts | 9 +- server/tests/api/server/tracker.ts | 6 +- server/tests/api/users/users.ts | 13 +- server/tests/api/videos/video-channels.ts | 5 +- server/tests/api/videos/videos-history.ts | 4 +- server/tests/api/videos/videos-views-cleaner.ts | 20 +-- server/tests/cli/plugins.ts | 4 +- server/tests/cli/prune-storage.ts | 2 +- server/tests/cli/update-host.ts | 2 +- server/tests/external-plugins/auto-block-videos.ts | 2 +- server/tests/external-plugins/auto-mute.ts | 2 +- server/tests/plugins/action-hooks.ts | 2 +- server/tools/test-live.ts | 2 +- shared/extra-utils/miscs/index.ts | 2 +- shared/extra-utils/miscs/sql-command.ts | 142 ++++++++++++++++++ shared/extra-utils/miscs/sql.ts | 161 --------------------- shared/extra-utils/miscs/stubs.ts | 7 - shared/extra-utils/server/servers.ts | 10 +- shared/extra-utils/shared/abstract-command.ts | 2 +- 35 files changed, 229 insertions(+), 292 deletions(-) create mode 100644 shared/extra-utils/miscs/sql-command.ts delete mode 100644 shared/extra-utils/miscs/sql.ts diff --git a/scripts/benchmark.ts b/scripts/benchmark.ts index 321b07c94..272f9e8b1 100644 --- a/scripts/benchmark.ts +++ b/scripts/benchmark.ts @@ -15,7 +15,7 @@ const outfile = process.argv[2] run() .catch(err => console.error(err)) .finally(() => { - if (server) killallServers([ server ]) + if (server) return killallServers([ server ]) }) function buildAuthorizationHeader () { diff --git a/server/tests/api/activitypub/cleaner.ts b/server/tests/api/activitypub/cleaner.ts index 27f17b4d6..5b08880bf 100644 --- a/server/tests/api/activitypub/cleaner.ts +++ b/server/tests/api/activitypub/cleaner.ts @@ -4,18 +4,12 @@ import 'mocha' import * as chai from 'chai' import { cleanupTests, - closeAllSequelize, - deleteAll, doubleFollow, flushAndRunMultipleServers, - getCount, getVideo, rateVideo, - selectQuery, ServerInfo, setAccessTokensToServers, - setVideoField, - updateQuery, uploadVideoAndGetId, wait, waitJobs @@ -86,9 +80,9 @@ describe('Test AP cleaner', function () { it('Should destroy server 3 internal likes and correctly clean them', async function () { this.timeout(20000) - await deleteAll(servers[2].internalServerNumber, 'accountVideoRate') + await servers[2].sqlCommand.deleteAll('accountVideoRate') for (const uuid of videoUUIDs) { - await setVideoField(servers[2].internalServerNumber, uuid, 'likes', '0') + await servers[2].sqlCommand.setVideoField(uuid, 'likes', '0') } await wait(5000) @@ -132,10 +126,10 @@ describe('Test AP cleaner', function () { it('Should destroy server 3 internal dislikes and correctly clean them', async function () { this.timeout(20000) - await deleteAll(servers[2].internalServerNumber, 'accountVideoRate') + await servers[2].sqlCommand.deleteAll('accountVideoRate') for (const uuid of videoUUIDs) { - await setVideoField(servers[2].internalServerNumber, uuid, 'dislikes', '0') + await servers[2].sqlCommand.setVideoField(uuid, 'dislikes', '0') } await wait(5000) @@ -159,15 +153,15 @@ describe('Test AP cleaner', function () { it('Should destroy server 3 internal shares and correctly clean them', async function () { this.timeout(20000) - const preCount = await getCount(servers[0].internalServerNumber, 'videoShare') + const preCount = await servers[0].sqlCommand.getCount('videoShare') expect(preCount).to.equal(6) - await deleteAll(servers[2].internalServerNumber, 'videoShare') + await servers[2].sqlCommand.deleteAll('videoShare') await wait(5000) await waitJobs(servers) // Still 6 because we don't have remote shares on local videos - const postCount = await getCount(servers[0].internalServerNumber, 'videoShare') + const postCount = await servers[0].sqlCommand.getCount('videoShare') expect(postCount).to.equal(6) }) @@ -179,7 +173,7 @@ describe('Test AP cleaner', function () { expect(total).to.equal(3) } - await deleteAll(servers[2].internalServerNumber, 'videoComment') + await servers[2].sqlCommand.deleteAll('videoComment') await wait(5000) await waitJobs(servers) @@ -196,7 +190,7 @@ describe('Test AP cleaner', function () { async function check (like: string, ofServerUrl: string, urlSuffix: string, remote: 'true' | 'false') { const query = `SELECT "videoId", "accountVideoRate".url FROM "accountVideoRate" ` + `INNER JOIN video ON "accountVideoRate"."videoId" = video.id AND remote IS ${remote} WHERE "accountVideoRate"."url" LIKE '${like}'` - const res = await selectQuery(servers[0].internalServerNumber, query) + const res = await servers[0].sqlCommand.selectQuery(query) for (const rate of res) { const matcher = new RegExp(`^${ofServerUrl}/accounts/root/dislikes/\\d+${urlSuffix}$`) @@ -225,7 +219,7 @@ describe('Test AP cleaner', function () { { const query = `UPDATE "accountVideoRate" SET url = url || 'stan'` - await updateQuery(servers[1].internalServerNumber, query) + await servers[1].sqlCommand.updateQuery(query) await wait(5000) await waitJobs(servers) @@ -242,7 +236,7 @@ describe('Test AP cleaner', function () { const query = `SELECT "videoId", "videoComment".url, uuid as "videoUUID" FROM "videoComment" ` + `INNER JOIN video ON "videoComment"."videoId" = video.id AND remote IS ${remote} WHERE "videoComment"."url" LIKE '${like}'` - const res = await selectQuery(servers[0].internalServerNumber, query) + const res = await servers[0].sqlCommand.selectQuery(query) for (const comment of res) { const matcher = new RegExp(`${ofServerUrl}/videos/watch/${comment.videoUUID}/comments/\\d+${urlSuffix}`) @@ -268,7 +262,7 @@ describe('Test AP cleaner', function () { { const query = `UPDATE "videoComment" SET url = url || 'kyle'` - await updateQuery(servers[1].internalServerNumber, query) + await servers[1].sqlCommand.updateQuery(query) await wait(5000) await waitJobs(servers) @@ -280,7 +274,5 @@ describe('Test AP cleaner', function () { after(async function () { await cleanupTests(servers) - - await closeAllSequelize(servers) }) }) diff --git a/server/tests/api/activitypub/fetch.ts b/server/tests/api/activitypub/fetch.ts index 35fd94eed..d5e21404c 100644 --- a/server/tests/api/activitypub/fetch.ts +++ b/server/tests/api/activitypub/fetch.ts @@ -1,23 +1,19 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ import 'mocha' - +import * as chai from 'chai' import { cleanupTests, - closeAllSequelize, createUser, doubleFollow, flushAndRunMultipleServers, getVideosListSort, ServerInfo, setAccessTokensToServers, - setActorField, - setVideoField, uploadVideo, userLogin, waitJobs } from '../../../../shared/extra-utils' -import * as chai from 'chai' import { Video } from '../../../../shared/models/videos' const expect = chai.expect @@ -50,12 +46,12 @@ describe('Test ActivityPub fetcher', function () { { const to = 'http://localhost:' + servers[0].port + '/accounts/user1' const value = 'http://localhost:' + servers[1].port + '/accounts/user1' - await setActorField(servers[0].internalServerNumber, to, 'url', value) + await servers[0].sqlCommand.setActorField(to, 'url', value) } { const value = 'http://localhost:' + servers[2].port + '/videos/watch/' + badVideoUUID - await setVideoField(servers[0].internalServerNumber, badVideoUUID, 'url', value) + await servers[0].sqlCommand.setVideoField(badVideoUUID, 'url', value) } }) @@ -88,7 +84,5 @@ describe('Test ActivityPub fetcher', function () { this.timeout(20000) await cleanupTests(servers) - - await closeAllSequelize(servers) }) }) diff --git a/server/tests/api/activitypub/refresher.ts b/server/tests/api/activitypub/refresher.ts index f295dfab7..af919f2f3 100644 --- a/server/tests/api/activitypub/refresher.ts +++ b/server/tests/api/activitypub/refresher.ts @@ -4,7 +4,6 @@ import 'mocha' import { HttpStatusCode } from '@shared/core-utils' import { cleanupTests, - closeAllSequelize, doubleFollow, flushAndRunMultipleServers, generateUserAccessToken, @@ -13,10 +12,7 @@ import { reRunServer, ServerInfo, setAccessTokensToServers, - setActorField, setDefaultVideoChannel, - setPlaylistField, - setVideoField, uploadVideo, uploadVideoAndGetId, wait, @@ -78,7 +74,7 @@ describe('Test AP refresher', function () { await wait(10000) // Change UUID so the remote server returns a 404 - await setVideoField(servers[1].internalServerNumber, videoUUID1, 'uuid', '304afe4f-39f9-4d49-8ed7-ac57b86b174f') + await servers[1].sqlCommand.setVideoField(videoUUID1, 'uuid', '304afe4f-39f9-4d49-8ed7-ac57b86b174f') await getVideo(servers[0].url, videoUUID1) await getVideo(servers[0].url, videoUUID2) @@ -92,9 +88,9 @@ describe('Test AP refresher', function () { it('Should not update a remote video if the remote instance is down', async function () { this.timeout(70000) - killallServers([ servers[1] ]) + await killallServers([ servers[1] ]) - await setVideoField(servers[1].internalServerNumber, videoUUID3, 'uuid', '304afe4f-39f9-4d49-8ed7-ac57b86b174e') + await servers[1].sqlCommand.setVideoField(videoUUID3, 'uuid', '304afe4f-39f9-4d49-8ed7-ac57b86b174e') // Video will need a refresh await wait(10000) @@ -120,7 +116,7 @@ describe('Test AP refresher', function () { // Change actor name so the remote server returns a 404 const to = 'http://localhost:' + servers[1].port + '/accounts/user2' - await setActorField(servers[1].internalServerNumber, to, 'preferredUsername', 'toto') + await servers[1].sqlCommand.setActorField(to, 'preferredUsername', 'toto') await command.get({ accountName: 'user1@localhost:' + servers[1].port }) await command.get({ accountName: 'user2@localhost:' + servers[1].port }) @@ -140,7 +136,7 @@ describe('Test AP refresher', function () { await wait(10000) // Change UUID so the remote server returns a 404 - await setPlaylistField(servers[1].internalServerNumber, playlistUUID2, 'uuid', '304afe4f-39f9-4d49-8ed7-ac57b86b178e') + await servers[1].sqlCommand.setPlaylistField(playlistUUID2, 'uuid', '304afe4f-39f9-4d49-8ed7-ac57b86b178e') await servers[0].playlistsCommand.get({ playlistId: playlistUUID1 }) await servers[0].playlistsCommand.get({ playlistId: playlistUUID2 }) @@ -156,7 +152,5 @@ describe('Test AP refresher', function () { this.timeout(10000) await cleanupTests(servers) - - await closeAllSequelize(servers) }) }) diff --git a/server/tests/api/activitypub/security.ts b/server/tests/api/activitypub/security.ts index 61db272f6..c32940070 100644 --- a/server/tests/api/activitypub/security.ts +++ b/server/tests/api/activitypub/security.ts @@ -7,12 +7,10 @@ import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-c import { buildAbsoluteFixturePath, cleanupTests, - closeAllSequelize, flushAndRunMultipleServers, killallServers, reRunServer, ServerInfo, - setActorField, wait } from '../../../../shared/extra-utils' import { makeFollowRequest, makePOSTAPRequest } from '../../../../shared/extra-utils/requests/activitypub' @@ -26,8 +24,8 @@ function setKeysOfServer (onServer: ServerInfo, ofServer: ServerInfo, publicKey: const url = 'http://localhost:' + ofServer.port + '/accounts/peertube' return Promise.all([ - setActorField(onServer.internalServerNumber, url, 'publicKey', publicKey), - setActorField(onServer.internalServerNumber, url, 'privateKey', privateKey) + onServer.sqlCommand.setActorField(url, 'publicKey', publicKey), + onServer.sqlCommand.setActorField(url, 'privateKey', privateKey) ]) } @@ -35,8 +33,8 @@ function setUpdatedAtOfServer (onServer: ServerInfo, ofServer: ServerInfo, updat const url = 'http://localhost:' + ofServer.port + '/accounts/peertube' return Promise.all([ - setActorField(onServer.internalServerNumber, url, 'createdAt', updatedAt), - setActorField(onServer.internalServerNumber, url, 'updatedAt', updatedAt) + onServer.sqlCommand.setActorField(url, 'createdAt', updatedAt), + onServer.sqlCommand.setActorField(url, 'updatedAt', updatedAt) ]) } @@ -173,7 +171,7 @@ describe('Test ActivityPub security', function () { await setUpdatedAtOfServer(servers[0], servers[1], '2015-07-17 22:00:00+00') // Invalid peertube actor cache - killallServers([ servers[1] ]) + await killallServers([ servers[1] ]) await reRunServer(servers[1]) const body = activityPubContextify(getAnnounceWithoutContext(servers[1])) @@ -294,7 +292,5 @@ describe('Test ActivityPub security', function () { this.timeout(10000) await cleanupTests(servers) - - await closeAllSequelize(servers) }) }) diff --git a/server/tests/api/check-params/contact-form.ts b/server/tests/api/check-params/contact-form.ts index fb30766d9..5539266b8 100644 --- a/server/tests/api/check-params/contact-form.ts +++ b/server/tests/api/check-params/contact-form.ts @@ -36,7 +36,7 @@ describe('Test contact form API validators', function () { it('Should not accept a contact form if it is disabled in the configuration', async function () { this.timeout(10000) - killallServers([ server ]) + await killallServers([ server ]) // Contact form is disabled await reRunServer(server, { smtp: { hostname: 'localhost', port: emailPort }, contact_form: { enabled: false } }) @@ -46,7 +46,7 @@ describe('Test contact form API validators', function () { it('Should not accept a contact form if from email is invalid', async function () { this.timeout(10000) - killallServers([ server ]) + await killallServers([ server ]) // Email & contact form enabled await reRunServer(server, { smtp: { hostname: 'localhost', port: emailPort } }) diff --git a/server/tests/api/check-params/users.ts b/server/tests/api/check-params/users.ts index 88fc8e8b1..bffe29bce 100644 --- a/server/tests/api/check-params/users.ts +++ b/server/tests/api/check-params/users.ts @@ -237,7 +237,7 @@ describe('Test users API validators', function () { it('Should succeed with no password on a server with smtp enabled', async function () { this.timeout(20000) - killallServers([ server ]) + await killallServers([ server ]) const config = immutableAssign(overrideConfig, { smtp: { diff --git a/server/tests/api/live/live.ts b/server/tests/api/live/live.ts index 0b06df44c..f9a162df6 100644 --- a/server/tests/api/live/live.ts +++ b/server/tests/api/live/live.ts @@ -587,7 +587,7 @@ describe('Test live', function () { await commands[0].waitUntilSegmentGeneration({ videoUUID: liveVideoId, resolution: 0, segment: 2 }) await commands[0].waitUntilSegmentGeneration({ videoUUID: liveVideoReplayId, resolution: 0, segment: 2 }) - killallServers([ servers[0] ]) + await killallServers([ servers[0] ]) await reRunServer(servers[0]) await wait(5000) diff --git a/server/tests/api/moderation/video-blacklist.ts b/server/tests/api/moderation/video-blacklist.ts index c72ebc16b..8b4723a2b 100644 --- a/server/tests/api/moderation/video-blacklist.ts +++ b/server/tests/api/moderation/video-blacklist.ts @@ -342,7 +342,7 @@ describe('Test video blacklist', function () { before(async function () { this.timeout(20000) - killallServers([ servers[0] ]) + await killallServers([ servers[0] ]) const config = { auto_blacklist: { diff --git a/server/tests/api/notifications/admin-notifications.ts b/server/tests/api/notifications/admin-notifications.ts index da9767b74..03fbe0b70 100644 --- a/server/tests/api/notifications/admin-notifications.ts +++ b/server/tests/api/notifications/admin-notifications.ts @@ -11,8 +11,6 @@ import { MockSmtpServer, prepareNotificationsTest, ServerInfo, - setPluginLatestVersion, - setPluginVersion, wait } from '@shared/extra-utils' import { PluginType, UserNotification, UserNotificationType } from '@shared/models' @@ -120,8 +118,8 @@ describe('Test admin notifications', function () { it('Should send a notification to admins on new plugin version', async function () { this.timeout(30000) - await setPluginVersion(server.internalServerNumber, 'hello-world', '0.0.1') - await setPluginLatestVersion(server.internalServerNumber, 'hello-world', '0.0.1') + await server.sqlCommand.setPluginVersion('hello-world', '0.0.1') + await server.sqlCommand.setPluginLatestVersion('hello-world', '0.0.1') await wait(6000) await checkNewPluginVersion(baseParams, PluginType.PLUGIN, 'hello-world', 'presence') @@ -142,8 +140,8 @@ describe('Test admin notifications', function () { it('Should send a new notification after a new plugin release', async function () { this.timeout(30000) - await setPluginVersion(server.internalServerNumber, 'hello-world', '0.0.1') - await setPluginLatestVersion(server.internalServerNumber, 'hello-world', '0.0.1') + await server.sqlCommand.setPluginVersion('hello-world', '0.0.1') + await server.sqlCommand.setPluginLatestVersion('hello-world', '0.0.1') await wait(6000) expect(adminNotifications.filter(n => n.type === UserNotificationType.NEW_PEERTUBE_VERSION)).to.have.lengthOf(2) diff --git a/server/tests/api/redundancy/redundancy-constraints.ts b/server/tests/api/redundancy/redundancy-constraints.ts index 500b96747..82d952471 100644 --- a/server/tests/api/redundancy/redundancy-constraints.ts +++ b/server/tests/api/redundancy/redundancy-constraints.ts @@ -121,7 +121,7 @@ describe('Test redundancy constraints', function () { } } } - await killallServers([ localServer ]) + await await killallServers([ localServer ]) await reRunServer(localServer, config) await uploadWrapper('video 2 server 2') @@ -150,7 +150,7 @@ describe('Test redundancy constraints', function () { } } } - killallServers([ localServer ]) + await killallServers([ localServer ]) await reRunServer(localServer, config) await uploadWrapper('video 3 server 2') diff --git a/server/tests/api/redundancy/redundancy.ts b/server/tests/api/redundancy/redundancy.ts index d20cb80f1..56a2af395 100644 --- a/server/tests/api/redundancy/redundancy.ts +++ b/server/tests/api/redundancy/redundancy.ts @@ -634,7 +634,7 @@ describe('Test videos redundancy', function () { it('Should stop server 1 and expire video redundancy', async function () { this.timeout(80000) - killallServers([ servers[0] ]) + await killallServers([ servers[0] ]) await wait(15000) @@ -703,7 +703,7 @@ describe('Test videos redundancy', function () { await waitJobs(servers) - killallServers([ servers[0] ]) + await killallServers([ servers[0] ]) await reRunServer(servers[0], { redundancy: { videos: { diff --git a/server/tests/api/server/config.ts b/server/tests/api/server/config.ts index 037628c9d..55cf2a1b8 100644 --- a/server/tests/api/server/config.ts +++ b/server/tests/api/server/config.ts @@ -456,7 +456,7 @@ describe('Test config', function () { it('Should have the configuration updated after a restart', async function () { this.timeout(10000) - killallServers([ server ]) + await killallServers([ server ]) await reRunServer(server) @@ -507,7 +507,7 @@ describe('Test config', function () { expect(res.headers['x-frame-options']).to.exist } - killallServers([ server ]) + await killallServers([ server ]) const config = { security: { diff --git a/server/tests/api/server/handle-down.ts b/server/tests/api/server/handle-down.ts index 94496a159..dd06acb5e 100644 --- a/server/tests/api/server/handle-down.ts +++ b/server/tests/api/server/handle-down.ts @@ -5,7 +5,6 @@ import * as chai from 'chai' import { HttpStatusCode } from '@shared/core-utils' import { cleanupTests, - closeAllSequelize, CommentsCommand, completeVideoCheck, flushAndRunMultipleServers, @@ -16,7 +15,6 @@ import { reRunServer, ServerInfo, setAccessTokensToServers, - setActorFollowScores, updateVideo, uploadVideo, uploadVideoAndGetId, @@ -129,7 +127,7 @@ describe('Test handle downs', function () { } // Kill server 2 - killallServers([ servers[1] ]) + await killallServers([ servers[1] ]) // Remove server 2 follower for (let i = 0; i < 10; i++) { @@ -139,7 +137,7 @@ describe('Test handle downs', function () { await waitJobs([ servers[0], servers[2] ]) // Kill server 3 - killallServers([ servers[2] ]) + await killallServers([ servers[2] ]) const resLastVideo1 = await uploadVideo(servers[0].url, servers[0].accessToken, videoAttributes) missedVideo1 = resLastVideo1.body.video @@ -311,7 +309,7 @@ describe('Test handle downs', function () { } await waitJobs(servers) - await setActorFollowScores(servers[1].internalServerNumber, 20) + await servers[1].sqlCommand.setActorFollowScores(20) // Wait video expiration await wait(11000) @@ -325,7 +323,7 @@ describe('Test handle downs', function () { it('Should remove followings that are down', async function () { this.timeout(120000) - killallServers([ servers[0] ]) + await killallServers([ servers[0] ]) // Wait video expiration await wait(11000) @@ -344,8 +342,6 @@ describe('Test handle downs', function () { }) after(async function () { - await closeAllSequelize([ servers[1] ]) - await cleanupTests(servers) }) }) diff --git a/server/tests/api/server/homepage.ts b/server/tests/api/server/homepage.ts index c08067f3c..18b9edc31 100644 --- a/server/tests/api/server/homepage.ts +++ b/server/tests/api/server/homepage.ts @@ -54,7 +54,7 @@ describe('Test instance homepage actions', function () { it('Should have the same homepage after a restart', async function () { this.timeout(30000) - killallServers([ server ]) + await killallServers([ server ]) await reRunServer(server) diff --git a/server/tests/api/server/logs.ts b/server/tests/api/server/logs.ts index ab83a329f..365f6cc2b 100644 --- a/server/tests/api/server/logs.ts +++ b/server/tests/api/server/logs.ts @@ -113,7 +113,7 @@ describe('Test logs', function () { it('Should not log ping requests', async function () { this.timeout(30000) - killallServers([ server ]) + await killallServers([ server ]) await reRunServer(server, { log: { log_ping_requests: false } }) diff --git a/server/tests/api/server/plugins.ts b/server/tests/api/server/plugins.ts index e22ecfad9..655cf00fa 100644 --- a/server/tests/api/server/plugins.ts +++ b/server/tests/api/server/plugins.ts @@ -5,7 +5,6 @@ import * as chai from 'chai' import { HttpStatusCode } from '@shared/core-utils' import { cleanupTests, - closeAllSequelize, flushAndRunServer, getMyUserInformation, killallServers, @@ -13,7 +12,6 @@ import { reRunServer, ServerInfo, setAccessTokensToServers, - setPluginVersion, testHelloWorldRegisteredSettings, updateMyUser, wait, @@ -244,7 +242,7 @@ describe('Test plugins', function () { await wait(6000) // Fake update our plugin version - await setPluginVersion(server.internalServerNumber, 'hello-world', '0.0.1') + await server.sqlCommand.setPluginVersion('hello-world', '0.0.1') // Fake update package.json const packageJSON = await command.getPackageJSON('peertube-plugin-hello-world') @@ -254,7 +252,7 @@ describe('Test plugins', function () { await command.updatePackageJSON('peertube-plugin-hello-world', packageJSON) // Restart the server to take into account this change - killallServers([ server ]) + await killallServers([ server ]) await reRunServer(server) { @@ -335,14 +333,13 @@ describe('Test plugins', function () { await check() - killallServers([ server ]) + await killallServers([ server ]) await reRunServer(server) await check() }) after(async function () { - await closeAllSequelize([ server ]) await cleanupTests([ server ]) }) }) diff --git a/server/tests/api/server/tracker.ts b/server/tests/api/server/tracker.ts index 4b86e0b90..868dc8977 100644 --- a/server/tests/api/server/tracker.ts +++ b/server/tests/api/server/tracker.ts @@ -61,8 +61,7 @@ describe('Test tracker', function () { const errCb = () => done(new Error('Tracker is enabled')) killallServers([ server ]) - - reRunServer(server, { tracker: { enabled: false } }) + .then(() => reRunServer(server, { tracker: { enabled: false } })) .then(() => { const webtorrent = new WebTorrent() @@ -86,8 +85,7 @@ describe('Test tracker', function () { this.timeout(20000) killallServers([ server ]) - - reRunServer(server) + .then(() => reRunServer(server)) .then(() => { const webtorrent = new WebTorrent() diff --git a/server/tests/api/users/users.ts b/server/tests/api/users/users.ts index 4d255f340..69a8dba34 100644 --- a/server/tests/api/users/users.ts +++ b/server/tests/api/users/users.ts @@ -6,7 +6,6 @@ import { HttpStatusCode } from '@shared/core-utils' import { blockUser, cleanupTests, - closeAllSequelize, createUser, deleteMe, flushAndRunServer, @@ -30,7 +29,6 @@ import { reRunServer, ServerInfo, setAccessTokensToServers, - setTokenField, testImage, unblockUser, updateMyAvatar, @@ -264,10 +262,10 @@ describe('Test users', function () { it('Should have an expired access token', async function () { this.timeout(15000) - await setTokenField(server.internalServerNumber, server.accessToken, 'accessTokenExpiresAt', new Date().toISOString()) - await setTokenField(server.internalServerNumber, server.accessToken, 'refreshTokenExpiresAt', new Date().toISOString()) + await server.sqlCommand.setTokenField(server.accessToken, 'accessTokenExpiresAt', new Date().toISOString()) + await server.sqlCommand.setTokenField(server.accessToken, 'refreshTokenExpiresAt', new Date().toISOString()) - killallServers([ server ]) + await killallServers([ server ]) await reRunServer(server) await getMyUserInformation(server.url, server.accessToken, 401) @@ -281,9 +279,9 @@ describe('Test users', function () { this.timeout(15000) const futureDate = new Date(new Date().getTime() + 1000 * 60).toISOString() - await setTokenField(server.internalServerNumber, server.accessToken, 'refreshTokenExpiresAt', futureDate) + await server.sqlCommand.setTokenField(server.accessToken, 'refreshTokenExpiresAt', futureDate) - killallServers([ server ]) + await killallServers([ server ]) await reRunServer(server) const res = await refreshToken(server, server.refreshToken) @@ -1013,7 +1011,6 @@ describe('Test users', function () { }) after(async function () { - await closeAllSequelize([ server ]) await cleanupTests([ server ]) }) }) diff --git a/server/tests/api/videos/video-channels.ts b/server/tests/api/videos/video-channels.ts index daf066eb1..e441ebbd4 100644 --- a/server/tests/api/videos/video-channels.ts +++ b/server/tests/api/videos/video-channels.ts @@ -9,7 +9,6 @@ import { createUser, doubleFollow, flushAndRunMultipleServers, - getActorImage, getVideo, getVideoChannelVideos, setDefaultVideoChannel, @@ -268,7 +267,7 @@ describe('Test video channels', function () { await testImage(server.url, 'avatar-resized', avatarPaths[server.port], '.png') await testFileExistsOrNot(server, 'avatars', basename(avatarPaths[server.port]), true) - const row = await getActorImage(server.internalServerNumber, basename(avatarPaths[server.port])) + const row = await server.sqlCommand.getActorImage(basename(avatarPaths[server.port])) expect(row.height).to.equal(ACTOR_IMAGES_SIZE.AVATARS.height) expect(row.width).to.equal(ACTOR_IMAGES_SIZE.AVATARS.width) } @@ -294,7 +293,7 @@ describe('Test video channels', function () { await testImage(server.url, 'banner-resized', bannerPaths[server.port]) await testFileExistsOrNot(server, 'avatars', basename(bannerPaths[server.port]), true) - const row = await getActorImage(server.internalServerNumber, basename(bannerPaths[server.port])) + const row = await server.sqlCommand.getActorImage(basename(bannerPaths[server.port])) expect(row.height).to.equal(ACTOR_IMAGES_SIZE.BANNERS.height) expect(row.width).to.equal(ACTOR_IMAGES_SIZE.BANNERS.width) } diff --git a/server/tests/api/videos/videos-history.ts b/server/tests/api/videos/videos-history.ts index 731447135..9a7635c35 100644 --- a/server/tests/api/videos/videos-history.ts +++ b/server/tests/api/videos/videos-history.ts @@ -204,7 +204,7 @@ describe('Test videos history', function () { it('Should not clean old history', async function () { this.timeout(50000) - killallServers([ server ]) + await killallServers([ server ]) await reRunServer(server, { history: { videos: { max_age: '10 days' } } }) @@ -219,7 +219,7 @@ describe('Test videos history', function () { it('Should clean old history', async function () { this.timeout(50000) - killallServers([ server ]) + await killallServers([ server ]) await reRunServer(server, { history: { videos: { max_age: '5 seconds' } } }) diff --git a/server/tests/api/videos/videos-views-cleaner.ts b/server/tests/api/videos/videos-views-cleaner.ts index b89f33217..b6cde6b50 100644 --- a/server/tests/api/videos/videos-views-cleaner.ts +++ b/server/tests/api/videos/videos-views-cleaner.ts @@ -1,11 +1,9 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ -import * as chai from 'chai' import 'mocha' +import * as chai from 'chai' import { cleanupTests, - closeAllSequelize, - countVideoViewsOf, doubleFollow, flushAndRunMultipleServers, killallServers, @@ -50,7 +48,7 @@ describe('Test video views cleaner', function () { it('Should not clean old video views', async function () { this.timeout(50000) - killallServers([ servers[0] ]) + await killallServers([ servers[0] ]) await reRunServer(servers[0], { views: { videos: { remote: { max_age: '10 days' } } } }) @@ -60,14 +58,14 @@ describe('Test video views cleaner', function () { { for (const server of servers) { - const total = await countVideoViewsOf(server.internalServerNumber, videoIdServer1) + const total = await server.sqlCommand.countVideoViewsOf(videoIdServer1) expect(total).to.equal(2, 'Server ' + server.serverNumber + ' does not have the correct amount of views') } } { for (const server of servers) { - const total = await countVideoViewsOf(server.internalServerNumber, videoIdServer2) + const total = await server.sqlCommand.countVideoViewsOf(videoIdServer2) expect(total).to.equal(2, 'Server ' + server.serverNumber + ' does not have the correct amount of views') } } @@ -76,7 +74,7 @@ describe('Test video views cleaner', function () { it('Should clean old video views', async function () { this.timeout(50000) - killallServers([ servers[0] ]) + await killallServers([ servers[0] ]) await reRunServer(servers[0], { views: { videos: { remote: { max_age: '5 seconds' } } } }) @@ -86,23 +84,21 @@ describe('Test video views cleaner', function () { { for (const server of servers) { - const total = await countVideoViewsOf(server.internalServerNumber, videoIdServer1) + const total = await server.sqlCommand.countVideoViewsOf(videoIdServer1) expect(total).to.equal(2) } } { - const totalServer1 = await countVideoViewsOf(servers[0].internalServerNumber, videoIdServer2) + const totalServer1 = await servers[0].sqlCommand.countVideoViewsOf(videoIdServer2) expect(totalServer1).to.equal(0) - const totalServer2 = await countVideoViewsOf(servers[1].internalServerNumber, videoIdServer2) + const totalServer2 = await servers[1].sqlCommand.countVideoViewsOf(videoIdServer2) expect(totalServer2).to.equal(2) } }) after(async function () { - await closeAllSequelize(servers) - await cleanupTests(servers) }) }) diff --git a/server/tests/cli/plugins.ts b/server/tests/cli/plugins.ts index e5efae36b..5344bfc96 100644 --- a/server/tests/cli/plugins.ts +++ b/server/tests/cli/plugins.ts @@ -39,7 +39,7 @@ describe('Test plugin scripts', function () { it('Should have the theme and the plugin registered when we restart peertube', async function () { this.timeout(30000) - killallServers([ server ]) + await killallServers([ server ]) await reRunServer(server) const config = await server.configCommand.getConfig() @@ -62,7 +62,7 @@ describe('Test plugin scripts', function () { it('Should have removed the plugin on another peertube restart', async function () { this.timeout(30000) - killallServers([ server ]) + await killallServers([ server ]) await reRunServer(server) const config = await server.configCommand.getConfig() diff --git a/server/tests/cli/prune-storage.ts b/server/tests/cli/prune-storage.ts index fa1df65a9..d4dbee682 100644 --- a/server/tests/cli/prune-storage.ts +++ b/server/tests/cli/prune-storage.ts @@ -110,7 +110,7 @@ describe('Test prune storage scripts', function () { await wait(1000) await waitJobs(servers) - killallServers(servers) + await killallServers(servers) await wait(1000) }) diff --git a/server/tests/cli/update-host.ts b/server/tests/cli/update-host.ts index d3a1520cf..e986a04f2 100644 --- a/server/tests/cli/update-host.ts +++ b/server/tests/cli/update-host.ts @@ -61,7 +61,7 @@ describe('Test update host scripts', function () { it('Should run update host', async function () { this.timeout(30000) - killallServers([ server ]) + await killallServers([ server ]) // Run server with standard configuration await reRunServer(server) diff --git a/server/tests/external-plugins/auto-block-videos.ts b/server/tests/external-plugins/auto-block-videos.ts index 6659b6f39..f4b55522a 100644 --- a/server/tests/external-plugins/auto-block-videos.ts +++ b/server/tests/external-plugins/auto-block-videos.ts @@ -164,7 +164,7 @@ describe('Official plugin auto-block videos', function () { await check(servers[0], video.uuid, true) - killallServers([ servers[0] ]) + await killallServers([ servers[0] ]) await reRunServer(servers[0]) await wait(2000) diff --git a/server/tests/external-plugins/auto-mute.ts b/server/tests/external-plugins/auto-mute.ts index f86c83808..844023b83 100644 --- a/server/tests/external-plugins/auto-mute.ts +++ b/server/tests/external-plugins/auto-mute.ts @@ -151,7 +151,7 @@ describe('Official plugin auto-mute', function () { expect(res.body.total).to.equal(2) } - killallServers([ servers[0] ]) + await killallServers([ servers[0] ]) await reRunServer(servers[0]) await wait(2000) diff --git a/server/tests/plugins/action-hooks.ts b/server/tests/plugins/action-hooks.ts index 6975ca4bb..bcf773854 100644 --- a/server/tests/plugins/action-hooks.ts +++ b/server/tests/plugins/action-hooks.ts @@ -44,7 +44,7 @@ describe('Test plugin action hooks', function () { await servers[0].pluginsCommand.install({ path: PluginsCommand.getPluginTestPath() }) - killallServers([ servers[0] ]) + await killallServers([ servers[0] ]) await reRunServer(servers[0], { live: { diff --git a/server/tools/test-live.ts b/server/tools/test-live.ts index 76fd69435..3c6a67cf7 100644 --- a/server/tools/test-live.ts +++ b/server/tools/test-live.ts @@ -40,7 +40,7 @@ async function run () { const cleanup = () => { console.log('Killing server') - killallServers([ server ]) + await killallServers([ server ]) } process.on('exit', cleanup) diff --git a/shared/extra-utils/miscs/index.ts b/shared/extra-utils/miscs/index.ts index ccacd4c79..7e236c329 100644 --- a/shared/extra-utils/miscs/index.ts +++ b/shared/extra-utils/miscs/index.ts @@ -1,3 +1,3 @@ export * from './miscs' -export * from './sql' +export * from './sql-command' export * from './stubs' diff --git a/shared/extra-utils/miscs/sql-command.ts b/shared/extra-utils/miscs/sql-command.ts new file mode 100644 index 000000000..2a3e9e607 --- /dev/null +++ b/shared/extra-utils/miscs/sql-command.ts @@ -0,0 +1,142 @@ +import { QueryTypes, Sequelize } from 'sequelize' +import { AbstractCommand } from '../shared' + +export class SQLCommand extends AbstractCommand { + private sequelize: Sequelize + + deleteAll (table: string) { + const seq = this.getSequelize() + + const options = { type: QueryTypes.DELETE } + + return seq.query(`DELETE FROM "${table}"`, options) + } + + async getCount (table: string) { + const seq = this.getSequelize() + + const options = { type: QueryTypes.SELECT as QueryTypes.SELECT } + + const [ { total } ] = await seq.query<{ total: string }>(`SELECT COUNT(*) as total FROM "${table}"`, options) + if (total === null) return 0 + + return parseInt(total, 10) + } + + setActorField (to: string, field: string, value: string) { + const seq = this.getSequelize() + + const options = { type: QueryTypes.UPDATE } + + return seq.query(`UPDATE actor SET "${field}" = '${value}' WHERE url = '${to}'`, options) + } + + setVideoField (uuid: string, field: string, value: string) { + const seq = this.getSequelize() + + const options = { type: QueryTypes.UPDATE } + + return seq.query(`UPDATE video SET "${field}" = '${value}' WHERE uuid = '${uuid}'`, options) + } + + setPlaylistField (uuid: string, field: string, value: string) { + const seq = this.getSequelize() + + const options = { type: QueryTypes.UPDATE } + + return seq.query(`UPDATE "videoPlaylist" SET "${field}" = '${value}' WHERE uuid = '${uuid}'`, options) + } + + async countVideoViewsOf (uuid: string) { + const seq = this.getSequelize() + + // tslint:disable + const query = 'SELECT SUM("videoView"."views") AS "total" FROM "videoView" ' + + `INNER JOIN "video" ON "video"."id" = "videoView"."videoId" WHERE "video"."uuid" = '${uuid}'` + + const options = { type: QueryTypes.SELECT as QueryTypes.SELECT } + const [ { total } ] = await seq.query<{ total: number }>(query, options) + + if (!total) return 0 + + return parseInt(total + '', 10) + } + + getActorImage (filename: string) { + return this.selectQuery(`SELECT * FROM "actorImage" WHERE filename = '${filename}'`) + .then(rows => rows[0]) + } + + selectQuery (query: string) { + const seq = this.getSequelize() + const options = { type: QueryTypes.SELECT as QueryTypes.SELECT } + + return seq.query(query, options) + } + + updateQuery (query: string) { + const seq = this.getSequelize() + const options = { type: QueryTypes.UPDATE as QueryTypes.UPDATE } + + return seq.query(query, options) + } + + setPluginField (pluginName: string, field: string, value: string) { + const seq = this.getSequelize() + + const options = { type: QueryTypes.UPDATE } + + return seq.query(`UPDATE "plugin" SET "${field}" = '${value}' WHERE "name" = '${pluginName}'`, options) + } + + setPluginVersion (pluginName: string, newVersion: string) { + return this.setPluginField(pluginName, 'version', newVersion) + } + + setPluginLatestVersion (pluginName: string, newVersion: string) { + return this.setPluginField(pluginName, 'latestVersion', newVersion) + } + + setActorFollowScores (newScore: number) { + const seq = this.getSequelize() + + const options = { type: QueryTypes.UPDATE } + + return seq.query(`UPDATE "actorFollow" SET "score" = ${newScore}`, options) + } + + setTokenField (accessToken: string, field: string, value: string) { + const seq = this.getSequelize() + + const options = { type: QueryTypes.UPDATE } + + return seq.query(`UPDATE "oAuthToken" SET "${field}" = '${value}' WHERE "accessToken" = '${accessToken}'`, options) + } + + async cleanup () { + if (!this.sequelize) return + + await this.sequelize.close() + this.sequelize = undefined + } + + private getSequelize () { + if (this.sequelize) return this.sequelize + + const dbname = 'peertube_test' + this.server.internalServerNumber + const username = 'peertube' + const password = 'peertube' + const host = 'localhost' + const port = 5432 + + this.sequelize = new Sequelize(dbname, username, password, { + dialect: 'postgres', + host, + port, + logging: false + }) + + return this.sequelize + } + +} diff --git a/shared/extra-utils/miscs/sql.ts b/shared/extra-utils/miscs/sql.ts deleted file mode 100644 index 65a0aa5fe..000000000 --- a/shared/extra-utils/miscs/sql.ts +++ /dev/null @@ -1,161 +0,0 @@ -import { QueryTypes, Sequelize } from 'sequelize' -import { ServerInfo } from '../server/servers' - -const sequelizes: { [ id: number ]: Sequelize } = {} - -function getSequelize (internalServerNumber: number) { - if (sequelizes[internalServerNumber]) return sequelizes[internalServerNumber] - - const dbname = 'peertube_test' + internalServerNumber - const username = 'peertube' - const password = 'peertube' - const host = 'localhost' - const port = 5432 - - const seq = new Sequelize(dbname, username, password, { - dialect: 'postgres', - host, - port, - logging: false - }) - - sequelizes[internalServerNumber] = seq - - return seq -} - -function deleteAll (internalServerNumber: number, table: string) { - const seq = getSequelize(internalServerNumber) - - const options = { type: QueryTypes.DELETE } - - return seq.query(`DELETE FROM "${table}"`, options) -} - -async function getCount (internalServerNumber: number, table: string) { - const seq = getSequelize(internalServerNumber) - - const options = { type: QueryTypes.SELECT as QueryTypes.SELECT } - - const [ { total } ] = await seq.query<{ total: string }>(`SELECT COUNT(*) as total FROM "${table}"`, options) - if (total === null) return 0 - - return parseInt(total, 10) -} - -function setActorField (internalServerNumber: number, to: string, field: string, value: string) { - const seq = getSequelize(internalServerNumber) - - const options = { type: QueryTypes.UPDATE } - - return seq.query(`UPDATE actor SET "${field}" = '${value}' WHERE url = '${to}'`, options) -} - -function setVideoField (internalServerNumber: number, uuid: string, field: string, value: string) { - const seq = getSequelize(internalServerNumber) - - const options = { type: QueryTypes.UPDATE } - - return seq.query(`UPDATE video SET "${field}" = '${value}' WHERE uuid = '${uuid}'`, options) -} - -function setPlaylistField (internalServerNumber: number, uuid: string, field: string, value: string) { - const seq = getSequelize(internalServerNumber) - - const options = { type: QueryTypes.UPDATE } - - return seq.query(`UPDATE "videoPlaylist" SET "${field}" = '${value}' WHERE uuid = '${uuid}'`, options) -} - -async function countVideoViewsOf (internalServerNumber: number, uuid: string) { - const seq = getSequelize(internalServerNumber) - - // tslint:disable - const query = 'SELECT SUM("videoView"."views") AS "total" FROM "videoView" ' + - `INNER JOIN "video" ON "video"."id" = "videoView"."videoId" WHERE "video"."uuid" = '${uuid}'` - - const options = { type: QueryTypes.SELECT as QueryTypes.SELECT } - const [ { total } ] = await seq.query<{ total: number }>(query, options) - - if (!total) return 0 - - return parseInt(total + '', 10) -} - -function getActorImage (internalServerNumber: number, filename: string) { - return selectQuery(internalServerNumber, `SELECT * FROM "actorImage" WHERE filename = '${filename}'`) - .then(rows => rows[0]) -} - -function selectQuery (internalServerNumber: number, query: string) { - const seq = getSequelize(internalServerNumber) - const options = { type: QueryTypes.SELECT as QueryTypes.SELECT } - - return seq.query(query, options) -} - -function updateQuery (internalServerNumber: number, query: string) { - const seq = getSequelize(internalServerNumber) - const options = { type: QueryTypes.UPDATE as QueryTypes.UPDATE } - - return seq.query(query, options) -} - -async function closeAllSequelize (servers: ServerInfo[]) { - for (const server of servers) { - if (sequelizes[server.internalServerNumber]) { - await sequelizes[server.internalServerNumber].close() - // eslint-disable-next-line - delete sequelizes[server.internalServerNumber] - } - } -} - -function setPluginField (internalServerNumber: number, pluginName: string, field: string, value: string) { - const seq = getSequelize(internalServerNumber) - - const options = { type: QueryTypes.UPDATE } - - return seq.query(`UPDATE "plugin" SET "${field}" = '${value}' WHERE "name" = '${pluginName}'`, options) -} - -function setPluginVersion (internalServerNumber: number, pluginName: string, newVersion: string) { - return setPluginField(internalServerNumber, pluginName, 'version', newVersion) -} - -function setPluginLatestVersion (internalServerNumber: number, pluginName: string, newVersion: string) { - return setPluginField(internalServerNumber, pluginName, 'latestVersion', newVersion) -} - -function setActorFollowScores (internalServerNumber: number, newScore: number) { - const seq = getSequelize(internalServerNumber) - - const options = { type: QueryTypes.UPDATE } - - return seq.query(`UPDATE "actorFollow" SET "score" = ${newScore}`, options) -} - -function setTokenField (internalServerNumber: number, accessToken: string, field: string, value: string) { - const seq = getSequelize(internalServerNumber) - - const options = { type: QueryTypes.UPDATE } - - return seq.query(`UPDATE "oAuthToken" SET "${field}" = '${value}' WHERE "accessToken" = '${accessToken}'`, options) -} - -export { - setVideoField, - setPlaylistField, - setActorField, - countVideoViewsOf, - setPluginVersion, - setPluginLatestVersion, - selectQuery, - getActorImage, - deleteAll, - setTokenField, - updateQuery, - setActorFollowScores, - closeAllSequelize, - getCount -} diff --git a/shared/extra-utils/miscs/stubs.ts b/shared/extra-utils/miscs/stubs.ts index d1eb0e3b2..940e4bf29 100644 --- a/shared/extra-utils/miscs/stubs.ts +++ b/shared/extra-utils/miscs/stubs.ts @@ -2,13 +2,6 @@ function buildRequestStub (): any { return { } } -function buildResponseStub (): any { - return { - locals: {} - } -} - export { - buildResponseStub, buildRequestStub } diff --git a/shared/extra-utils/server/servers.ts b/shared/extra-utils/server/servers.ts index 41b48a8ee..bd3be8373 100644 --- a/shared/extra-utils/server/servers.ts +++ b/shared/extra-utils/server/servers.ts @@ -30,6 +30,7 @@ import { ServicesCommand, StreamingPlaylistsCommand } from '../videos' +import { SQLCommand } from '../miscs' import { CommentsCommand } from '../videos/comments-command' import { ConfigCommand } from './config-command' import { ContactFormCommand } from './contact-form-command' @@ -123,6 +124,7 @@ interface ServerInfo { streamingPlaylistsCommand?: StreamingPlaylistsCommand channelsCommand?: ChannelsCommand commentsCommand?: CommentsCommand + sqlCommand?: SQLCommand } function parallelTests () { @@ -367,6 +369,7 @@ function assignCommands (server: ServerInfo) { server.streamingPlaylistsCommand = new StreamingPlaylistsCommand(server) server.channelsCommand = new ChannelsCommand(server) server.commentsCommand = new CommentsCommand(server) + server.sqlCommand = new SQLCommand(server) } async function reRunServer (server: ServerInfo, configOverride?: any) { @@ -398,17 +401,20 @@ async function checkDirectoryIsEmpty (server: ServerInfo, directory: string, exc expect(filtered).to.have.lengthOf(0) } -function killallServers (servers: ServerInfo[]) { +async function killallServers (servers: ServerInfo[]) { for (const server of servers) { if (!server.app) continue + await server.sqlCommand.cleanup() + process.kill(-server.app.pid) + server.app = null } } async function cleanupTests (servers: ServerInfo[]) { - killallServers(servers) + await killallServers(servers) if (isGithubCI()) { await ensureDir('artifacts') diff --git a/shared/extra-utils/shared/abstract-command.ts b/shared/extra-utils/shared/abstract-command.ts index 6a9ab1348..200db90d4 100644 --- a/shared/extra-utils/shared/abstract-command.ts +++ b/shared/extra-utils/shared/abstract-command.ts @@ -1,6 +1,6 @@ import { isAbsolute, join } from 'path' import { HttpStatusCode } from '@shared/core-utils' -import { root } from '../miscs' +import { root } from '../miscs/miscs' import { makeDeleteRequest, makeGetRequest, -- cgit v1.2.3 From dd0ebb715123dfa126a82d4e4fe3a04064ae77b8 Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Fri, 9 Jul 2021 16:23:01 +0200 Subject: Introduce notifications command --- server/tests/api/check-params/contact-form.ts | 2 +- server/tests/api/check-params/video-comments.ts | 2 +- .../tests/api/moderation/blocklist-notification.ts | 47 +- server/tests/api/moderation/blocklist.ts | 28 +- .../tests/api/notifications/notifications-api.ts | 92 +-- .../tests/api/notifications/user-notifications.ts | 5 +- server/tests/api/server/plugins.ts | 3 +- server/tests/api/videos/video-hls.ts | 1 + server/tests/api/videos/video-nsfw.ts | 142 ++-- server/tools/test-live.ts | 2 +- shared/extra-utils/search/search-command.ts | 2 +- shared/extra-utils/server/servers.ts | 6 +- shared/extra-utils/shared/abstract-command.ts | 7 +- shared/extra-utils/users/index.ts | 3 +- shared/extra-utils/users/notifications-command.ts | 87 +++ shared/extra-utils/users/notifications.ts | 729 +++++++++++++++++++ shared/extra-utils/users/user-notifications.ts | 808 --------------------- .../videos/streaming-playlists-command.ts | 2 +- 18 files changed, 983 insertions(+), 985 deletions(-) create mode 100644 shared/extra-utils/users/notifications-command.ts create mode 100644 shared/extra-utils/users/notifications.ts delete mode 100644 shared/extra-utils/users/user-notifications.ts diff --git a/server/tests/api/check-params/contact-form.ts b/server/tests/api/check-params/contact-form.ts index 5539266b8..4eed1661a 100644 --- a/server/tests/api/check-params/contact-form.ts +++ b/server/tests/api/check-params/contact-form.ts @@ -69,7 +69,7 @@ describe('Test contact form API validators', function () { }) it('Should accept a contact form with the correct parameters', async function () { - await command.send({ ...defaultBody }) + await command.send(defaultBody) }) after(async function () { diff --git a/server/tests/api/check-params/video-comments.ts b/server/tests/api/check-params/video-comments.ts index ff94645cb..0f8c81392 100644 --- a/server/tests/api/check-params/video-comments.ts +++ b/server/tests/api/check-params/video-comments.ts @@ -278,7 +278,7 @@ describe('Test video comments API validator', function () { let commentToDelete: number { - const created = await server.commentsCommand.createThread({ videoId: video.uuid, text: 'hello' }) + const created = await server.commentsCommand.createThread({ videoId: video.uuid, token: userAccessToken, text: 'hello' }) commentToDelete = created.id } diff --git a/server/tests/api/moderation/blocklist-notification.ts b/server/tests/api/moderation/blocklist-notification.ts index a077d8739..b676a4db4 100644 --- a/server/tests/api/moderation/blocklist-notification.ts +++ b/server/tests/api/moderation/blocklist-notification.ts @@ -7,27 +7,22 @@ import { createUser, doubleFollow, flushAndRunMultipleServers, - getUserNotifications, - markAsReadAllNotifications, ServerInfo, setAccessTokensToServers, uploadVideo, userLogin, waitJobs } from '@shared/extra-utils' -import { UserNotification, UserNotificationType } from '@shared/models' +import { UserNotificationType } from '@shared/models' const expect = chai.expect -async function checkNotifications (url: string, token: string, expected: UserNotificationType[]) { - const res = await getUserNotifications(url, token, 0, 10, true) - - const notifications: UserNotification[] = res.body.data - - expect(notifications).to.have.lengthOf(expected.length) +async function checkNotifications (server: ServerInfo, token: string, expected: UserNotificationType[]) { + const { data } = await server.notificationsCommand.list({ token, start: 0, count: 10, unread: true }) + expect(data).to.have.lengthOf(expected.length) for (const type of expected) { - expect(notifications.find(n => n.type === type)).to.exist + expect(data.find(n => n.type === type)).to.exist } } @@ -47,8 +42,8 @@ describe('Test blocklist', function () { await waitJobs(servers) - await markAsReadAllNotifications(servers[0].url, userToken1) - await markAsReadAllNotifications(servers[0].url, userToken2) + await servers[0].notificationsCommand.markAsReadAll({ token: userToken1 }) + await servers[0].notificationsCommand.markAsReadAll({ token: userToken2 }) { const res = await uploadVideo(servers[0].url, userToken1, { name: 'video' }) @@ -122,7 +117,7 @@ describe('Test blocklist', function () { it('Should have appropriate notifications', async function () { const notifs = [ UserNotificationType.NEW_COMMENT_ON_MY_VIDEO, UserNotificationType.NEW_FOLLOW ] - await checkNotifications(servers[0].url, userToken1, notifs) + await checkNotifications(servers[0], userToken1, notifs) }) it('Should block an account', async function () { @@ -133,13 +128,13 @@ describe('Test blocklist', function () { }) it('Should not have notifications from this account', async function () { - await checkNotifications(servers[0].url, userToken1, []) + await checkNotifications(servers[0], userToken1, []) }) it('Should have notifications of this account on user 2', async function () { const notifs = [ UserNotificationType.COMMENT_MENTION, UserNotificationType.NEW_FOLLOW ] - await checkNotifications(servers[0].url, userToken2, notifs) + await checkNotifications(servers[0], userToken2, notifs) await servers[0].blocklistCommand.removeFromMyBlocklist({ token: userToken1, account: 'user3@' + servers[1].host }) }) @@ -155,7 +150,7 @@ describe('Test blocklist', function () { it('Should have appropriate notifications', async function () { const notifs = [ UserNotificationType.NEW_COMMENT_ON_MY_VIDEO, UserNotificationType.NEW_FOLLOW ] - await checkNotifications(servers[0].url, userToken1, notifs) + await checkNotifications(servers[0], userToken1, notifs) }) it('Should block an account', async function () { @@ -166,13 +161,13 @@ describe('Test blocklist', function () { }) it('Should not have notifications from this account', async function () { - await checkNotifications(servers[0].url, userToken1, []) + await checkNotifications(servers[0], userToken1, []) }) it('Should have notifications of this account on user 2', async function () { const notifs = [ UserNotificationType.COMMENT_MENTION, UserNotificationType.NEW_FOLLOW ] - await checkNotifications(servers[0].url, userToken2, notifs) + await checkNotifications(servers[0], userToken2, notifs) await servers[0].blocklistCommand.removeFromMyBlocklist({ token: userToken1, server: servers[1].host }) }) @@ -189,12 +184,12 @@ describe('Test blocklist', function () { it('Should have appropriate notifications', async function () { { const notifs = [ UserNotificationType.NEW_COMMENT_ON_MY_VIDEO, UserNotificationType.NEW_FOLLOW ] - await checkNotifications(servers[0].url, userToken1, notifs) + await checkNotifications(servers[0], userToken1, notifs) } { const notifs = [ UserNotificationType.COMMENT_MENTION, UserNotificationType.NEW_FOLLOW ] - await checkNotifications(servers[0].url, userToken2, notifs) + await checkNotifications(servers[0], userToken2, notifs) } }) @@ -206,8 +201,8 @@ describe('Test blocklist', function () { }) it('Should not have notifications from this account', async function () { - await checkNotifications(servers[0].url, userToken1, []) - await checkNotifications(servers[0].url, userToken2, []) + await checkNotifications(servers[0], userToken1, []) + await checkNotifications(servers[0], userToken2, []) await servers[0].blocklistCommand.removeFromServerBlocklist({ account: 'user3@' + servers[1].host }) }) @@ -224,12 +219,12 @@ describe('Test blocklist', function () { it('Should have appropriate notifications', async function () { { const notifs = [ UserNotificationType.NEW_COMMENT_ON_MY_VIDEO, UserNotificationType.NEW_FOLLOW ] - await checkNotifications(servers[0].url, userToken1, notifs) + await checkNotifications(servers[0], userToken1, notifs) } { const notifs = [ UserNotificationType.COMMENT_MENTION, UserNotificationType.NEW_FOLLOW ] - await checkNotifications(servers[0].url, userToken2, notifs) + await checkNotifications(servers[0], userToken2, notifs) } }) @@ -241,8 +236,8 @@ describe('Test blocklist', function () { }) it('Should not have notifications from this account', async function () { - await checkNotifications(servers[0].url, userToken1, []) - await checkNotifications(servers[0].url, userToken2, []) + await checkNotifications(servers[0], userToken1, []) + await checkNotifications(servers[0], userToken2, []) }) }) diff --git a/server/tests/api/moderation/blocklist.ts b/server/tests/api/moderation/blocklist.ts index 00cb6c65c..44e3de4e4 100644 --- a/server/tests/api/moderation/blocklist.ts +++ b/server/tests/api/moderation/blocklist.ts @@ -9,7 +9,6 @@ import { createUser, doubleFollow, flushAndRunMultipleServers, - getUserNotifications, getVideosList, getVideosListWithToken, ServerInfo, @@ -18,7 +17,7 @@ import { userLogin, waitJobs } from '@shared/extra-utils' -import { UserNotification, UserNotificationType, Video } from '@shared/models' +import { UserNotificationType, Video } from '@shared/models' const expect = chai.expect @@ -59,9 +58,8 @@ async function checkCommentNotification ( await waitJobs([ mainServer, comment.server ]) - const res = await getUserNotifications(mainServer.url, mainServer.accessToken, 0, 30) - const commentNotifications = (res.body.data as UserNotification[]) - .filter(n => n.comment && n.comment.video.uuid === comment.videoUUID && n.createdAt >= createdAt) + const { data } = await mainServer.notificationsCommand.list({ start: 0, count: 30 }) + const commentNotifications = data.filter(n => n.comment && n.comment.video.uuid === comment.videoUUID && n.createdAt >= createdAt) if (check === 'presence') expect(commentNotifications).to.have.lengthOf(1) else expect(commentNotifications).to.have.lengthOf(0) @@ -710,12 +708,10 @@ describe('Test blocklist', function () { await waitJobs(servers) - const res = await getUserNotifications(servers[0].url, servers[0].accessToken, 0, 30) - const commentNotifications = (res.body.data as UserNotification[]) - .filter(n => { - return n.type === UserNotificationType.NEW_INSTANCE_FOLLOWER && - n.createdAt >= now.toISOString() - }) + const { data } = await servers[0].notificationsCommand.list({ start: 0, count: 30 }) + const commentNotifications = data.filter(n => { + return n.type === UserNotificationType.NEW_INSTANCE_FOLLOWER && n.createdAt >= now.toISOString() + }) expect(commentNotifications).to.have.lengthOf(0) } @@ -773,12 +769,10 @@ describe('Test blocklist', function () { await waitJobs(servers) - const res = await getUserNotifications(servers[0].url, servers[0].accessToken, 0, 30) - const commentNotifications = (res.body.data as UserNotification[]) - .filter(n => { - return n.type === UserNotificationType.NEW_INSTANCE_FOLLOWER && - n.createdAt >= now.toISOString() - }) + const { data } = await servers[0].notificationsCommand.list({ start: 0, count: 30 }) + const commentNotifications = data.filter(n => { + return n.type === UserNotificationType.NEW_INSTANCE_FOLLOWER && n.createdAt >= now.toISOString() + }) expect(commentNotifications).to.have.lengthOf(1) } diff --git a/server/tests/api/notifications/notifications-api.ts b/server/tests/api/notifications/notifications-api.ts index 1ed98ae7a..447492c5f 100644 --- a/server/tests/api/notifications/notifications-api.ts +++ b/server/tests/api/notifications/notifications-api.ts @@ -8,14 +8,10 @@ import { cleanupTests, getAllNotificationsSettings, getMyUserInformation, - getUserNotifications, immutableAssign, - markAsReadAllNotifications, - markAsReadNotifications, MockSmtpServer, prepareNotificationsTest, ServerInfo, - updateMyNotificationSettings, uploadRandomVideo, waitJobs } from '@shared/extra-utils' @@ -26,7 +22,7 @@ const expect = chai.expect describe('Test notifications API', function () { let server: ServerInfo let userNotifications: UserNotification[] = [] - let userAccessToken: string + let userToken: string let emails: object[] = [] before(async function () { @@ -34,11 +30,11 @@ describe('Test notifications API', function () { const res = await prepareNotificationsTest(1) emails = res.emails - userAccessToken = res.userAccessToken + userToken = res.userAccessToken userNotifications = res.userNotifications server = res.servers[0] - await server.subscriptionsCommand.add({ token: userAccessToken, targetUri: 'root_channel@localhost:' + server.port }) + await server.subscriptionsCommand.add({ token: userToken, targetUri: 'root_channel@localhost:' + server.port }) for (let i = 0; i < 10; i++) { await uploadRandomVideo(server, false) @@ -50,49 +46,46 @@ describe('Test notifications API', function () { describe('Mark as read', function () { it('Should mark as read some notifications', async function () { - const res = await getUserNotifications(server.url, userAccessToken, 2, 3) - const ids = res.body.data.map(n => n.id) + const { data } = await server.notificationsCommand.list({ token: userToken, start: 2, count: 3 }) + const ids = data.map(n => n.id) - await markAsReadNotifications(server.url, userAccessToken, ids) + await server.notificationsCommand.markAsRead({ token: userToken, ids }) }) it('Should have the notifications marked as read', async function () { - const res = await getUserNotifications(server.url, userAccessToken, 0, 10) - - const notifications = res.body.data as UserNotification[] - expect(notifications[0].read).to.be.false - expect(notifications[1].read).to.be.false - expect(notifications[2].read).to.be.true - expect(notifications[3].read).to.be.true - expect(notifications[4].read).to.be.true - expect(notifications[5].read).to.be.false + const { data } = await server.notificationsCommand.list({ token: userToken, start: 0, count: 10 }) + + expect(data[0].read).to.be.false + expect(data[1].read).to.be.false + expect(data[2].read).to.be.true + expect(data[3].read).to.be.true + expect(data[4].read).to.be.true + expect(data[5].read).to.be.false }) it('Should only list read notifications', async function () { - const res = await getUserNotifications(server.url, userAccessToken, 0, 10, false) + const { data } = await server.notificationsCommand.list({ token: userToken, start: 0, count: 10, unread: false }) - const notifications = res.body.data as UserNotification[] - for (const notification of notifications) { + for (const notification of data) { expect(notification.read).to.be.true } }) it('Should only list unread notifications', async function () { - const res = await getUserNotifications(server.url, userAccessToken, 0, 10, true) + const { data } = await server.notificationsCommand.list({ token: userToken, start: 0, count: 10, unread: true }) - const notifications = res.body.data as UserNotification[] - for (const notification of notifications) { + for (const notification of data) { expect(notification.read).to.be.false } }) it('Should mark as read all notifications', async function () { - await markAsReadAllNotifications(server.url, userAccessToken) + await server.notificationsCommand.markAsReadAll({ token: userToken }) - const res = await getUserNotifications(server.url, userAccessToken, 0, 10, true) + const body = await server.notificationsCommand.list({ token: userToken, start: 0, count: 10, unread: true }) - expect(res.body.total).to.equal(0) - expect(res.body.data).to.have.lengthOf(0) + expect(body.total).to.equal(0) + expect(body.data).to.have.lengthOf(0) }) }) @@ -104,19 +97,20 @@ describe('Test notifications API', function () { server: server, emails, socketNotifications: userNotifications, - token: userAccessToken + token: userToken } }) it('Should not have notifications', async function () { this.timeout(20000) - await updateMyNotificationSettings(server.url, userAccessToken, immutableAssign(getAllNotificationsSettings(), { - newVideoFromSubscription: UserNotificationSettingValue.NONE - })) + await server.notificationsCommand.updateMySettings({ + token: userToken, + settings: { ...getAllNotificationsSettings(), newVideoFromSubscription: UserNotificationSettingValue.NONE } + }) { - const res = await getMyUserInformation(server.url, userAccessToken) + const res = await getMyUserInformation(server.url, userToken) const info = res.body as User expect(info.notificationSettings.newVideoFromSubscription).to.equal(UserNotificationSettingValue.NONE) } @@ -130,12 +124,13 @@ describe('Test notifications API', function () { it('Should only have web notifications', async function () { this.timeout(20000) - await updateMyNotificationSettings(server.url, userAccessToken, immutableAssign(getAllNotificationsSettings(), { - newVideoFromSubscription: UserNotificationSettingValue.WEB - })) + await server.notificationsCommand.updateMySettings({ + token: userToken, + settings: { ...getAllNotificationsSettings(), newVideoFromSubscription: UserNotificationSettingValue.WEB } + }) { - const res = await getMyUserInformation(server.url, userAccessToken) + const res = await getMyUserInformation(server.url, userToken) const info = res.body as User expect(info.notificationSettings.newVideoFromSubscription).to.equal(UserNotificationSettingValue.WEB) } @@ -156,12 +151,13 @@ describe('Test notifications API', function () { it('Should only have mail notifications', async function () { this.timeout(20000) - await updateMyNotificationSettings(server.url, userAccessToken, immutableAssign(getAllNotificationsSettings(), { - newVideoFromSubscription: UserNotificationSettingValue.EMAIL - })) + await server.notificationsCommand.updateMySettings({ + token: userToken, + settings: { ...getAllNotificationsSettings(), newVideoFromSubscription: UserNotificationSettingValue.EMAIL } + }) { - const res = await getMyUserInformation(server.url, userAccessToken) + const res = await getMyUserInformation(server.url, userToken) const info = res.body as User expect(info.notificationSettings.newVideoFromSubscription).to.equal(UserNotificationSettingValue.EMAIL) } @@ -182,12 +178,16 @@ describe('Test notifications API', function () { it('Should have email and web notifications', async function () { this.timeout(20000) - await updateMyNotificationSettings(server.url, userAccessToken, immutableAssign(getAllNotificationsSettings(), { - newVideoFromSubscription: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL - })) + await server.notificationsCommand.updateMySettings({ + token: userToken, + settings: { + ...getAllNotificationsSettings(), + newVideoFromSubscription: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL + } + }) { - const res = await getMyUserInformation(server.url, userAccessToken) + const res = await getMyUserInformation(server.url, userToken) const info = res.body as User expect(info.notificationSettings.newVideoFromSubscription).to.equal( UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL diff --git a/server/tests/api/notifications/user-notifications.ts b/server/tests/api/notifications/user-notifications.ts index 1d159c48f..4b31edf25 100644 --- a/server/tests/api/notifications/user-notifications.ts +++ b/server/tests/api/notifications/user-notifications.ts @@ -10,7 +10,6 @@ import { checkNewVideoFromSubscription, checkVideoIsPublished, cleanupTests, - getLastNotification, ImportsCommand, MockSmtpServer, prepareNotificationsTest, @@ -64,7 +63,7 @@ describe('Test user notifications', function () { await uploadRandomVideoOnServers(servers, 1) - const notification = await getLastNotification(servers[0].url, userAccessToken) + const notification = await servers[0].notificationsCommand.getLastest({ token: userAccessToken }) expect(notification).to.be.undefined expect(emails).to.have.lengthOf(0) @@ -245,7 +244,7 @@ describe('Test user notifications', function () { await uploadRandomVideoOnServers(servers, 2, { waitTranscoding: false }) await waitJobs(servers) - const notification = await getLastNotification(servers[0].url, userAccessToken) + const notification = await servers[0].notificationsCommand.getLastest({ token: userAccessToken }) if (notification) { expect(notification.type).to.not.equal(UserNotificationType.MY_VIDEO_PUBLISHED) } diff --git a/server/tests/api/server/plugins.ts b/server/tests/api/server/plugins.ts index 655cf00fa..d4a43276f 100644 --- a/server/tests/api/server/plugins.ts +++ b/server/tests/api/server/plugins.ts @@ -146,13 +146,12 @@ describe('Test plugins', function () { } { - const body = await command.list({ + const { data } = await command.list({ count: 2, start: 0, sort: 'name' }) - const data = body expect(data[0].name).to.equal('background-red') expect(data[1].name).to.equal('hello-world') } diff --git a/server/tests/api/videos/video-hls.ts b/server/tests/api/videos/video-hls.ts index 3dd8c9066..428e1316d 100644 --- a/server/tests/api/videos/video-hls.ts +++ b/server/tests/api/videos/video-hls.ts @@ -109,6 +109,7 @@ describe('Test HLS videos', function () { let videoAudioUUID = '' function runTestSuite (hlsOnly: boolean) { + it('Should upload a video and transcode it to HLS', async function () { this.timeout(120000) diff --git a/server/tests/api/videos/video-nsfw.ts b/server/tests/api/videos/video-nsfw.ts index 65813517d..5f30939cc 100644 --- a/server/tests/api/videos/video-nsfw.ts +++ b/server/tests/api/videos/video-nsfw.ts @@ -18,13 +18,13 @@ import { uploadVideo, userLogin } from '@shared/extra-utils' -import { BooleanBothQuery, CustomConfig, User, VideosOverview } from '@shared/models' +import { BooleanBothQuery, CustomConfig, ResultList, User, Video, VideosOverview } from '@shared/models' const expect = chai.expect function createOverviewRes (overview: VideosOverview) { const videos = overview.categories[0].videos - return { body: { data: videos, total: videos.length } } + return { data: videos, total: videos.length } } describe('Test video NSFW policy', function () { @@ -32,49 +32,47 @@ describe('Test video NSFW policy', function () { let userAccessToken: string let customConfig: CustomConfig - function getVideosFunctions (token?: string, query: { nsfw?: BooleanBothQuery } = {}) { - return getMyUserInformation(server.url, server.accessToken) - .then(res => { - const user: User = res.body - const videoChannelName = user.videoChannels[0].name - const accountName = user.account.name + '@' + user.account.host - const hasQuery = Object.keys(query).length !== 0 - let promises: Promise[] - - if (token) { - promises = [ - getVideosListWithToken(server.url, token, query), - server.searchCommand.advancedVideoSearch({ token, search: { search: 'n', ...query } }), - getAccountVideos(server.url, token, accountName, 0, 5, undefined, query), - getVideoChannelVideos(server.url, token, videoChannelName, 0, 5, undefined, query) - ] - - // Overviews do not support video filters - if (!hasQuery) { - const p = server.overviewsCommand.getVideos({ page: 1, token }) - .then(res => createOverviewRes(res)) - promises.push(p) - } - - return Promise.all(promises) - } - - promises = [ - getVideosList(server.url), - server.searchCommand.searchVideos({ search: 'n' }), - getAccountVideos(server.url, undefined, accountName, 0, 5), - getVideoChannelVideos(server.url, undefined, videoChannelName, 0, 5) - ] - - // Overviews do not support video filters - if (!hasQuery) { - const p = server.overviewsCommand.getVideos({ page: 1 }) - .then(res => createOverviewRes(res)) - promises.push(p) - } - - return Promise.all(promises) - }) + async function getVideosFunctions (token?: string, query: { nsfw?: BooleanBothQuery } = {}) { + const res = await getMyUserInformation(server.url, server.accessToken) + const user: User = res.body + const videoChannelName = user.videoChannels[0].name + const accountName = user.account.name + '@' + user.account.host + const hasQuery = Object.keys(query).length !== 0 + let promises: Promise>[] + + if (token) { + promises = [ + getVideosListWithToken(server.url, token, query).then(res => res.body), + server.searchCommand.advancedVideoSearch({ token, search: { search: 'n', ...query } }), + getAccountVideos(server.url, token, accountName, 0, 5, undefined, query).then(res => res.body), + getVideoChannelVideos(server.url, token, videoChannelName, 0, 5, undefined, query).then(res => res.body) + ] + + // Overviews do not support video filters + if (!hasQuery) { + const p = server.overviewsCommand.getVideos({ page: 1, token }) + .then(res => createOverviewRes(res)) + promises.push(p) + } + + return Promise.all(promises) + } + + promises = [ + getVideosList(server.url).then(res => res.body), + server.searchCommand.searchVideos({ search: 'n' }), + getAccountVideos(server.url, undefined, accountName, 0, 5).then(res => res.body), + getVideoChannelVideos(server.url, undefined, videoChannelName, 0, 5).then(res => res.body) + ] + + // Overviews do not support video filters + if (!hasQuery) { + const p = server.overviewsCommand.getVideos({ page: 1 }) + .then(res => createOverviewRes(res)) + promises.push(p) + } + + return Promise.all(promises) } before(async function () { @@ -102,10 +100,10 @@ describe('Test video NSFW policy', function () { const serverConfig = await server.configCommand.getConfig() expect(serverConfig.instance.defaultNSFWPolicy).to.equal('display') - for (const res of await getVideosFunctions()) { - expect(res.body.total).to.equal(2) + for (const body of await getVideosFunctions()) { + expect(body.total).to.equal(2) - const videos = res.body.data + const videos = body.data expect(videos).to.have.lengthOf(2) expect(videos[0].name).to.equal('normal') expect(videos[1].name).to.equal('nsfw') @@ -119,10 +117,10 @@ describe('Test video NSFW policy', function () { const serverConfig = await server.configCommand.getConfig() expect(serverConfig.instance.defaultNSFWPolicy).to.equal('do_not_list') - for (const res of await getVideosFunctions()) { - expect(res.body.total).to.equal(1) + for (const body of await getVideosFunctions()) { + expect(body.total).to.equal(1) - const videos = res.body.data + const videos = body.data expect(videos).to.have.lengthOf(1) expect(videos[0].name).to.equal('normal') } @@ -135,10 +133,10 @@ describe('Test video NSFW policy', function () { const serverConfig = await server.configCommand.getConfig() expect(serverConfig.instance.defaultNSFWPolicy).to.equal('blur') - for (const res of await getVideosFunctions()) { - expect(res.body.total).to.equal(2) + for (const body of await getVideosFunctions()) { + expect(body.total).to.equal(2) - const videos = res.body.data + const videos = body.data expect(videos).to.have.lengthOf(2) expect(videos[0].name).to.equal('normal') expect(videos[1].name).to.equal('nsfw') @@ -165,10 +163,10 @@ describe('Test video NSFW policy', function () { customConfig.instance.defaultNSFWPolicy = 'do_not_list' await server.configCommand.updateCustomConfig({ newCustomConfig: customConfig }) - for (const res of await getVideosFunctions(userAccessToken)) { - expect(res.body.total).to.equal(2) + for (const body of await getVideosFunctions(userAccessToken)) { + expect(body.total).to.equal(2) - const videos = res.body.data + const videos = body.data expect(videos).to.have.lengthOf(2) expect(videos[0].name).to.equal('normal') expect(videos[1].name).to.equal('nsfw') @@ -182,10 +180,10 @@ describe('Test video NSFW policy', function () { nsfwPolicy: 'display' }) - for (const res of await getVideosFunctions(server.accessToken)) { - expect(res.body.total).to.equal(2) + for (const body of await getVideosFunctions(server.accessToken)) { + expect(body.total).to.equal(2) - const videos = res.body.data + const videos = body.data expect(videos).to.have.lengthOf(2) expect(videos[0].name).to.equal('normal') expect(videos[1].name).to.equal('nsfw') @@ -199,10 +197,10 @@ describe('Test video NSFW policy', function () { nsfwPolicy: 'do_not_list' }) - for (const res of await getVideosFunctions(server.accessToken)) { - expect(res.body.total).to.equal(1) + for (const body of await getVideosFunctions(server.accessToken)) { + expect(body.total).to.equal(1) - const videos = res.body.data + const videos = body.data expect(videos).to.have.lengthOf(1) expect(videos[0].name).to.equal('normal') } @@ -219,30 +217,30 @@ describe('Test video NSFW policy', function () { }) it('Should display NSFW videos when the nsfw param === true', async function () { - for (const res of await getVideosFunctions(server.accessToken, { nsfw: 'true' })) { - expect(res.body.total).to.equal(1) + for (const body of await getVideosFunctions(server.accessToken, { nsfw: 'true' })) { + expect(body.total).to.equal(1) - const videos = res.body.data + const videos = body.data expect(videos).to.have.lengthOf(1) expect(videos[0].name).to.equal('nsfw') } }) it('Should hide NSFW videos when the nsfw param === true', async function () { - for (const res of await getVideosFunctions(server.accessToken, { nsfw: 'false' })) { - expect(res.body.total).to.equal(1) + for (const body of await getVideosFunctions(server.accessToken, { nsfw: 'false' })) { + expect(body.total).to.equal(1) - const videos = res.body.data + const videos = body.data expect(videos).to.have.lengthOf(1) expect(videos[0].name).to.equal('normal') } }) it('Should display both videos when the nsfw param === both', async function () { - for (const res of await getVideosFunctions(server.accessToken, { nsfw: 'both' })) { - expect(res.body.total).to.equal(2) + for (const body of await getVideosFunctions(server.accessToken, { nsfw: 'both' })) { + expect(body.total).to.equal(2) - const videos = res.body.data + const videos = body.data expect(videos).to.have.lengthOf(2) expect(videos[0].name).to.equal('normal') expect(videos[1].name).to.equal('nsfw') diff --git a/server/tools/test-live.ts b/server/tools/test-live.ts index 3c6a67cf7..3d1198d9c 100644 --- a/server/tools/test-live.ts +++ b/server/tools/test-live.ts @@ -38,7 +38,7 @@ async function run () { const server = await flushAndRunServer(1, {}, [], { hideLogs: false, execArgv: [ '--inspect' ] }) - const cleanup = () => { + const cleanup = async () => { console.log('Killing server') await killallServers([ server ]) } diff --git a/shared/extra-utils/search/search-command.ts b/shared/extra-utils/search/search-command.ts index 7539a21ec..b6054f093 100644 --- a/shared/extra-utils/search/search-command.ts +++ b/shared/extra-utils/search/search-command.ts @@ -90,7 +90,7 @@ export class SearchCommand extends AbstractCommand { ...options, path, - query: search, + query: { sort: '-publishedAt', ...search }, implicitToken: false, defaultExpectedStatus: HttpStatusCode.OK_200 }) diff --git a/shared/extra-utils/server/servers.ts b/shared/extra-utils/server/servers.ts index bd3be8373..e0e49d2c4 100644 --- a/shared/extra-utils/server/servers.ts +++ b/shared/extra-utils/server/servers.ts @@ -11,13 +11,14 @@ import { CLICommand } from '../cli' import { CustomPagesCommand } from '../custom-pages' import { FeedCommand } from '../feeds' import { LogsCommand } from '../logs' +import { SQLCommand } from '../miscs' import { buildServerDirectory, getFileSize, isGithubCI, root, wait } from '../miscs/miscs' import { AbusesCommand } from '../moderation' import { OverviewsCommand } from '../overviews' import { makeGetRequest } from '../requests/requests' import { SearchCommand } from '../search' import { SocketIOCommand } from '../socket' -import { AccountsCommand, BlocklistCommand, SubscriptionsCommand } from '../users' +import { AccountsCommand, BlocklistCommand, NotificationsCommand, SubscriptionsCommand } from '../users' import { BlacklistCommand, CaptionsCommand, @@ -30,7 +31,6 @@ import { ServicesCommand, StreamingPlaylistsCommand } from '../videos' -import { SQLCommand } from '../miscs' import { CommentsCommand } from '../videos/comments-command' import { ConfigCommand } from './config-command' import { ContactFormCommand } from './contact-form-command' @@ -125,6 +125,7 @@ interface ServerInfo { channelsCommand?: ChannelsCommand commentsCommand?: CommentsCommand sqlCommand?: SQLCommand + notificationsCommand?: NotificationsCommand } function parallelTests () { @@ -370,6 +371,7 @@ function assignCommands (server: ServerInfo) { server.channelsCommand = new ChannelsCommand(server) server.commentsCommand = new CommentsCommand(server) server.sqlCommand = new SQLCommand(server) + server.notificationsCommand = new NotificationsCommand(server) } async function reRunServer (server: ServerInfo, configOverride?: any) { diff --git a/shared/extra-utils/shared/abstract-command.ts b/shared/extra-utils/shared/abstract-command.ts index 200db90d4..fd2deb57e 100644 --- a/shared/extra-utils/shared/abstract-command.ts +++ b/shared/extra-utils/shared/abstract-command.ts @@ -78,7 +78,7 @@ abstract class AbstractCommand { } protected getRequest (options: InternalGetCommandOptions) { - const { redirects, query, contentType, accept } = options + const { redirects, query, contentType, accept, range } = options return makeGetRequest({ ...this.buildCommonRequestOptions(options), @@ -86,6 +86,7 @@ abstract class AbstractCommand { redirects, query, contentType, + range, accept }) } @@ -168,10 +169,10 @@ abstract class AbstractCommand { } private buildCommonRequestOptions (options: InternalCommonCommandOptions) { - const { path } = options + const { url, path } = options return { - url: this.server.url, + url: url ?? this.server.url, path, token: this.buildCommonRequestToken(options), diff --git a/shared/extra-utils/users/index.ts b/shared/extra-utils/users/index.ts index 9f760d7fd..ed166c756 100644 --- a/shared/extra-utils/users/index.ts +++ b/shared/extra-utils/users/index.ts @@ -2,6 +2,7 @@ export * from './accounts-command' export * from './accounts' export * from './blocklist-command' export * from './login' -export * from './user-notifications' +export * from './notifications' +export * from './notifications-command' export * from './subscriptions-command' export * from './users' diff --git a/shared/extra-utils/users/notifications-command.ts b/shared/extra-utils/users/notifications-command.ts new file mode 100644 index 000000000..dfe574ca1 --- /dev/null +++ b/shared/extra-utils/users/notifications-command.ts @@ -0,0 +1,87 @@ +import { ResultList } from '@shared/models' +import { HttpStatusCode } from '../../core-utils/miscs/http-error-codes' +import { UserNotification, UserNotificationSetting } from '../../models/users' +import { AbstractCommand, OverrideCommandOptions } from '../shared' + +export class NotificationsCommand extends AbstractCommand { + + updateMySettings (options: OverrideCommandOptions & { + settings: UserNotificationSetting + }) { + const path = '/api/v1/users/me/notification-settings' + + return this.putBodyRequest({ + ...options, + + path, + fields: options.settings, + implicitToken: true, + defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 + }) + } + + list (options: OverrideCommandOptions & { + start?: number + count?: number + unread?: boolean + sort?: string + }) { + const { start, count, unread, sort = '-createdAt' } = options + const path = '/api/v1/users/me/notifications' + + return this.getRequestBody>({ + ...options, + + path, + query: { + start, + count, + sort, + unread + }, + implicitToken: true, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } + + markAsRead (options: OverrideCommandOptions & { + ids: number[] + }) { + const { ids } = options + const path = '/api/v1/users/me/notifications/read' + + return this.postBodyRequest({ + ...options, + + path, + fields: { ids }, + implicitToken: true, + defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 + }) + } + + markAsReadAll (options: OverrideCommandOptions) { + const path = '/api/v1/users/me/notifications/read-all' + + return this.postBodyRequest({ + ...options, + + path, + implicitToken: true, + defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 + }) + } + + async getLastest (options: OverrideCommandOptions = {}) { + const { total, data } = await this.list({ + ...options, + start: 0, + count: 1, + sort: '-createdAt' + }) + + if (total === 0) return undefined + + return data[0] + } +} diff --git a/shared/extra-utils/users/notifications.ts b/shared/extra-utils/users/notifications.ts new file mode 100644 index 000000000..81f0729fa --- /dev/null +++ b/shared/extra-utils/users/notifications.ts @@ -0,0 +1,729 @@ +/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ + +import { expect } from 'chai' +import { inspect } from 'util' +import { AbuseState, PluginType } from '@shared/models' +import { UserNotification, UserNotificationSetting, UserNotificationSettingValue, UserNotificationType } from '../../models/users' +import { MockSmtpServer } from '../mock-servers/mock-email' +import { doubleFollow } from '../server/follows' +import { flushAndRunMultipleServers, ServerInfo } from '../server/servers' +import { setAccessTokensToServers, userLogin } from './login' +import { createUser, getMyUserInformation } from './users' + +function getAllNotificationsSettings (): UserNotificationSetting { + return { + newVideoFromSubscription: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL, + newCommentOnMyVideo: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL, + abuseAsModerator: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL, + videoAutoBlacklistAsModerator: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL, + blacklistOnMyVideo: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL, + myVideoImportFinished: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL, + myVideoPublished: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL, + commentMention: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL, + newFollow: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL, + newUserRegistration: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL, + newInstanceFollower: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL, + abuseNewMessage: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL, + abuseStateChange: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL, + autoInstanceFollowing: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL, + newPeerTubeVersion: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL, + newPluginVersion: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL + } +} + +type CheckerBaseParams = { + server: ServerInfo + emails: any[] + socketNotifications: UserNotification[] + token: string + check?: { web: boolean, mail: boolean } +} + +type CheckerType = 'presence' | 'absence' + +async function checkNotification ( + base: CheckerBaseParams, + notificationChecker: (notification: UserNotification, type: CheckerType) => void, + emailNotificationFinder: (email: object) => boolean, + checkType: CheckerType +) { + const check = base.check || { web: true, mail: true } + + if (check.web) { + const notification = await base.server.notificationsCommand.getLastest({ token: base.token }) + + if (notification || checkType !== 'absence') { + notificationChecker(notification, checkType) + } + + const socketNotification = base.socketNotifications.find(n => { + try { + notificationChecker(n, 'presence') + return true + } catch { + return false + } + }) + + if (checkType === 'presence') { + const obj = inspect(base.socketNotifications, { depth: 5 }) + expect(socketNotification, 'The socket notification is absent when it should be present. ' + obj).to.not.be.undefined + } else { + const obj = inspect(socketNotification, { depth: 5 }) + expect(socketNotification, 'The socket notification is present when it should not be present. ' + obj).to.be.undefined + } + } + + if (check.mail) { + // Last email + const email = base.emails + .slice() + .reverse() + .find(e => emailNotificationFinder(e)) + + if (checkType === 'presence') { + const emails = base.emails.map(e => e.text) + expect(email, 'The email is absent when is should be present. ' + inspect(emails)).to.not.be.undefined + } else { + expect(email, 'The email is present when is should not be present. ' + inspect(email)).to.be.undefined + } + } +} + +function checkVideo (video: any, videoName?: string, videoUUID?: string) { + if (videoName) { + expect(video.name).to.be.a('string') + expect(video.name).to.not.be.empty + expect(video.name).to.equal(videoName) + } + + if (videoUUID) { + expect(video.uuid).to.be.a('string') + expect(video.uuid).to.not.be.empty + expect(video.uuid).to.equal(videoUUID) + } + + expect(video.id).to.be.a('number') +} + +function checkActor (actor: any) { + expect(actor.displayName).to.be.a('string') + expect(actor.displayName).to.not.be.empty + expect(actor.host).to.not.be.undefined +} + +function checkComment (comment: any, commentId: number, threadId: number) { + expect(comment.id).to.equal(commentId) + expect(comment.threadId).to.equal(threadId) +} + +async function checkNewVideoFromSubscription (base: CheckerBaseParams, videoName: string, videoUUID: string, type: CheckerType) { + const notificationType = UserNotificationType.NEW_VIDEO_FROM_SUBSCRIPTION + + function notificationChecker (notification: UserNotification, type: CheckerType) { + if (type === 'presence') { + expect(notification).to.not.be.undefined + expect(notification.type).to.equal(notificationType) + + checkVideo(notification.video, videoName, videoUUID) + checkActor(notification.video.channel) + } else { + expect(notification).to.satisfy((n: UserNotification) => { + return n === undefined || n.type !== UserNotificationType.NEW_VIDEO_FROM_SUBSCRIPTION || n.video.name !== videoName + }) + } + } + + function emailNotificationFinder (email: object) { + const text = email['text'] + return text.indexOf(videoUUID) !== -1 && text.indexOf('Your subscription') !== -1 + } + + await checkNotification(base, notificationChecker, emailNotificationFinder, type) +} + +async function checkVideoIsPublished (base: CheckerBaseParams, videoName: string, videoUUID: string, type: CheckerType) { + const notificationType = UserNotificationType.MY_VIDEO_PUBLISHED + + function notificationChecker (notification: UserNotification, type: CheckerType) { + if (type === 'presence') { + expect(notification).to.not.be.undefined + expect(notification.type).to.equal(notificationType) + + checkVideo(notification.video, videoName, videoUUID) + checkActor(notification.video.channel) + } else { + expect(notification.video).to.satisfy(v => v === undefined || v.name !== videoName) + } + } + + function emailNotificationFinder (email: object) { + const text: string = email['text'] + return text.includes(videoUUID) && text.includes('Your video') + } + + await checkNotification(base, notificationChecker, emailNotificationFinder, type) +} + +async function checkMyVideoImportIsFinished ( + base: CheckerBaseParams, + videoName: string, + videoUUID: string, + url: string, + success: boolean, + type: CheckerType +) { + const notificationType = success ? UserNotificationType.MY_VIDEO_IMPORT_SUCCESS : UserNotificationType.MY_VIDEO_IMPORT_ERROR + + function notificationChecker (notification: UserNotification, type: CheckerType) { + if (type === 'presence') { + expect(notification).to.not.be.undefined + expect(notification.type).to.equal(notificationType) + + expect(notification.videoImport.targetUrl).to.equal(url) + + if (success) checkVideo(notification.videoImport.video, videoName, videoUUID) + } else { + expect(notification.videoImport).to.satisfy(i => i === undefined || i.targetUrl !== url) + } + } + + function emailNotificationFinder (email: object) { + const text: string = email['text'] + const toFind = success ? ' finished' : ' error' + + return text.includes(url) && text.includes(toFind) + } + + await checkNotification(base, notificationChecker, emailNotificationFinder, type) +} + +async function checkUserRegistered (base: CheckerBaseParams, username: string, type: CheckerType) { + const notificationType = UserNotificationType.NEW_USER_REGISTRATION + + function notificationChecker (notification: UserNotification, type: CheckerType) { + if (type === 'presence') { + expect(notification).to.not.be.undefined + expect(notification.type).to.equal(notificationType) + + checkActor(notification.account) + expect(notification.account.name).to.equal(username) + } else { + expect(notification).to.satisfy(n => n.type !== notificationType || n.account.name !== username) + } + } + + function emailNotificationFinder (email: object) { + const text: string = email['text'] + + return text.includes(' registered.') && text.includes(username) + } + + await checkNotification(base, notificationChecker, emailNotificationFinder, type) +} + +async function checkNewActorFollow ( + base: CheckerBaseParams, + followType: 'channel' | 'account', + followerName: string, + followerDisplayName: string, + followingDisplayName: string, + type: CheckerType +) { + const notificationType = UserNotificationType.NEW_FOLLOW + + function notificationChecker (notification: UserNotification, type: CheckerType) { + if (type === 'presence') { + expect(notification).to.not.be.undefined + expect(notification.type).to.equal(notificationType) + + checkActor(notification.actorFollow.follower) + expect(notification.actorFollow.follower.displayName).to.equal(followerDisplayName) + expect(notification.actorFollow.follower.name).to.equal(followerName) + expect(notification.actorFollow.follower.host).to.not.be.undefined + + const following = notification.actorFollow.following + expect(following.displayName).to.equal(followingDisplayName) + expect(following.type).to.equal(followType) + } else { + expect(notification).to.satisfy(n => { + return n.type !== notificationType || + (n.actorFollow.follower.name !== followerName && n.actorFollow.following !== followingDisplayName) + }) + } + } + + function emailNotificationFinder (email: object) { + const text: string = email['text'] + + return text.includes(followType) && text.includes(followingDisplayName) && text.includes(followerDisplayName) + } + + await checkNotification(base, notificationChecker, emailNotificationFinder, type) +} + +async function checkNewInstanceFollower (base: CheckerBaseParams, followerHost: string, type: CheckerType) { + const notificationType = UserNotificationType.NEW_INSTANCE_FOLLOWER + + function notificationChecker (notification: UserNotification, type: CheckerType) { + if (type === 'presence') { + expect(notification).to.not.be.undefined + expect(notification.type).to.equal(notificationType) + + checkActor(notification.actorFollow.follower) + expect(notification.actorFollow.follower.name).to.equal('peertube') + expect(notification.actorFollow.follower.host).to.equal(followerHost) + + expect(notification.actorFollow.following.name).to.equal('peertube') + } else { + expect(notification).to.satisfy(n => { + return n.type !== notificationType || n.actorFollow.follower.host !== followerHost + }) + } + } + + function emailNotificationFinder (email: object) { + const text: string = email['text'] + + return text.includes('instance has a new follower') && text.includes(followerHost) + } + + await checkNotification(base, notificationChecker, emailNotificationFinder, type) +} + +async function checkAutoInstanceFollowing (base: CheckerBaseParams, followerHost: string, followingHost: string, type: CheckerType) { + const notificationType = UserNotificationType.AUTO_INSTANCE_FOLLOWING + + function notificationChecker (notification: UserNotification, type: CheckerType) { + if (type === 'presence') { + expect(notification).to.not.be.undefined + expect(notification.type).to.equal(notificationType) + + const following = notification.actorFollow.following + checkActor(following) + expect(following.name).to.equal('peertube') + expect(following.host).to.equal(followingHost) + + expect(notification.actorFollow.follower.name).to.equal('peertube') + expect(notification.actorFollow.follower.host).to.equal(followerHost) + } else { + expect(notification).to.satisfy(n => { + return n.type !== notificationType || n.actorFollow.following.host !== followingHost + }) + } + } + + function emailNotificationFinder (email: object) { + const text: string = email['text'] + + return text.includes(' automatically followed a new instance') && text.includes(followingHost) + } + + await checkNotification(base, notificationChecker, emailNotificationFinder, type) +} + +async function checkCommentMention ( + base: CheckerBaseParams, + uuid: string, + commentId: number, + threadId: number, + byAccountDisplayName: string, + type: CheckerType +) { + const notificationType = UserNotificationType.COMMENT_MENTION + + function notificationChecker (notification: UserNotification, type: CheckerType) { + if (type === 'presence') { + expect(notification).to.not.be.undefined + expect(notification.type).to.equal(notificationType) + + checkComment(notification.comment, commentId, threadId) + checkActor(notification.comment.account) + expect(notification.comment.account.displayName).to.equal(byAccountDisplayName) + + checkVideo(notification.comment.video, undefined, uuid) + } else { + expect(notification).to.satisfy(n => n.type !== notificationType || n.comment.id !== commentId) + } + } + + function emailNotificationFinder (email: object) { + const text: string = email['text'] + + return text.includes(' mentioned ') && text.includes(uuid) && text.includes(byAccountDisplayName) + } + + await checkNotification(base, notificationChecker, emailNotificationFinder, type) +} + +let lastEmailCount = 0 + +async function checkNewCommentOnMyVideo (base: CheckerBaseParams, uuid: string, commentId: number, threadId: number, type: CheckerType) { + const notificationType = UserNotificationType.NEW_COMMENT_ON_MY_VIDEO + + function notificationChecker (notification: UserNotification, type: CheckerType) { + if (type === 'presence') { + expect(notification).to.not.be.undefined + expect(notification.type).to.equal(notificationType) + + checkComment(notification.comment, commentId, threadId) + checkActor(notification.comment.account) + checkVideo(notification.comment.video, undefined, uuid) + } else { + expect(notification).to.satisfy((n: UserNotification) => { + return n === undefined || n.comment === undefined || n.comment.id !== commentId + }) + } + } + + const commentUrl = `http://localhost:${base.server.port}/w/${uuid};threadId=${threadId}` + + function emailNotificationFinder (email: object) { + return email['text'].indexOf(commentUrl) !== -1 + } + + await checkNotification(base, notificationChecker, emailNotificationFinder, type) + + if (type === 'presence') { + // We cannot detect email duplicates, so check we received another email + expect(base.emails).to.have.length.above(lastEmailCount) + lastEmailCount = base.emails.length + } +} + +async function checkNewVideoAbuseForModerators (base: CheckerBaseParams, videoUUID: string, videoName: string, type: CheckerType) { + const notificationType = UserNotificationType.NEW_ABUSE_FOR_MODERATORS + + function notificationChecker (notification: UserNotification, type: CheckerType) { + if (type === 'presence') { + expect(notification).to.not.be.undefined + expect(notification.type).to.equal(notificationType) + + expect(notification.abuse.id).to.be.a('number') + checkVideo(notification.abuse.video, videoName, videoUUID) + } else { + expect(notification).to.satisfy((n: UserNotification) => { + return n === undefined || n.abuse === undefined || n.abuse.video.uuid !== videoUUID + }) + } + } + + function emailNotificationFinder (email: object) { + const text = email['text'] + return text.indexOf(videoUUID) !== -1 && text.indexOf('abuse') !== -1 + } + + await checkNotification(base, notificationChecker, emailNotificationFinder, type) +} + +async function checkNewAbuseMessage (base: CheckerBaseParams, abuseId: number, message: string, toEmail: string, type: CheckerType) { + const notificationType = UserNotificationType.ABUSE_NEW_MESSAGE + + function notificationChecker (notification: UserNotification, type: CheckerType) { + if (type === 'presence') { + expect(notification).to.not.be.undefined + expect(notification.type).to.equal(notificationType) + + expect(notification.abuse.id).to.equal(abuseId) + } else { + expect(notification).to.satisfy((n: UserNotification) => { + return n === undefined || n.type !== notificationType || n.abuse === undefined || n.abuse.id !== abuseId + }) + } + } + + function emailNotificationFinder (email: object) { + const text = email['text'] + const to = email['to'].filter(t => t.address === toEmail) + + return text.indexOf(message) !== -1 && to.length !== 0 + } + + await checkNotification(base, notificationChecker, emailNotificationFinder, type) +} + +async function checkAbuseStateChange (base: CheckerBaseParams, abuseId: number, state: AbuseState, type: CheckerType) { + const notificationType = UserNotificationType.ABUSE_STATE_CHANGE + + function notificationChecker (notification: UserNotification, type: CheckerType) { + if (type === 'presence') { + expect(notification).to.not.be.undefined + expect(notification.type).to.equal(notificationType) + + expect(notification.abuse.id).to.equal(abuseId) + expect(notification.abuse.state).to.equal(state) + } else { + expect(notification).to.satisfy((n: UserNotification) => { + return n === undefined || n.abuse === undefined || n.abuse.id !== abuseId + }) + } + } + + function emailNotificationFinder (email: object) { + const text = email['text'] + + const contains = state === AbuseState.ACCEPTED + ? ' accepted' + : ' rejected' + + return text.indexOf(contains) !== -1 + } + + await checkNotification(base, notificationChecker, emailNotificationFinder, type) +} + +async function checkNewCommentAbuseForModerators (base: CheckerBaseParams, videoUUID: string, videoName: string, type: CheckerType) { + const notificationType = UserNotificationType.NEW_ABUSE_FOR_MODERATORS + + function notificationChecker (notification: UserNotification, type: CheckerType) { + if (type === 'presence') { + expect(notification).to.not.be.undefined + expect(notification.type).to.equal(notificationType) + + expect(notification.abuse.id).to.be.a('number') + checkVideo(notification.abuse.comment.video, videoName, videoUUID) + } else { + expect(notification).to.satisfy((n: UserNotification) => { + return n === undefined || n.abuse === undefined || n.abuse.comment.video.uuid !== videoUUID + }) + } + } + + function emailNotificationFinder (email: object) { + const text = email['text'] + return text.indexOf(videoUUID) !== -1 && text.indexOf('abuse') !== -1 + } + + await checkNotification(base, notificationChecker, emailNotificationFinder, type) +} + +async function checkNewAccountAbuseForModerators (base: CheckerBaseParams, displayName: string, type: CheckerType) { + const notificationType = UserNotificationType.NEW_ABUSE_FOR_MODERATORS + + function notificationChecker (notification: UserNotification, type: CheckerType) { + if (type === 'presence') { + expect(notification).to.not.be.undefined + expect(notification.type).to.equal(notificationType) + + expect(notification.abuse.id).to.be.a('number') + expect(notification.abuse.account.displayName).to.equal(displayName) + } else { + expect(notification).to.satisfy((n: UserNotification) => { + return n === undefined || n.abuse === undefined || n.abuse.account.displayName !== displayName + }) + } + } + + function emailNotificationFinder (email: object) { + const text = email['text'] + return text.indexOf(displayName) !== -1 && text.indexOf('abuse') !== -1 + } + + await checkNotification(base, notificationChecker, emailNotificationFinder, type) +} + +async function checkVideoAutoBlacklistForModerators (base: CheckerBaseParams, videoUUID: string, videoName: string, type: CheckerType) { + const notificationType = UserNotificationType.VIDEO_AUTO_BLACKLIST_FOR_MODERATORS + + function notificationChecker (notification: UserNotification, type: CheckerType) { + if (type === 'presence') { + expect(notification).to.not.be.undefined + expect(notification.type).to.equal(notificationType) + + expect(notification.videoBlacklist.video.id).to.be.a('number') + checkVideo(notification.videoBlacklist.video, videoName, videoUUID) + } else { + expect(notification).to.satisfy((n: UserNotification) => { + return n === undefined || n.video === undefined || n.video.uuid !== videoUUID + }) + } + } + + function emailNotificationFinder (email: object) { + const text = email['text'] + return text.indexOf(videoUUID) !== -1 && email['text'].indexOf('video-auto-blacklist/list') !== -1 + } + + await checkNotification(base, notificationChecker, emailNotificationFinder, type) +} + +async function checkNewBlacklistOnMyVideo ( + base: CheckerBaseParams, + videoUUID: string, + videoName: string, + blacklistType: 'blacklist' | 'unblacklist' +) { + const notificationType = blacklistType === 'blacklist' + ? UserNotificationType.BLACKLIST_ON_MY_VIDEO + : UserNotificationType.UNBLACKLIST_ON_MY_VIDEO + + function notificationChecker (notification: UserNotification) { + expect(notification).to.not.be.undefined + expect(notification.type).to.equal(notificationType) + + const video = blacklistType === 'blacklist' ? notification.videoBlacklist.video : notification.video + + checkVideo(video, videoName, videoUUID) + } + + function emailNotificationFinder (email: object) { + const text = email['text'] + return text.indexOf(videoUUID) !== -1 && text.indexOf(' ' + blacklistType) !== -1 + } + + await checkNotification(base, notificationChecker, emailNotificationFinder, 'presence') +} + +async function checkNewPeerTubeVersion (base: CheckerBaseParams, latestVersion: string, type: CheckerType) { + const notificationType = UserNotificationType.NEW_PEERTUBE_VERSION + + function notificationChecker (notification: UserNotification, type: CheckerType) { + if (type === 'presence') { + expect(notification).to.not.be.undefined + expect(notification.type).to.equal(notificationType) + + expect(notification.peertube).to.exist + expect(notification.peertube.latestVersion).to.equal(latestVersion) + } else { + expect(notification).to.satisfy((n: UserNotification) => { + return n === undefined || n.peertube === undefined || n.peertube.latestVersion !== latestVersion + }) + } + } + + function emailNotificationFinder (email: object) { + const text = email['text'] + + return text.includes(latestVersion) + } + + await checkNotification(base, notificationChecker, emailNotificationFinder, type) +} + +async function checkNewPluginVersion (base: CheckerBaseParams, pluginType: PluginType, pluginName: string, type: CheckerType) { + const notificationType = UserNotificationType.NEW_PLUGIN_VERSION + + function notificationChecker (notification: UserNotification, type: CheckerType) { + if (type === 'presence') { + expect(notification).to.not.be.undefined + expect(notification.type).to.equal(notificationType) + + expect(notification.plugin.name).to.equal(pluginName) + expect(notification.plugin.type).to.equal(pluginType) + } else { + expect(notification).to.satisfy((n: UserNotification) => { + return n === undefined || n.plugin === undefined || n.plugin.name !== pluginName + }) + } + } + + function emailNotificationFinder (email: object) { + const text = email['text'] + + return text.includes(pluginName) + } + + await checkNotification(base, notificationChecker, emailNotificationFinder, type) +} + +async function prepareNotificationsTest (serversCount = 3, overrideConfigArg: any = {}) { + const userNotifications: UserNotification[] = [] + const adminNotifications: UserNotification[] = [] + const adminNotificationsServer2: UserNotification[] = [] + const emails: object[] = [] + + const port = await MockSmtpServer.Instance.collectEmails(emails) + + const overrideConfig = { + smtp: { + hostname: 'localhost', + port + }, + signup: { + limit: 20 + } + } + const servers = await flushAndRunMultipleServers(serversCount, Object.assign(overrideConfig, overrideConfigArg)) + + await setAccessTokensToServers(servers) + + if (serversCount > 1) { + await doubleFollow(servers[0], servers[1]) + } + + const user = { + username: 'user_1', + password: 'super password' + } + await createUser({ + url: servers[0].url, + accessToken: servers[0].accessToken, + username: user.username, + password: user.password, + videoQuota: 10 * 1000 * 1000 + }) + const userAccessToken = await userLogin(servers[0], user) + + await servers[0].notificationsCommand.updateMySettings({ token: userAccessToken, settings: getAllNotificationsSettings() }) + await servers[0].notificationsCommand.updateMySettings({ settings: getAllNotificationsSettings() }) + + if (serversCount > 1) { + await servers[1].notificationsCommand.updateMySettings({ settings: getAllNotificationsSettings() }) + } + + { + const socket = servers[0].socketIOCommand.getUserNotificationSocket({ token: userAccessToken }) + socket.on('new-notification', n => userNotifications.push(n)) + } + { + const socket = servers[0].socketIOCommand.getUserNotificationSocket() + socket.on('new-notification', n => adminNotifications.push(n)) + } + + if (serversCount > 1) { + const socket = servers[1].socketIOCommand.getUserNotificationSocket() + socket.on('new-notification', n => adminNotificationsServer2.push(n)) + } + + const resChannel = await getMyUserInformation(servers[0].url, servers[0].accessToken) + const channelId = resChannel.body.videoChannels[0].id + + return { + userNotifications, + adminNotifications, + adminNotificationsServer2, + userAccessToken, + emails, + servers, + channelId + } +} + +// --------------------------------------------------------------------------- + +export { + getAllNotificationsSettings, + + CheckerBaseParams, + CheckerType, + checkNotification, + checkMyVideoImportIsFinished, + checkUserRegistered, + checkAutoInstanceFollowing, + checkVideoIsPublished, + checkNewVideoFromSubscription, + checkNewActorFollow, + checkNewCommentOnMyVideo, + checkNewBlacklistOnMyVideo, + checkCommentMention, + checkNewVideoAbuseForModerators, + checkVideoAutoBlacklistForModerators, + checkNewAbuseMessage, + checkAbuseStateChange, + checkNewInstanceFollower, + prepareNotificationsTest, + checkNewCommentAbuseForModerators, + checkNewAccountAbuseForModerators, + checkNewPeerTubeVersion, + checkNewPluginVersion +} diff --git a/shared/extra-utils/users/user-notifications.ts b/shared/extra-utils/users/user-notifications.ts deleted file mode 100644 index 961cfcc0f..000000000 --- a/shared/extra-utils/users/user-notifications.ts +++ /dev/null @@ -1,808 +0,0 @@ -/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ - -import { expect } from 'chai' -import { inspect } from 'util' -import { AbuseState, PluginType } from '@shared/models' -import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' -import { UserNotification, UserNotificationSetting, UserNotificationSettingValue, UserNotificationType } from '../../models/users' -import { MockSmtpServer } from '../mock-servers/mock-email' -import { makeGetRequest, makePostBodyRequest, makePutBodyRequest } from '../requests/requests' -import { doubleFollow } from '../server/follows' -import { flushAndRunMultipleServers, ServerInfo } from '../server/servers' -import { setAccessTokensToServers, userLogin } from './login' -import { createUser, getMyUserInformation } from './users' - -function updateMyNotificationSettings ( - url: string, - token: string, - settings: UserNotificationSetting, - statusCodeExpected = HttpStatusCode.NO_CONTENT_204 -) { - const path = '/api/v1/users/me/notification-settings' - - return makePutBodyRequest({ - url, - path, - token, - fields: settings, - statusCodeExpected - }) -} - -async function getUserNotifications ( - url: string, - token: string, - start: number, - count: number, - unread?: boolean, - sort = '-createdAt', - statusCodeExpected = HttpStatusCode.OK_200 -) { - const path = '/api/v1/users/me/notifications' - - return makeGetRequest({ - url, - path, - token, - query: { - start, - count, - sort, - unread - }, - statusCodeExpected - }) -} - -function markAsReadNotifications (url: string, token: string, ids: number[], statusCodeExpected = HttpStatusCode.NO_CONTENT_204) { - const path = '/api/v1/users/me/notifications/read' - - return makePostBodyRequest({ - url, - path, - token, - fields: { ids }, - statusCodeExpected - }) -} - -function markAsReadAllNotifications (url: string, token: string, statusCodeExpected = HttpStatusCode.NO_CONTENT_204) { - const path = '/api/v1/users/me/notifications/read-all' - - return makePostBodyRequest({ - url, - path, - token, - statusCodeExpected - }) -} - -async function getLastNotification (serverUrl: string, accessToken: string) { - const res = await getUserNotifications(serverUrl, accessToken, 0, 1, undefined, '-createdAt') - - if (res.body.total === 0) return undefined - - return res.body.data[0] as UserNotification -} - -type CheckerBaseParams = { - server: ServerInfo - emails: any[] - socketNotifications: UserNotification[] - token: string - check?: { web: boolean, mail: boolean } -} - -type CheckerType = 'presence' | 'absence' - -async function checkNotification ( - base: CheckerBaseParams, - notificationChecker: (notification: UserNotification, type: CheckerType) => void, - emailNotificationFinder: (email: object) => boolean, - checkType: CheckerType -) { - const check = base.check || { web: true, mail: true } - - if (check.web) { - const notification = await getLastNotification(base.server.url, base.token) - - if (notification || checkType !== 'absence') { - notificationChecker(notification, checkType) - } - - const socketNotification = base.socketNotifications.find(n => { - try { - notificationChecker(n, 'presence') - return true - } catch { - return false - } - }) - - if (checkType === 'presence') { - const obj = inspect(base.socketNotifications, { depth: 5 }) - expect(socketNotification, 'The socket notification is absent when it should be present. ' + obj).to.not.be.undefined - } else { - const obj = inspect(socketNotification, { depth: 5 }) - expect(socketNotification, 'The socket notification is present when it should not be present. ' + obj).to.be.undefined - } - } - - if (check.mail) { - // Last email - const email = base.emails - .slice() - .reverse() - .find(e => emailNotificationFinder(e)) - - if (checkType === 'presence') { - const emails = base.emails.map(e => e.text) - expect(email, 'The email is absent when is should be present. ' + inspect(emails)).to.not.be.undefined - } else { - expect(email, 'The email is present when is should not be present. ' + inspect(email)).to.be.undefined - } - } -} - -function checkVideo (video: any, videoName?: string, videoUUID?: string) { - if (videoName) { - expect(video.name).to.be.a('string') - expect(video.name).to.not.be.empty - expect(video.name).to.equal(videoName) - } - - if (videoUUID) { - expect(video.uuid).to.be.a('string') - expect(video.uuid).to.not.be.empty - expect(video.uuid).to.equal(videoUUID) - } - - expect(video.id).to.be.a('number') -} - -function checkActor (actor: any) { - expect(actor.displayName).to.be.a('string') - expect(actor.displayName).to.not.be.empty - expect(actor.host).to.not.be.undefined -} - -function checkComment (comment: any, commentId: number, threadId: number) { - expect(comment.id).to.equal(commentId) - expect(comment.threadId).to.equal(threadId) -} - -async function checkNewVideoFromSubscription (base: CheckerBaseParams, videoName: string, videoUUID: string, type: CheckerType) { - const notificationType = UserNotificationType.NEW_VIDEO_FROM_SUBSCRIPTION - - function notificationChecker (notification: UserNotification, type: CheckerType) { - if (type === 'presence') { - expect(notification).to.not.be.undefined - expect(notification.type).to.equal(notificationType) - - checkVideo(notification.video, videoName, videoUUID) - checkActor(notification.video.channel) - } else { - expect(notification).to.satisfy((n: UserNotification) => { - return n === undefined || n.type !== UserNotificationType.NEW_VIDEO_FROM_SUBSCRIPTION || n.video.name !== videoName - }) - } - } - - function emailNotificationFinder (email: object) { - const text = email['text'] - return text.indexOf(videoUUID) !== -1 && text.indexOf('Your subscription') !== -1 - } - - await checkNotification(base, notificationChecker, emailNotificationFinder, type) -} - -async function checkVideoIsPublished (base: CheckerBaseParams, videoName: string, videoUUID: string, type: CheckerType) { - const notificationType = UserNotificationType.MY_VIDEO_PUBLISHED - - function notificationChecker (notification: UserNotification, type: CheckerType) { - if (type === 'presence') { - expect(notification).to.not.be.undefined - expect(notification.type).to.equal(notificationType) - - checkVideo(notification.video, videoName, videoUUID) - checkActor(notification.video.channel) - } else { - expect(notification.video).to.satisfy(v => v === undefined || v.name !== videoName) - } - } - - function emailNotificationFinder (email: object) { - const text: string = email['text'] - return text.includes(videoUUID) && text.includes('Your video') - } - - await checkNotification(base, notificationChecker, emailNotificationFinder, type) -} - -async function checkMyVideoImportIsFinished ( - base: CheckerBaseParams, - videoName: string, - videoUUID: string, - url: string, - success: boolean, - type: CheckerType -) { - const notificationType = success ? UserNotificationType.MY_VIDEO_IMPORT_SUCCESS : UserNotificationType.MY_VIDEO_IMPORT_ERROR - - function notificationChecker (notification: UserNotification, type: CheckerType) { - if (type === 'presence') { - expect(notification).to.not.be.undefined - expect(notification.type).to.equal(notificationType) - - expect(notification.videoImport.targetUrl).to.equal(url) - - if (success) checkVideo(notification.videoImport.video, videoName, videoUUID) - } else { - expect(notification.videoImport).to.satisfy(i => i === undefined || i.targetUrl !== url) - } - } - - function emailNotificationFinder (email: object) { - const text: string = email['text'] - const toFind = success ? ' finished' : ' error' - - return text.includes(url) && text.includes(toFind) - } - - await checkNotification(base, notificationChecker, emailNotificationFinder, type) -} - -async function checkUserRegistered (base: CheckerBaseParams, username: string, type: CheckerType) { - const notificationType = UserNotificationType.NEW_USER_REGISTRATION - - function notificationChecker (notification: UserNotification, type: CheckerType) { - if (type === 'presence') { - expect(notification).to.not.be.undefined - expect(notification.type).to.equal(notificationType) - - checkActor(notification.account) - expect(notification.account.name).to.equal(username) - } else { - expect(notification).to.satisfy(n => n.type !== notificationType || n.account.name !== username) - } - } - - function emailNotificationFinder (email: object) { - const text: string = email['text'] - - return text.includes(' registered.') && text.includes(username) - } - - await checkNotification(base, notificationChecker, emailNotificationFinder, type) -} - -async function checkNewActorFollow ( - base: CheckerBaseParams, - followType: 'channel' | 'account', - followerName: string, - followerDisplayName: string, - followingDisplayName: string, - type: CheckerType -) { - const notificationType = UserNotificationType.NEW_FOLLOW - - function notificationChecker (notification: UserNotification, type: CheckerType) { - if (type === 'presence') { - expect(notification).to.not.be.undefined - expect(notification.type).to.equal(notificationType) - - checkActor(notification.actorFollow.follower) - expect(notification.actorFollow.follower.displayName).to.equal(followerDisplayName) - expect(notification.actorFollow.follower.name).to.equal(followerName) - expect(notification.actorFollow.follower.host).to.not.be.undefined - - const following = notification.actorFollow.following - expect(following.displayName).to.equal(followingDisplayName) - expect(following.type).to.equal(followType) - } else { - expect(notification).to.satisfy(n => { - return n.type !== notificationType || - (n.actorFollow.follower.name !== followerName && n.actorFollow.following !== followingDisplayName) - }) - } - } - - function emailNotificationFinder (email: object) { - const text: string = email['text'] - - return text.includes(followType) && text.includes(followingDisplayName) && text.includes(followerDisplayName) - } - - await checkNotification(base, notificationChecker, emailNotificationFinder, type) -} - -async function checkNewInstanceFollower (base: CheckerBaseParams, followerHost: string, type: CheckerType) { - const notificationType = UserNotificationType.NEW_INSTANCE_FOLLOWER - - function notificationChecker (notification: UserNotification, type: CheckerType) { - if (type === 'presence') { - expect(notification).to.not.be.undefined - expect(notification.type).to.equal(notificationType) - - checkActor(notification.actorFollow.follower) - expect(notification.actorFollow.follower.name).to.equal('peertube') - expect(notification.actorFollow.follower.host).to.equal(followerHost) - - expect(notification.actorFollow.following.name).to.equal('peertube') - } else { - expect(notification).to.satisfy(n => { - return n.type !== notificationType || n.actorFollow.follower.host !== followerHost - }) - } - } - - function emailNotificationFinder (email: object) { - const text: string = email['text'] - - return text.includes('instance has a new follower') && text.includes(followerHost) - } - - await checkNotification(base, notificationChecker, emailNotificationFinder, type) -} - -async function checkAutoInstanceFollowing (base: CheckerBaseParams, followerHost: string, followingHost: string, type: CheckerType) { - const notificationType = UserNotificationType.AUTO_INSTANCE_FOLLOWING - - function notificationChecker (notification: UserNotification, type: CheckerType) { - if (type === 'presence') { - expect(notification).to.not.be.undefined - expect(notification.type).to.equal(notificationType) - - const following = notification.actorFollow.following - checkActor(following) - expect(following.name).to.equal('peertube') - expect(following.host).to.equal(followingHost) - - expect(notification.actorFollow.follower.name).to.equal('peertube') - expect(notification.actorFollow.follower.host).to.equal(followerHost) - } else { - expect(notification).to.satisfy(n => { - return n.type !== notificationType || n.actorFollow.following.host !== followingHost - }) - } - } - - function emailNotificationFinder (email: object) { - const text: string = email['text'] - - return text.includes(' automatically followed a new instance') && text.includes(followingHost) - } - - await checkNotification(base, notificationChecker, emailNotificationFinder, type) -} - -async function checkCommentMention ( - base: CheckerBaseParams, - uuid: string, - commentId: number, - threadId: number, - byAccountDisplayName: string, - type: CheckerType -) { - const notificationType = UserNotificationType.COMMENT_MENTION - - function notificationChecker (notification: UserNotification, type: CheckerType) { - if (type === 'presence') { - expect(notification).to.not.be.undefined - expect(notification.type).to.equal(notificationType) - - checkComment(notification.comment, commentId, threadId) - checkActor(notification.comment.account) - expect(notification.comment.account.displayName).to.equal(byAccountDisplayName) - - checkVideo(notification.comment.video, undefined, uuid) - } else { - expect(notification).to.satisfy(n => n.type !== notificationType || n.comment.id !== commentId) - } - } - - function emailNotificationFinder (email: object) { - const text: string = email['text'] - - return text.includes(' mentioned ') && text.includes(uuid) && text.includes(byAccountDisplayName) - } - - await checkNotification(base, notificationChecker, emailNotificationFinder, type) -} - -let lastEmailCount = 0 - -async function checkNewCommentOnMyVideo (base: CheckerBaseParams, uuid: string, commentId: number, threadId: number, type: CheckerType) { - const notificationType = UserNotificationType.NEW_COMMENT_ON_MY_VIDEO - - function notificationChecker (notification: UserNotification, type: CheckerType) { - if (type === 'presence') { - expect(notification).to.not.be.undefined - expect(notification.type).to.equal(notificationType) - - checkComment(notification.comment, commentId, threadId) - checkActor(notification.comment.account) - checkVideo(notification.comment.video, undefined, uuid) - } else { - expect(notification).to.satisfy((n: UserNotification) => { - return n === undefined || n.comment === undefined || n.comment.id !== commentId - }) - } - } - - const commentUrl = `http://localhost:${base.server.port}/w/${uuid};threadId=${threadId}` - - function emailNotificationFinder (email: object) { - return email['text'].indexOf(commentUrl) !== -1 - } - - await checkNotification(base, notificationChecker, emailNotificationFinder, type) - - if (type === 'presence') { - // We cannot detect email duplicates, so check we received another email - expect(base.emails).to.have.length.above(lastEmailCount) - lastEmailCount = base.emails.length - } -} - -async function checkNewVideoAbuseForModerators (base: CheckerBaseParams, videoUUID: string, videoName: string, type: CheckerType) { - const notificationType = UserNotificationType.NEW_ABUSE_FOR_MODERATORS - - function notificationChecker (notification: UserNotification, type: CheckerType) { - if (type === 'presence') { - expect(notification).to.not.be.undefined - expect(notification.type).to.equal(notificationType) - - expect(notification.abuse.id).to.be.a('number') - checkVideo(notification.abuse.video, videoName, videoUUID) - } else { - expect(notification).to.satisfy((n: UserNotification) => { - return n === undefined || n.abuse === undefined || n.abuse.video.uuid !== videoUUID - }) - } - } - - function emailNotificationFinder (email: object) { - const text = email['text'] - return text.indexOf(videoUUID) !== -1 && text.indexOf('abuse') !== -1 - } - - await checkNotification(base, notificationChecker, emailNotificationFinder, type) -} - -async function checkNewAbuseMessage (base: CheckerBaseParams, abuseId: number, message: string, toEmail: string, type: CheckerType) { - const notificationType = UserNotificationType.ABUSE_NEW_MESSAGE - - function notificationChecker (notification: UserNotification, type: CheckerType) { - if (type === 'presence') { - expect(notification).to.not.be.undefined - expect(notification.type).to.equal(notificationType) - - expect(notification.abuse.id).to.equal(abuseId) - } else { - expect(notification).to.satisfy((n: UserNotification) => { - return n === undefined || n.type !== notificationType || n.abuse === undefined || n.abuse.id !== abuseId - }) - } - } - - function emailNotificationFinder (email: object) { - const text = email['text'] - const to = email['to'].filter(t => t.address === toEmail) - - return text.indexOf(message) !== -1 && to.length !== 0 - } - - await checkNotification(base, notificationChecker, emailNotificationFinder, type) -} - -async function checkAbuseStateChange (base: CheckerBaseParams, abuseId: number, state: AbuseState, type: CheckerType) { - const notificationType = UserNotificationType.ABUSE_STATE_CHANGE - - function notificationChecker (notification: UserNotification, type: CheckerType) { - if (type === 'presence') { - expect(notification).to.not.be.undefined - expect(notification.type).to.equal(notificationType) - - expect(notification.abuse.id).to.equal(abuseId) - expect(notification.abuse.state).to.equal(state) - } else { - expect(notification).to.satisfy((n: UserNotification) => { - return n === undefined || n.abuse === undefined || n.abuse.id !== abuseId - }) - } - } - - function emailNotificationFinder (email: object) { - const text = email['text'] - - const contains = state === AbuseState.ACCEPTED - ? ' accepted' - : ' rejected' - - return text.indexOf(contains) !== -1 - } - - await checkNotification(base, notificationChecker, emailNotificationFinder, type) -} - -async function checkNewCommentAbuseForModerators (base: CheckerBaseParams, videoUUID: string, videoName: string, type: CheckerType) { - const notificationType = UserNotificationType.NEW_ABUSE_FOR_MODERATORS - - function notificationChecker (notification: UserNotification, type: CheckerType) { - if (type === 'presence') { - expect(notification).to.not.be.undefined - expect(notification.type).to.equal(notificationType) - - expect(notification.abuse.id).to.be.a('number') - checkVideo(notification.abuse.comment.video, videoName, videoUUID) - } else { - expect(notification).to.satisfy((n: UserNotification) => { - return n === undefined || n.abuse === undefined || n.abuse.comment.video.uuid !== videoUUID - }) - } - } - - function emailNotificationFinder (email: object) { - const text = email['text'] - return text.indexOf(videoUUID) !== -1 && text.indexOf('abuse') !== -1 - } - - await checkNotification(base, notificationChecker, emailNotificationFinder, type) -} - -async function checkNewAccountAbuseForModerators (base: CheckerBaseParams, displayName: string, type: CheckerType) { - const notificationType = UserNotificationType.NEW_ABUSE_FOR_MODERATORS - - function notificationChecker (notification: UserNotification, type: CheckerType) { - if (type === 'presence') { - expect(notification).to.not.be.undefined - expect(notification.type).to.equal(notificationType) - - expect(notification.abuse.id).to.be.a('number') - expect(notification.abuse.account.displayName).to.equal(displayName) - } else { - expect(notification).to.satisfy((n: UserNotification) => { - return n === undefined || n.abuse === undefined || n.abuse.account.displayName !== displayName - }) - } - } - - function emailNotificationFinder (email: object) { - const text = email['text'] - return text.indexOf(displayName) !== -1 && text.indexOf('abuse') !== -1 - } - - await checkNotification(base, notificationChecker, emailNotificationFinder, type) -} - -async function checkVideoAutoBlacklistForModerators (base: CheckerBaseParams, videoUUID: string, videoName: string, type: CheckerType) { - const notificationType = UserNotificationType.VIDEO_AUTO_BLACKLIST_FOR_MODERATORS - - function notificationChecker (notification: UserNotification, type: CheckerType) { - if (type === 'presence') { - expect(notification).to.not.be.undefined - expect(notification.type).to.equal(notificationType) - - expect(notification.videoBlacklist.video.id).to.be.a('number') - checkVideo(notification.videoBlacklist.video, videoName, videoUUID) - } else { - expect(notification).to.satisfy((n: UserNotification) => { - return n === undefined || n.video === undefined || n.video.uuid !== videoUUID - }) - } - } - - function emailNotificationFinder (email: object) { - const text = email['text'] - return text.indexOf(videoUUID) !== -1 && email['text'].indexOf('video-auto-blacklist/list') !== -1 - } - - await checkNotification(base, notificationChecker, emailNotificationFinder, type) -} - -async function checkNewBlacklistOnMyVideo ( - base: CheckerBaseParams, - videoUUID: string, - videoName: string, - blacklistType: 'blacklist' | 'unblacklist' -) { - const notificationType = blacklistType === 'blacklist' - ? UserNotificationType.BLACKLIST_ON_MY_VIDEO - : UserNotificationType.UNBLACKLIST_ON_MY_VIDEO - - function notificationChecker (notification: UserNotification) { - expect(notification).to.not.be.undefined - expect(notification.type).to.equal(notificationType) - - const video = blacklistType === 'blacklist' ? notification.videoBlacklist.video : notification.video - - checkVideo(video, videoName, videoUUID) - } - - function emailNotificationFinder (email: object) { - const text = email['text'] - return text.indexOf(videoUUID) !== -1 && text.indexOf(' ' + blacklistType) !== -1 - } - - await checkNotification(base, notificationChecker, emailNotificationFinder, 'presence') -} - -async function checkNewPeerTubeVersion (base: CheckerBaseParams, latestVersion: string, type: CheckerType) { - const notificationType = UserNotificationType.NEW_PEERTUBE_VERSION - - function notificationChecker (notification: UserNotification, type: CheckerType) { - if (type === 'presence') { - expect(notification).to.not.be.undefined - expect(notification.type).to.equal(notificationType) - - expect(notification.peertube).to.exist - expect(notification.peertube.latestVersion).to.equal(latestVersion) - } else { - expect(notification).to.satisfy((n: UserNotification) => { - return n === undefined || n.peertube === undefined || n.peertube.latestVersion !== latestVersion - }) - } - } - - function emailNotificationFinder (email: object) { - const text = email['text'] - - return text.includes(latestVersion) - } - - await checkNotification(base, notificationChecker, emailNotificationFinder, type) -} - -async function checkNewPluginVersion (base: CheckerBaseParams, pluginType: PluginType, pluginName: string, type: CheckerType) { - const notificationType = UserNotificationType.NEW_PLUGIN_VERSION - - function notificationChecker (notification: UserNotification, type: CheckerType) { - if (type === 'presence') { - expect(notification).to.not.be.undefined - expect(notification.type).to.equal(notificationType) - - expect(notification.plugin.name).to.equal(pluginName) - expect(notification.plugin.type).to.equal(pluginType) - } else { - expect(notification).to.satisfy((n: UserNotification) => { - return n === undefined || n.plugin === undefined || n.plugin.name !== pluginName - }) - } - } - - function emailNotificationFinder (email: object) { - const text = email['text'] - - return text.includes(pluginName) - } - - await checkNotification(base, notificationChecker, emailNotificationFinder, type) -} - -function getAllNotificationsSettings (): UserNotificationSetting { - return { - newVideoFromSubscription: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL, - newCommentOnMyVideo: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL, - abuseAsModerator: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL, - videoAutoBlacklistAsModerator: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL, - blacklistOnMyVideo: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL, - myVideoImportFinished: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL, - myVideoPublished: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL, - commentMention: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL, - newFollow: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL, - newUserRegistration: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL, - newInstanceFollower: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL, - abuseNewMessage: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL, - abuseStateChange: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL, - autoInstanceFollowing: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL, - newPeerTubeVersion: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL, - newPluginVersion: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL - } -} - -async function prepareNotificationsTest (serversCount = 3, overrideConfigArg: any = {}) { - const userNotifications: UserNotification[] = [] - const adminNotifications: UserNotification[] = [] - const adminNotificationsServer2: UserNotification[] = [] - const emails: object[] = [] - - const port = await MockSmtpServer.Instance.collectEmails(emails) - - const overrideConfig = { - smtp: { - hostname: 'localhost', - port - }, - signup: { - limit: 20 - } - } - const servers = await flushAndRunMultipleServers(serversCount, Object.assign(overrideConfig, overrideConfigArg)) - - await setAccessTokensToServers(servers) - - if (serversCount > 1) { - await doubleFollow(servers[0], servers[1]) - } - - const user = { - username: 'user_1', - password: 'super password' - } - await createUser({ - url: servers[0].url, - accessToken: servers[0].accessToken, - username: user.username, - password: user.password, - videoQuota: 10 * 1000 * 1000 - }) - const userAccessToken = await userLogin(servers[0], user) - - await updateMyNotificationSettings(servers[0].url, userAccessToken, getAllNotificationsSettings()) - await updateMyNotificationSettings(servers[0].url, servers[0].accessToken, getAllNotificationsSettings()) - - if (serversCount > 1) { - await updateMyNotificationSettings(servers[1].url, servers[1].accessToken, getAllNotificationsSettings()) - } - - { - const socket = servers[0].socketIOCommand.getUserNotificationSocket({ token: userAccessToken }) - socket.on('new-notification', n => userNotifications.push(n)) - } - { - const socket = servers[0].socketIOCommand.getUserNotificationSocket() - socket.on('new-notification', n => adminNotifications.push(n)) - } - - if (serversCount > 1) { - const socket = servers[1].socketIOCommand.getUserNotificationSocket() - socket.on('new-notification', n => adminNotificationsServer2.push(n)) - } - - const resChannel = await getMyUserInformation(servers[0].url, servers[0].accessToken) - const channelId = resChannel.body.videoChannels[0].id - - return { - userNotifications, - adminNotifications, - adminNotificationsServer2, - userAccessToken, - emails, - servers, - channelId - } -} - -// --------------------------------------------------------------------------- - -export { - CheckerBaseParams, - CheckerType, - getAllNotificationsSettings, - checkNotification, - markAsReadAllNotifications, - checkMyVideoImportIsFinished, - checkUserRegistered, - checkAutoInstanceFollowing, - checkVideoIsPublished, - checkNewVideoFromSubscription, - checkNewActorFollow, - checkNewCommentOnMyVideo, - checkNewBlacklistOnMyVideo, - checkCommentMention, - updateMyNotificationSettings, - checkNewVideoAbuseForModerators, - checkVideoAutoBlacklistForModerators, - checkNewAbuseMessage, - checkAbuseStateChange, - getUserNotifications, - markAsReadNotifications, - getLastNotification, - checkNewInstanceFollower, - prepareNotificationsTest, - checkNewCommentAbuseForModerators, - checkNewAccountAbuseForModerators, - checkNewPeerTubeVersion, - checkNewPluginVersion -} diff --git a/shared/extra-utils/videos/streaming-playlists-command.ts b/shared/extra-utils/videos/streaming-playlists-command.ts index b109597c9..fab3eb556 100644 --- a/shared/extra-utils/videos/streaming-playlists-command.ts +++ b/shared/extra-utils/videos/streaming-playlists-command.ts @@ -21,7 +21,7 @@ export class StreamingPlaylistsCommand extends AbstractCommand { url: string range?: string }) { - return unwrapText(this.getRawRequest({ + return unwrapBody(this.getRawRequest({ ...options, url: options.url, -- cgit v1.2.3 From 5e2fea3ab9357c228b5d21166092f9a2368e258e Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Mon, 12 Jul 2021 16:06:57 +0200 Subject: Fix search tests --- server/tools/test-live.ts | 2 +- shared/extra-utils/search/search-command.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/server/tools/test-live.ts b/server/tools/test-live.ts index 3d1198d9c..7004e98e8 100644 --- a/server/tools/test-live.ts +++ b/server/tools/test-live.ts @@ -38,7 +38,7 @@ async function run () { const server = await flushAndRunServer(1, {}, [], { hideLogs: false, execArgv: [ '--inspect' ] }) - const cleanup = async () => { + const cleanup = async () => { console.log('Killing server') await killallServers([ server ]) } diff --git a/shared/extra-utils/search/search-command.ts b/shared/extra-utils/search/search-command.ts index b6054f093..7539a21ec 100644 --- a/shared/extra-utils/search/search-command.ts +++ b/shared/extra-utils/search/search-command.ts @@ -90,7 +90,7 @@ export class SearchCommand extends AbstractCommand { ...options, path, - query: { sort: '-publishedAt', ...search }, + query: search, implicitToken: false, defaultExpectedStatus: HttpStatusCode.OK_200 }) -- cgit v1.2.3 From 0d8ecb7592577f54012413a2b5a9b159cfc90399 Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Tue, 13 Jul 2021 08:33:02 +0200 Subject: Fix NSFW tests --- server/tests/api/videos/multiple-servers.ts | 1 + server/tests/api/videos/video-nsfw.ts | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/server/tests/api/videos/multiple-servers.ts b/server/tests/api/videos/multiple-servers.ts index 2148d8e1c..1b6f0f48a 100644 --- a/server/tests/api/videos/multiple-servers.ts +++ b/server/tests/api/videos/multiple-servers.ts @@ -582,6 +582,7 @@ describe('Test multiple servers', function () { await waitJobs(servers) await wait(5000) + await waitJobs(servers) let baseVideos = null for (const server of servers) { diff --git a/server/tests/api/videos/video-nsfw.ts b/server/tests/api/videos/video-nsfw.ts index 5f30939cc..c9c3792eb 100644 --- a/server/tests/api/videos/video-nsfw.ts +++ b/server/tests/api/videos/video-nsfw.ts @@ -43,7 +43,7 @@ describe('Test video NSFW policy', function () { if (token) { promises = [ getVideosListWithToken(server.url, token, query).then(res => res.body), - server.searchCommand.advancedVideoSearch({ token, search: { search: 'n', ...query } }), + server.searchCommand.advancedVideoSearch({ token, search: { search: 'n', sort: '-publishedAt', ...query } }), getAccountVideos(server.url, token, accountName, 0, 5, undefined, query).then(res => res.body), getVideoChannelVideos(server.url, token, videoChannelName, 0, 5, undefined, query).then(res => res.body) ] @@ -60,7 +60,7 @@ describe('Test video NSFW policy', function () { promises = [ getVideosList(server.url).then(res => res.body), - server.searchCommand.searchVideos({ search: 'n' }), + server.searchCommand.searchVideos({ search: 'n', sort: '-publishedAt' }), getAccountVideos(server.url, undefined, accountName, 0, 5).then(res => res.body), getVideoChannelVideos(server.url, undefined, videoChannelName, 0, 5).then(res => res.body) ] -- cgit v1.2.3 From 6c5065a011b099618681a37bd77eaa7bd3db752e Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Tue, 13 Jul 2021 09:43:59 +0200 Subject: Introduce server commands --- server/tests/api/activitypub/helpers.ts | 5 +- server/tests/api/check-params/config.ts | 28 ++-- server/tests/api/check-params/live.ts | 29 ++-- server/tests/api/check-params/plugins.ts | 7 +- server/tests/api/check-params/search.ts | 55 ++++--- .../tests/api/check-params/user-notifications.ts | 20 +-- server/tests/api/check-params/users.ts | 77 +++++----- server/tests/api/check-params/video-channels.ts | 31 ++-- server/tests/api/check-params/video-imports.ts | 29 ++-- server/tests/api/check-params/video-playlists.ts | 5 +- server/tests/api/check-params/videos.ts | 75 ++++----- server/tests/api/live/live.ts | 3 +- .../api/notifications/moderation-notifications.ts | 13 +- .../tests/api/notifications/notifications-api.ts | 11 +- server/tests/api/redundancy/manage-redundancy.ts | 7 +- .../tests/api/redundancy/redundancy-constraints.ts | 11 +- server/tests/api/redundancy/redundancy.ts | 36 ++--- server/tests/api/search/search-index.ts | 24 +-- server/tests/api/search/search-videos.ts | 46 +++--- server/tests/api/server/handle-down.ts | 9 +- server/tests/api/server/logs.ts | 5 +- server/tests/api/server/plugins.ts | 5 +- server/tests/api/users/users-multiple-servers.ts | 2 +- server/tests/api/videos/audio-only.ts | 5 +- server/tests/api/videos/multiple-servers.ts | 4 +- server/tests/api/videos/resumable-upload.ts | 5 +- server/tests/api/videos/single-server.ts | 2 +- server/tests/api/videos/video-captions.ts | 2 +- server/tests/api/videos/video-imports.ts | 13 +- server/tests/api/videos/video-transcoder.ts | 22 ++- server/tests/cli/optimize-old-videos.ts | 3 +- server/tests/cli/prune-storage.ts | 31 ++-- server/tests/cli/regenerate-thumbnails.ts | 5 +- server/tests/plugins/action-hooks.ts | 5 +- server/tests/plugins/external-auth.ts | 7 +- server/tests/plugins/filter-hooks.ts | 39 +++-- server/tests/plugins/id-and-pass-auth.ts | 13 +- server/tests/plugins/plugin-helpers.ts | 19 ++- server/tests/plugins/plugin-storage.ts | 17 +-- server/tests/plugins/plugin-transcoding.ts | 3 +- shared/extra-utils/miscs/checks.ts | 46 ++++++ shared/extra-utils/miscs/generate.ts | 61 ++++++++ shared/extra-utils/miscs/index.ts | 6 +- shared/extra-utils/miscs/miscs.ts | 170 --------------------- shared/extra-utils/miscs/sql-command.ts | 2 +- shared/extra-utils/miscs/stubs.ts | 7 - shared/extra-utils/miscs/tests.ts | 62 ++++++++ shared/extra-utils/miscs/webtorrent.ts | 16 ++ shared/extra-utils/mock-servers/mock-email.ts | 4 +- shared/extra-utils/requests/check-api-params.ts | 11 +- shared/extra-utils/requests/requests.ts | 4 +- shared/extra-utils/server/directories.ts | 34 +++++ shared/extra-utils/server/index.ts | 2 + shared/extra-utils/server/jobs.ts | 2 +- shared/extra-utils/server/plugins-command.ts | 3 +- shared/extra-utils/server/servers-command.ts | 81 ++++++++++ shared/extra-utils/server/servers.ts | 108 ++----------- shared/extra-utils/shared/abstract-command.ts | 2 +- shared/extra-utils/videos/captions-command.ts | 4 +- shared/extra-utils/videos/live-command.ts | 7 +- shared/extra-utils/videos/live.ts | 4 +- shared/extra-utils/videos/playlists.ts | 2 +- shared/extra-utils/videos/videos.ts | 30 +--- 63 files changed, 688 insertions(+), 708 deletions(-) create mode 100644 shared/extra-utils/miscs/checks.ts create mode 100644 shared/extra-utils/miscs/generate.ts delete mode 100644 shared/extra-utils/miscs/miscs.ts delete mode 100644 shared/extra-utils/miscs/stubs.ts create mode 100644 shared/extra-utils/miscs/tests.ts create mode 100644 shared/extra-utils/miscs/webtorrent.ts create mode 100644 shared/extra-utils/server/directories.ts create mode 100644 shared/extra-utils/server/servers-command.ts diff --git a/server/tests/api/activitypub/helpers.ts b/server/tests/api/activitypub/helpers.ts index 66d7631b7..57b1cab23 100644 --- a/server/tests/api/activitypub/helpers.ts +++ b/server/tests/api/activitypub/helpers.ts @@ -2,11 +2,10 @@ import 'mocha' import { expect } from 'chai' -import { buildRequestStub } from '../../../../shared/extra-utils/miscs/stubs' -import { isHTTPSignatureVerified, isJsonLDSignatureVerified, parseHTTPSignature } from '../../../helpers/peertube-crypto' import { cloneDeep } from 'lodash' +import { buildAbsoluteFixturePath, buildRequestStub } from '@shared/extra-utils' import { buildSignedActivity } from '../../../helpers/activitypub' -import { buildAbsoluteFixturePath } from '@shared/extra-utils' +import { isHTTPSignatureVerified, isJsonLDSignatureVerified, parseHTTPSignature } from '../../../helpers/peertube-crypto' describe('Test activity pub helpers', function () { describe('When checking the Linked Signature', function () { diff --git a/server/tests/api/check-params/config.ts b/server/tests/api/check-params/config.ts index 9549070ef..291de93ea 100644 --- a/server/tests/api/check-params/config.ts +++ b/server/tests/api/check-params/config.ts @@ -1,22 +1,20 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ -import { omit } from 'lodash' import 'mocha' -import { CustomConfig } from '../../../../shared/models/server/custom-config.model' - +import { omit } from 'lodash' +import { HttpStatusCode } from '@shared/core-utils' import { cleanupTests, createUser, flushAndRunServer, - immutableAssign, makeDeleteRequest, makeGetRequest, makePutBodyRequest, ServerInfo, setAccessTokensToServers, userLogin -} from '../../../../shared/extra-utils' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' +} from '@shared/extra-utils' +import { CustomConfig } from '@shared/models' describe('Test config API validators', function () { const path = '/api/v1/config/custom' @@ -265,11 +263,13 @@ describe('Test config API validators', function () { }) it('Should fail with a bad default NSFW policy', async function () { - const newUpdateParams = immutableAssign(updateParams, { + const newUpdateParams = { + ...updateParams, + instance: { defaultNSFWPolicy: 'hello' } - }) + } await makePutBodyRequest({ url: server.url, @@ -282,13 +282,15 @@ describe('Test config API validators', function () { it('Should fail if email disabled and signup requires email verification', async function () { // opposite scenario - success when enable enabled - covered via tests/api/users/user-verification.ts - const newUpdateParams = immutableAssign(updateParams, { + const newUpdateParams = { + ...updateParams, + signup: { enabled: true, limit: 5, requiresEmailVerification: true } - }) + } await makePutBodyRequest({ url: server.url, @@ -300,7 +302,9 @@ describe('Test config API validators', function () { }) it('Should fail with a disabled webtorrent & hls transcoding', async function () { - const newUpdateParams = immutableAssign(updateParams, { + const newUpdateParams = { + ...updateParams, + transcoding: { hls: { enabled: false @@ -309,7 +313,7 @@ describe('Test config API validators', function () { enabled: false } } - }) + } await makePutBodyRequest({ url: server.url, diff --git a/server/tests/api/check-params/live.ts b/server/tests/api/check-params/live.ts index d851d258d..394967285 100644 --- a/server/tests/api/check-params/live.ts +++ b/server/tests/api/check-params/live.ts @@ -10,7 +10,6 @@ import { createUser, flushAndRunServer, getMyUserInformation, - immutableAssign, LiveCommand, makePostBodyRequest, makeUploadRequest, @@ -97,37 +96,37 @@ describe('Test video lives API validator', function () { }) it('Should fail with a long name', async function () { - const fields = immutableAssign(baseCorrectParams, { name: 'super'.repeat(65) }) + const fields = { ...baseCorrectParams, name: 'super'.repeat(65) } await makePostBodyRequest({ url: server.url, path, token: server.accessToken, fields }) }) it('Should fail with a bad category', async function () { - const fields = immutableAssign(baseCorrectParams, { category: 125 }) + const fields = { ...baseCorrectParams, category: 125 } await makePostBodyRequest({ url: server.url, path, token: server.accessToken, fields }) }) it('Should fail with a bad licence', async function () { - const fields = immutableAssign(baseCorrectParams, { licence: 125 }) + const fields = { ...baseCorrectParams, licence: 125 } await makePostBodyRequest({ url: server.url, path, token: server.accessToken, fields }) }) it('Should fail with a bad language', async function () { - const fields = immutableAssign(baseCorrectParams, { language: 'a'.repeat(15) }) + const fields = { ...baseCorrectParams, language: 'a'.repeat(15) } await makePostBodyRequest({ url: server.url, path, token: server.accessToken, fields }) }) it('Should fail with a long description', async function () { - const fields = immutableAssign(baseCorrectParams, { description: 'super'.repeat(2500) }) + const fields = { ...baseCorrectParams, description: 'super'.repeat(2500) } await makePostBodyRequest({ url: server.url, path, token: server.accessToken, fields }) }) it('Should fail with a long support text', async function () { - const fields = immutableAssign(baseCorrectParams, { support: 'super'.repeat(201) }) + const fields = { ...baseCorrectParams, support: 'super'.repeat(201) } await makePostBodyRequest({ url: server.url, path, token: server.accessToken, fields }) }) @@ -139,7 +138,7 @@ describe('Test video lives API validator', function () { }) it('Should fail with a bad channel', async function () { - const fields = immutableAssign(baseCorrectParams, { channelId: 545454 }) + const fields = { ...baseCorrectParams, channelId: 545454 } await makePostBodyRequest({ url: server.url, path, token: server.accessToken, fields }) }) @@ -155,25 +154,25 @@ describe('Test video lives API validator', function () { const res = await getMyUserInformation(server.url, accessTokenUser) const customChannelId = res.body.videoChannels[0].id - const fields = immutableAssign(baseCorrectParams, { channelId: customChannelId }) + const fields = { ...baseCorrectParams, channelId: customChannelId } await makePostBodyRequest({ url: server.url, path, token: userAccessToken, fields }) }) it('Should fail with too many tags', async function () { - const fields = immutableAssign(baseCorrectParams, { tags: [ 'tag1', 'tag2', 'tag3', 'tag4', 'tag5', 'tag6' ] }) + const fields = { ...baseCorrectParams, tags: [ 'tag1', 'tag2', 'tag3', 'tag4', 'tag5', 'tag6' ] } await makePostBodyRequest({ url: server.url, path, token: server.accessToken, fields }) }) it('Should fail with a tag length too low', async function () { - const fields = immutableAssign(baseCorrectParams, { tags: [ 'tag1', 't' ] }) + const fields = { ...baseCorrectParams, tags: [ 'tag1', 't' ] } await makePostBodyRequest({ url: server.url, path, token: server.accessToken, fields }) }) it('Should fail with a tag length too big', async function () { - const fields = immutableAssign(baseCorrectParams, { tags: [ 'tag1', 'my_super_tag_too_long_long_long_long_long_long' ] }) + const fields = { ...baseCorrectParams, tags: [ 'tag1', 'my_super_tag_too_long_long_long_long_long_long' ] } await makePostBodyRequest({ url: server.url, path, token: server.accessToken, fields }) }) @@ -215,7 +214,7 @@ describe('Test video lives API validator', function () { }) it('Should fail with save replay and permanent live set to true', async function () { - const fields = immutableAssign(baseCorrectParams, { saveReplay: true, permanentLive: true }) + const fields = { ...baseCorrectParams, saveReplay: true, permanentLive: true } await makePostBodyRequest({ url: server.url, path, token: server.accessToken, fields }) }) @@ -253,7 +252,7 @@ describe('Test video lives API validator', function () { }) it('Should forbid to save replay if not enabled by the admin', async function () { - const fields = immutableAssign(baseCorrectParams, { saveReplay: true }) + const fields = { ...baseCorrectParams, saveReplay: true } await server.configCommand.updateCustomSubConfig({ newConfig: { @@ -274,7 +273,7 @@ describe('Test video lives API validator', function () { }) it('Should allow to save replay if enabled by the admin', async function () { - const fields = immutableAssign(baseCorrectParams, { saveReplay: true }) + const fields = { ...baseCorrectParams, saveReplay: true } await server.configCommand.updateCustomSubConfig({ newConfig: { diff --git a/server/tests/api/check-params/plugins.ts b/server/tests/api/check-params/plugins.ts index d372221d0..8509b8ac5 100644 --- a/server/tests/api/check-params/plugins.ts +++ b/server/tests/api/check-params/plugins.ts @@ -9,7 +9,6 @@ import { cleanupTests, createUser, flushAndRunServer, - immutableAssign, makeGetRequest, makePostBodyRequest, makePutBodyRequest, @@ -200,7 +199,7 @@ describe('Test server plugins API validators', function () { }) it('Should fail with an invalid plugin type', async function () { - const query = immutableAssign(baseQuery, { pluginType: 5 }) + const query = { ...baseQuery, pluginType: 5 } await makeGetRequest({ url: server.url, @@ -211,7 +210,7 @@ describe('Test server plugins API validators', function () { }) it('Should fail with an invalid current peertube engine', async function () { - const query = immutableAssign(baseQuery, { currentPeerTubeEngine: '1.0' }) + const query = { ...baseQuery, currentPeerTubeEngine: '1.0' } await makeGetRequest({ url: server.url, @@ -271,7 +270,7 @@ describe('Test server plugins API validators', function () { }) it('Should fail with an invalid plugin type', async function () { - const query = immutableAssign(baseQuery, { pluginType: 5 }) + const query = { ...baseQuery, pluginType: 5 } await makeGetRequest({ url: server.url, diff --git a/server/tests/api/check-params/search.ts b/server/tests/api/check-params/search.ts index 4a2fc1197..7973c112f 100644 --- a/server/tests/api/check-params/search.ts +++ b/server/tests/api/check-params/search.ts @@ -8,7 +8,6 @@ import { checkBadStartPagination, cleanupTests, flushAndRunServer, - immutableAssign, makeGetRequest, ServerInfo, setAccessTokensToServers @@ -63,78 +62,78 @@ describe('Test videos API validator', function () { }) it('Should fail with an invalid category', async function () { - const customQuery1 = immutableAssign(query, { categoryOneOf: [ 'aa', 'b' ] }) + const customQuery1 = { ...query, categoryOneOf: [ 'aa', 'b' ] } await makeGetRequest({ url: server.url, path, query: customQuery1, statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) - const customQuery2 = immutableAssign(query, { categoryOneOf: 'a' }) + const customQuery2 = { ...query, categoryOneOf: 'a' } await makeGetRequest({ url: server.url, path, query: customQuery2, statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) }) it('Should succeed with a valid category', async function () { - const customQuery1 = immutableAssign(query, { categoryOneOf: [ 1, 7 ] }) + const customQuery1 = { ...query, categoryOneOf: [ 1, 7 ] } await makeGetRequest({ url: server.url, path, query: customQuery1, statusCodeExpected: HttpStatusCode.OK_200 }) - const customQuery2 = immutableAssign(query, { categoryOneOf: 1 }) + const customQuery2 = { ...query, categoryOneOf: 1 } await makeGetRequest({ url: server.url, path, query: customQuery2, statusCodeExpected: HttpStatusCode.OK_200 }) }) it('Should fail with an invalid licence', async function () { - const customQuery1 = immutableAssign(query, { licenceOneOf: [ 'aa', 'b' ] }) + const customQuery1 = { ...query, licenceOneOf: [ 'aa', 'b' ] } await makeGetRequest({ url: server.url, path, query: customQuery1, statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) - const customQuery2 = immutableAssign(query, { licenceOneOf: 'a' }) + const customQuery2 = { ...query, licenceOneOf: 'a' } await makeGetRequest({ url: server.url, path, query: customQuery2, statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) }) it('Should succeed with a valid licence', async function () { - const customQuery1 = immutableAssign(query, { licenceOneOf: [ 1, 2 ] }) + const customQuery1 = { ...query, licenceOneOf: [ 1, 2 ] } await makeGetRequest({ url: server.url, path, query: customQuery1, statusCodeExpected: HttpStatusCode.OK_200 }) - const customQuery2 = immutableAssign(query, { licenceOneOf: 1 }) + const customQuery2 = { ...query, licenceOneOf: 1 } await makeGetRequest({ url: server.url, path, query: customQuery2, statusCodeExpected: HttpStatusCode.OK_200 }) }) it('Should succeed with a valid language', async function () { - const customQuery1 = immutableAssign(query, { languageOneOf: [ 'fr', 'en' ] }) + const customQuery1 = { ...query, languageOneOf: [ 'fr', 'en' ] } await makeGetRequest({ url: server.url, path, query: customQuery1, statusCodeExpected: HttpStatusCode.OK_200 }) - const customQuery2 = immutableAssign(query, { languageOneOf: 'fr' }) + const customQuery2 = { ...query, languageOneOf: 'fr' } await makeGetRequest({ url: server.url, path, query: customQuery2, statusCodeExpected: HttpStatusCode.OK_200 }) }) it('Should succeed with valid tags', async function () { - const customQuery1 = immutableAssign(query, { tagsOneOf: [ 'tag1', 'tag2' ] }) + const customQuery1 = { ...query, tagsOneOf: [ 'tag1', 'tag2' ] } await makeGetRequest({ url: server.url, path, query: customQuery1, statusCodeExpected: HttpStatusCode.OK_200 }) - const customQuery2 = immutableAssign(query, { tagsOneOf: 'tag1' }) + const customQuery2 = { ...query, tagsOneOf: 'tag1' } await makeGetRequest({ url: server.url, path, query: customQuery2, statusCodeExpected: HttpStatusCode.OK_200 }) - const customQuery3 = immutableAssign(query, { tagsAllOf: [ 'tag1', 'tag2' ] }) + const customQuery3 = { ...query, tagsAllOf: [ 'tag1', 'tag2' ] } await makeGetRequest({ url: server.url, path, query: customQuery3, statusCodeExpected: HttpStatusCode.OK_200 }) - const customQuery4 = immutableAssign(query, { tagsAllOf: 'tag1' }) + const customQuery4 = { ...query, tagsAllOf: 'tag1' } await makeGetRequest({ url: server.url, path, query: customQuery4, statusCodeExpected: HttpStatusCode.OK_200 }) }) it('Should fail with invalid durations', async function () { - const customQuery1 = immutableAssign(query, { durationMin: 'hello' }) + const customQuery1 = { ...query, durationMin: 'hello' } await makeGetRequest({ url: server.url, path, query: customQuery1, statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) - const customQuery2 = immutableAssign(query, { durationMax: 'hello' }) + const customQuery2 = { ...query, durationMax: 'hello' } await makeGetRequest({ url: server.url, path, query: customQuery2, statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) }) it('Should fail with invalid dates', async function () { - const customQuery1 = immutableAssign(query, { startDate: 'hello' }) + const customQuery1 = { ...query, startDate: 'hello' } await makeGetRequest({ url: server.url, path, query: customQuery1, statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) - const customQuery2 = immutableAssign(query, { endDate: 'hello' }) + const customQuery2 = { ...query, endDate: 'hello' } await makeGetRequest({ url: server.url, path, query: customQuery2, statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) - const customQuery3 = immutableAssign(query, { originallyPublishedStartDate: 'hello' }) + const customQuery3 = { ...query, originallyPublishedStartDate: 'hello' } await makeGetRequest({ url: server.url, path, query: customQuery3, statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) - const customQuery4 = immutableAssign(query, { originallyPublishedEndDate: 'hello' }) + const customQuery4 = { ...query, originallyPublishedEndDate: 'hello' } await makeGetRequest({ url: server.url, path, query: customQuery4, statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) }) }) @@ -201,41 +200,41 @@ describe('Test videos API validator', function () { for (const path of paths) { { - const customQuery = immutableAssign(query, { searchTarget: 'hello' }) + const customQuery = { ...query, searchTarget: 'hello' } await makeGetRequest({ url: server.url, path, query: customQuery, statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) } { - const customQuery = immutableAssign(query, { searchTarget: undefined }) + const customQuery = { ...query, searchTarget: undefined } await makeGetRequest({ url: server.url, path, query: customQuery, statusCodeExpected: HttpStatusCode.OK_200 }) } { - const customQuery = immutableAssign(query, { searchTarget: 'local' }) + const customQuery = { ...query, searchTarget: 'local' } await makeGetRequest({ url: server.url, path, query: customQuery, statusCodeExpected: HttpStatusCode.OK_200 }) } { - const customQuery = immutableAssign(query, { searchTarget: 'search-index' }) + const customQuery = { ...query, searchTarget: 'search-index' } await makeGetRequest({ url: server.url, path, query: customQuery, statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) } await updateSearchIndex(server, true, true) { - const customQuery = immutableAssign(query, { searchTarget: 'local' }) + const customQuery = { ...query, searchTarget: 'local' } await makeGetRequest({ url: server.url, path, query: customQuery, statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) } { - const customQuery = immutableAssign(query, { searchTarget: 'search-index' }) + const customQuery = { ...query, searchTarget: 'search-index' } await makeGetRequest({ url: server.url, path, query: customQuery, statusCodeExpected: HttpStatusCode.OK_200 }) } await updateSearchIndex(server, true, false) { - const customQuery = immutableAssign(query, { searchTarget: 'local' }) + const customQuery = { ...query, searchTarget: 'local' } await makeGetRequest({ url: server.url, path, query: customQuery, statusCodeExpected: HttpStatusCode.OK_200 }) } diff --git a/server/tests/api/check-params/user-notifications.ts b/server/tests/api/check-params/user-notifications.ts index 26d4423f9..913eca366 100644 --- a/server/tests/api/check-params/user-notifications.ts +++ b/server/tests/api/check-params/user-notifications.ts @@ -2,25 +2,21 @@ import 'mocha' import { io } from 'socket.io-client' - +import { HttpStatusCode } from '@shared/core-utils' import { + checkBadCountPagination, + checkBadSortPagination, + checkBadStartPagination, cleanupTests, flushAndRunServer, - immutableAssign, makeGetRequest, makePostBodyRequest, makePutBodyRequest, ServerInfo, setAccessTokensToServers, wait -} from '../../../../shared/extra-utils' -import { - checkBadCountPagination, - checkBadSortPagination, - checkBadStartPagination -} from '../../../../shared/extra-utils/requests/check-api-params' -import { UserNotificationSetting, UserNotificationSettingValue } from '../../../../shared/models/users' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' +} from '@shared/extra-utils' +import { UserNotificationSetting, UserNotificationSettingValue } from '@shared/models' describe('Test user notifications API validators', function () { let server: ServerInfo @@ -193,7 +189,7 @@ describe('Test user notifications API validators', function () { it('Should fail with incorrect field values', async function () { { - const fields = immutableAssign(correctFields, { newCommentOnMyVideo: 15 }) + const fields = { ...correctFields, newCommentOnMyVideo: 15 } await makePutBodyRequest({ url: server.url, @@ -205,7 +201,7 @@ describe('Test user notifications API validators', function () { } { - const fields = immutableAssign(correctFields, { newCommentOnMyVideo: 'toto' }) + const fields = { ...correctFields, newCommentOnMyVideo: 'toto' } await makePutBodyRequest({ url: server.url, diff --git a/server/tests/api/check-params/users.ts b/server/tests/api/check-params/users.ts index bffe29bce..fda7e9640 100644 --- a/server/tests/api/check-params/users.ts +++ b/server/tests/api/check-params/users.ts @@ -15,7 +15,6 @@ import { getMyUserVideoRating, getUserScopedTokens, getUsersList, - immutableAssign, killallServers, makeGetRequest, makePostBodyRequest, @@ -181,25 +180,25 @@ describe('Test users API validators', function () { } it('Should fail with a too small username', async function () { - const fields = immutableAssign(baseCorrectParams, { username: '' }) + const fields = { ...baseCorrectParams, username: '' } await makePostBodyRequest({ url: server.url, path, token: server.accessToken, fields }) }) it('Should fail with a too long username', async function () { - const fields = immutableAssign(baseCorrectParams, { username: 'super'.repeat(50) }) + const fields = { ...baseCorrectParams, username: 'super'.repeat(50) } await makePostBodyRequest({ url: server.url, path, token: server.accessToken, fields }) }) it('Should fail with a not lowercase username', async function () { - const fields = immutableAssign(baseCorrectParams, { username: 'Toto' }) + const fields = { ...baseCorrectParams, username: 'Toto' } await makePostBodyRequest({ url: server.url, path, token: server.accessToken, fields }) }) it('Should fail with an incorrect username', async function () { - const fields = immutableAssign(baseCorrectParams, { username: 'my username' }) + const fields = { ...baseCorrectParams, username: 'my username' } await makePostBodyRequest({ url: server.url, path, token: server.accessToken, fields }) }) @@ -211,25 +210,25 @@ describe('Test users API validators', function () { }) it('Should fail with an invalid email', async function () { - const fields = immutableAssign(baseCorrectParams, { email: 'test_example.com' }) + const fields = { ...baseCorrectParams, email: 'test_example.com' } await makePostBodyRequest({ url: server.url, path, token: server.accessToken, fields }) }) it('Should fail with a too small password', async function () { - const fields = immutableAssign(baseCorrectParams, { password: 'bla' }) + const fields = { ...baseCorrectParams, password: 'bla' } await makePostBodyRequest({ url: server.url, path, token: server.accessToken, fields }) }) it('Should fail with a too long password', async function () { - const fields = immutableAssign(baseCorrectParams, { password: 'super'.repeat(61) }) + const fields = { ...baseCorrectParams, password: 'super'.repeat(61) } await makePostBodyRequest({ url: server.url, path, token: server.accessToken, fields }) }) it('Should fail with empty password and no smtp configured', async function () { - const fields = immutableAssign(baseCorrectParams, { password: '' }) + const fields = { ...baseCorrectParams, password: '' } await makePostBodyRequest({ url: server.url, path, token: server.accessToken, fields }) }) @@ -239,19 +238,23 @@ describe('Test users API validators', function () { await killallServers([ server ]) - const config = immutableAssign(overrideConfig, { + const config = { + ...overrideConfig, + smtp: { hostname: 'localhost', port: emailPort } - }) + } await reRunServer(server, config) - const fields = immutableAssign(baseCorrectParams, { + const fields = { + ...baseCorrectParams, + password: '', username: 'create_password', email: 'create_password@example.com' - }) + } await makePostBodyRequest({ url: server.url, @@ -263,7 +266,7 @@ describe('Test users API validators', function () { }) it('Should fail with invalid admin flags', async function () { - const fields = immutableAssign(baseCorrectParams, { adminFlags: 'toto' }) + const fields = { ...baseCorrectParams, adminFlags: 'toto' } await makePostBodyRequest({ url: server.url, path, token: server.accessToken, fields }) }) @@ -279,7 +282,7 @@ describe('Test users API validators', function () { }) it('Should fail if we add a user with the same username', async function () { - const fields = immutableAssign(baseCorrectParams, { username: 'user1' }) + const fields = { ...baseCorrectParams, username: 'user1' } await makePostBodyRequest({ url: server.url, @@ -291,7 +294,7 @@ describe('Test users API validators', function () { }) it('Should fail if we add a user with the same email', async function () { - const fields = immutableAssign(baseCorrectParams, { email: 'user1@example.com' }) + const fields = { ...baseCorrectParams, email: 'user1@example.com' } await makePostBodyRequest({ url: server.url, @@ -315,13 +318,13 @@ describe('Test users API validators', function () { }) it('Should fail with an invalid videoQuota', async function () { - const fields = immutableAssign(baseCorrectParams, { videoQuota: -5 }) + const fields = { ...baseCorrectParams, videoQuota: -5 } await makePostBodyRequest({ url: server.url, path, token: server.accessToken, fields }) }) it('Should fail with an invalid videoQuotaDaily', async function () { - const fields = immutableAssign(baseCorrectParams, { videoQuotaDaily: -7 }) + const fields = { ...baseCorrectParams, videoQuotaDaily: -7 } await makePostBodyRequest({ url: server.url, path, token: server.accessToken, fields }) }) @@ -333,13 +336,13 @@ describe('Test users API validators', function () { }) it('Should fail with an invalid user role', async function () { - const fields = immutableAssign(baseCorrectParams, { role: 88989 }) + const fields = { ...baseCorrectParams, role: 88989 } await makePostBodyRequest({ url: server.url, path, token: server.accessToken, fields }) }) it('Should fail with a "peertube" username', async function () { - const fields = immutableAssign(baseCorrectParams, { username: 'peertube' }) + const fields = { ...baseCorrectParams, username: 'peertube' } await makePostBodyRequest({ url: server.url, @@ -352,7 +355,7 @@ describe('Test users API validators', function () { it('Should fail to create a moderator or an admin with a moderator', async function () { for (const role of [ UserRole.MODERATOR, UserRole.ADMINISTRATOR ]) { - const fields = immutableAssign(baseCorrectParams, { role }) + const fields = { ...baseCorrectParams, role } await makePostBodyRequest({ url: server.url, @@ -365,7 +368,7 @@ describe('Test users API validators', function () { }) it('Should succeed to create a user with a moderator', async function () { - const fields = immutableAssign(baseCorrectParams, { username: 'a4656', email: 'a4656@example.com', role: UserRole.USER }) + const fields = { ...baseCorrectParams, username: 'a4656', email: 'a4656@example.com', role: UserRole.USER } await makePostBodyRequest({ url: server.url, @@ -937,19 +940,19 @@ describe('Test users API validators', function () { } it('Should fail with a too small username', async function () { - const fields = immutableAssign(baseCorrectParams, { username: '' }) + const fields = { ...baseCorrectParams, username: '' } await makePostBodyRequest({ url: server.url, path: registrationPath, token: server.accessToken, fields }) }) it('Should fail with a too long username', async function () { - const fields = immutableAssign(baseCorrectParams, { username: 'super'.repeat(50) }) + const fields = { ...baseCorrectParams, username: 'super'.repeat(50) } await makePostBodyRequest({ url: server.url, path: registrationPath, token: server.accessToken, fields }) }) it('Should fail with an incorrect username', async function () { - const fields = immutableAssign(baseCorrectParams, { username: 'my username' }) + const fields = { ...baseCorrectParams, username: 'my username' } await makePostBodyRequest({ url: server.url, path: registrationPath, token: server.accessToken, fields }) }) @@ -961,25 +964,25 @@ describe('Test users API validators', function () { }) it('Should fail with an invalid email', async function () { - const fields = immutableAssign(baseCorrectParams, { email: 'test_example.com' }) + const fields = { ...baseCorrectParams, email: 'test_example.com' } await makePostBodyRequest({ url: server.url, path: registrationPath, token: server.accessToken, fields }) }) it('Should fail with a too small password', async function () { - const fields = immutableAssign(baseCorrectParams, { password: 'bla' }) + const fields = { ...baseCorrectParams, password: 'bla' } await makePostBodyRequest({ url: server.url, path: registrationPath, token: server.accessToken, fields }) }) it('Should fail with a too long password', async function () { - const fields = immutableAssign(baseCorrectParams, { password: 'super'.repeat(61) }) + const fields = { ...baseCorrectParams, password: 'super'.repeat(61) } await makePostBodyRequest({ url: server.url, path: registrationPath, token: server.accessToken, fields }) }) it('Should fail if we register a user with the same username', async function () { - const fields = immutableAssign(baseCorrectParams, { username: 'root' }) + const fields = { ...baseCorrectParams, username: 'root' } await makePostBodyRequest({ url: server.url, @@ -991,7 +994,7 @@ describe('Test users API validators', function () { }) it('Should fail with a "peertube" username', async function () { - const fields = immutableAssign(baseCorrectParams, { username: 'peertube' }) + const fields = { ...baseCorrectParams, username: 'peertube' } await makePostBodyRequest({ url: server.url, @@ -1003,7 +1006,7 @@ describe('Test users API validators', function () { }) it('Should fail if we register a user with the same email', async function () { - const fields = immutableAssign(baseCorrectParams, { email: 'admin' + server.internalServerNumber + '@example.com' }) + const fields = { ...baseCorrectParams, email: 'admin' + server.internalServerNumber + '@example.com' } await makePostBodyRequest({ url: server.url, @@ -1015,26 +1018,26 @@ describe('Test users API validators', function () { }) it('Should fail with a bad display name', async function () { - const fields = immutableAssign(baseCorrectParams, { displayName: 'a'.repeat(150) }) + const fields = { ...baseCorrectParams, displayName: 'a'.repeat(150) } await makePostBodyRequest({ url: server.url, path: registrationPath, token: server.accessToken, fields }) }) it('Should fail with a bad channel name', async function () { - const fields = immutableAssign(baseCorrectParams, { channel: { name: '[]azf', displayName: 'toto' } }) + const fields = { ...baseCorrectParams, channel: { name: '[]azf', displayName: 'toto' } } await makePostBodyRequest({ url: server.url, path: registrationPath, token: server.accessToken, fields }) }) it('Should fail with a bad channel display name', async function () { - const fields = immutableAssign(baseCorrectParams, { channel: { name: 'toto', displayName: '' } }) + const fields = { ...baseCorrectParams, channel: { name: 'toto', displayName: '' } } await makePostBodyRequest({ url: server.url, path: registrationPath, token: server.accessToken, fields }) }) it('Should fail with a channel name that is the same as username', async function () { const source = { username: 'super_user', channel: { name: 'super_user', displayName: 'display name' } } - const fields = immutableAssign(baseCorrectParams, source) + const fields = { ...baseCorrectParams, ...source } await makePostBodyRequest({ url: server.url, path: registrationPath, token: server.accessToken, fields }) }) @@ -1043,7 +1046,7 @@ describe('Test users API validators', function () { const attributes = { name: 'existing_channel', displayName: 'hello', description: 'super description' } await server.channelsCommand.create({ attributes }) - const fields = immutableAssign(baseCorrectParams, { channel: { name: 'existing_channel', displayName: 'toto' } }) + const fields = { ...baseCorrectParams, channel: { name: 'existing_channel', displayName: 'toto' } } await makePostBodyRequest({ url: server.url, @@ -1055,7 +1058,7 @@ describe('Test users API validators', function () { }) it('Should succeed with the correct params', async function () { - const fields = immutableAssign(baseCorrectParams, { channel: { name: 'super_channel', displayName: 'toto' } }) + const fields = { ...baseCorrectParams, channel: { name: 'super_channel', displayName: 'toto' } } await makePostBodyRequest({ url: server.url, diff --git a/server/tests/api/check-params/video-channels.ts b/server/tests/api/check-params/video-channels.ts index d29346dc3..3b72d3796 100644 --- a/server/tests/api/check-params/video-channels.ts +++ b/server/tests/api/check-params/video-channels.ts @@ -3,14 +3,16 @@ import 'mocha' import * as chai from 'chai' import { omit } from 'lodash' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '@shared/core-utils' import { buildAbsoluteFixturePath, ChannelsCommand, + checkBadCountPagination, + checkBadSortPagination, + checkBadStartPagination, cleanupTests, createUser, flushAndRunServer, - immutableAssign, makeGetRequest, makePostBodyRequest, makePutBodyRequest, @@ -18,13 +20,8 @@ import { ServerInfo, setAccessTokensToServers, userLogin -} from '../../../../shared/extra-utils' -import { - checkBadCountPagination, - checkBadSortPagination, - checkBadStartPagination -} from '../../../../shared/extra-utils/requests/check-api-params' -import { VideoChannelUpdate } from '../../../../shared/models/videos' +} from '@shared/extra-utils' +import { VideoChannelUpdate } from '@shared/models' const expect = chai.expect @@ -127,7 +124,7 @@ describe('Test video channels API validator', function () { }) it('Should fail with a bad name', async function () { - const fields = immutableAssign(baseCorrectParams, { name: 'super name' }) + const fields = { ...baseCorrectParams, name: 'super name' } await makePostBodyRequest({ url: server.url, path: videoChannelPath, token: server.accessToken, fields }) }) @@ -137,17 +134,17 @@ describe('Test video channels API validator', function () { }) it('Should fail with a long name', async function () { - const fields = immutableAssign(baseCorrectParams, { displayName: 'super'.repeat(25) }) + const fields = { ...baseCorrectParams, displayName: 'super'.repeat(25) } await makePostBodyRequest({ url: server.url, path: videoChannelPath, token: server.accessToken, fields }) }) it('Should fail with a long description', async function () { - const fields = immutableAssign(baseCorrectParams, { description: 'super'.repeat(201) }) + const fields = { ...baseCorrectParams, description: 'super'.repeat(201) } await makePostBodyRequest({ url: server.url, path: videoChannelPath, token: server.accessToken, fields }) }) it('Should fail with a long support text', async function () { - const fields = immutableAssign(baseCorrectParams, { support: 'super'.repeat(201) }) + const fields = { ...baseCorrectParams, support: 'super'.repeat(201) } await makePostBodyRequest({ url: server.url, path: videoChannelPath, token: server.accessToken, fields }) }) @@ -206,22 +203,22 @@ describe('Test video channels API validator', function () { }) it('Should fail with a long name', async function () { - const fields = immutableAssign(baseCorrectParams, { displayName: 'super'.repeat(25) }) + const fields = { ...baseCorrectParams, displayName: 'super'.repeat(25) } await makePutBodyRequest({ url: server.url, path, token: server.accessToken, fields }) }) it('Should fail with a long description', async function () { - const fields = immutableAssign(baseCorrectParams, { description: 'super'.repeat(201) }) + const fields = { ...baseCorrectParams, description: 'super'.repeat(201) } await makePutBodyRequest({ url: server.url, path, token: server.accessToken, fields }) }) it('Should fail with a long support text', async function () { - const fields = immutableAssign(baseCorrectParams, { support: 'super'.repeat(201) }) + const fields = { ...baseCorrectParams, support: 'super'.repeat(201) } await makePutBodyRequest({ url: server.url, path, token: server.accessToken, fields }) }) it('Should fail with a bad bulkVideosSupportUpdate field', async function () { - const fields = immutableAssign(baseCorrectParams, { bulkVideosSupportUpdate: 'super' }) + const fields = { ...baseCorrectParams, bulkVideosSupportUpdate: 'super' } await makePutBodyRequest({ url: server.url, path, token: server.accessToken, fields }) }) diff --git a/server/tests/api/check-params/video-imports.ts b/server/tests/api/check-params/video-imports.ts index ea473191e..2cc124cc1 100644 --- a/server/tests/api/check-params/video-imports.ts +++ b/server/tests/api/check-params/video-imports.ts @@ -12,7 +12,6 @@ import { createUser, flushAndRunServer, getMyUserInformation, - immutableAssign, ImportsCommand, makeGetRequest, makePostBodyRequest, @@ -108,43 +107,43 @@ describe('Test video imports API validator', function () { }) it('Should fail with a bad target url', async function () { - const fields = immutableAssign(baseCorrectParams, { targetUrl: 'htt://hello' }) + const fields = { ...baseCorrectParams, targetUrl: 'htt://hello' } await makePostBodyRequest({ url: server.url, path, token: server.accessToken, fields }) }) it('Should fail with a long name', async function () { - const fields = immutableAssign(baseCorrectParams, { name: 'super'.repeat(65) }) + const fields = { ...baseCorrectParams, name: 'super'.repeat(65) } await makePostBodyRequest({ url: server.url, path, token: server.accessToken, fields }) }) it('Should fail with a bad category', async function () { - const fields = immutableAssign(baseCorrectParams, { category: 125 }) + const fields = { ...baseCorrectParams, category: 125 } await makePostBodyRequest({ url: server.url, path, token: server.accessToken, fields }) }) it('Should fail with a bad licence', async function () { - const fields = immutableAssign(baseCorrectParams, { licence: 125 }) + const fields = { ...baseCorrectParams, licence: 125 } await makePostBodyRequest({ url: server.url, path, token: server.accessToken, fields }) }) it('Should fail with a bad language', async function () { - const fields = immutableAssign(baseCorrectParams, { language: 'a'.repeat(15) }) + const fields = { ...baseCorrectParams, language: 'a'.repeat(15) } await makePostBodyRequest({ url: server.url, path, token: server.accessToken, fields }) }) it('Should fail with a long description', async function () { - const fields = immutableAssign(baseCorrectParams, { description: 'super'.repeat(2500) }) + const fields = { ...baseCorrectParams, description: 'super'.repeat(2500) } await makePostBodyRequest({ url: server.url, path, token: server.accessToken, fields }) }) it('Should fail with a long support text', async function () { - const fields = immutableAssign(baseCorrectParams, { support: 'super'.repeat(201) }) + const fields = { ...baseCorrectParams, support: 'super'.repeat(201) } await makePostBodyRequest({ url: server.url, path, token: server.accessToken, fields }) }) @@ -156,7 +155,7 @@ describe('Test video imports API validator', function () { }) it('Should fail with a bad channel', async function () { - const fields = immutableAssign(baseCorrectParams, { channelId: 545454 }) + const fields = { ...baseCorrectParams, channelId: 545454 } await makePostBodyRequest({ url: server.url, path, token: server.accessToken, fields }) }) @@ -172,25 +171,25 @@ describe('Test video imports API validator', function () { const res = await getMyUserInformation(server.url, accessTokenUser) const customChannelId = res.body.videoChannels[0].id - const fields = immutableAssign(baseCorrectParams, { channelId: customChannelId }) + const fields = { ...baseCorrectParams, channelId: customChannelId } await makePostBodyRequest({ url: server.url, path, token: userAccessToken, fields }) }) it('Should fail with too many tags', async function () { - const fields = immutableAssign(baseCorrectParams, { tags: [ 'tag1', 'tag2', 'tag3', 'tag4', 'tag5', 'tag6' ] }) + const fields = { ...baseCorrectParams, tags: [ 'tag1', 'tag2', 'tag3', 'tag4', 'tag5', 'tag6' ] } await makePostBodyRequest({ url: server.url, path, token: server.accessToken, fields }) }) it('Should fail with a tag length too low', async function () { - const fields = immutableAssign(baseCorrectParams, { tags: [ 'tag1', 't' ] }) + const fields = { ...baseCorrectParams, tags: [ 'tag1', 't' ] } await makePostBodyRequest({ url: server.url, path, token: server.accessToken, fields }) }) it('Should fail with a tag length too big', async function () { - const fields = immutableAssign(baseCorrectParams, { tags: [ 'tag1', 'my_super_tag_too_long_long_long_long_long_long' ] }) + const fields = { ...baseCorrectParams, tags: [ 'tag1', 'my_super_tag_too_long_long_long_long_long_long' ] } await makePostBodyRequest({ url: server.url, path, token: server.accessToken, fields }) }) @@ -242,7 +241,7 @@ describe('Test video imports API validator', function () { it('Should fail with an invalid magnet URI', async function () { let fields = omit(baseCorrectParams, 'targetUrl') - fields = immutableAssign(fields, { magnetUri: 'blabla' }) + fields = { ...fields, magnetUri: 'blabla' } await makePostBodyRequest({ url: server.url, path, token: server.accessToken, fields }) }) @@ -301,7 +300,7 @@ describe('Test video imports API validator', function () { }) let fields = omit(baseCorrectParams, 'targetUrl') - fields = immutableAssign(fields, { magnetUri: ImportsCommand.getMagnetURI() }) + fields = { ...fields, magnetUri: ImportsCommand.getMagnetURI() } await makePostBodyRequest({ url: server.url, diff --git a/server/tests/api/check-params/video-playlists.ts b/server/tests/api/check-params/video-playlists.ts index 1c507a047..3799e73b6 100644 --- a/server/tests/api/check-params/video-playlists.ts +++ b/server/tests/api/check-params/video-playlists.ts @@ -1,6 +1,7 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ import 'mocha' +import { HttpStatusCode } from '@shared/core-utils' import { VideoPlaylistCreate, VideoPlaylistCreateResult, @@ -10,7 +11,6 @@ import { VideoPlaylistReorder, VideoPlaylistType } from '@shared/models' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' import { checkBadCountPagination, checkBadSortPagination, @@ -18,7 +18,6 @@ import { cleanupTests, flushAndRunServer, generateUserAccessToken, - immutableAssign, makeGetRequest, PlaylistsCommand, ServerInfo, @@ -214,7 +213,7 @@ describe('Test video playlists API validator', function () { } } const getUpdate = (params: any, playlistId: number | string) => { - return immutableAssign(params, { playlistId: playlistId }) + return { ...params, playlistId: playlistId } } it('Should fail with an unauthenticated user', async function () { diff --git a/server/tests/api/check-params/videos.ts b/server/tests/api/check-params/videos.ts index 4d7a9a23b..6549063b1 100644 --- a/server/tests/api/check-params/videos.ts +++ b/server/tests/api/check-params/videos.ts @@ -15,7 +15,6 @@ import { getMyUserInformation, getVideo, getVideosList, - immutableAssign, makeDeleteRequest, makeGetRequest, makePutBodyRequest, @@ -225,42 +224,42 @@ describe('Test videos API validator', function () { }) it('Should fail with a long name', async function () { - const fields = immutableAssign(baseCorrectParams, { name: 'super'.repeat(65) }) + const fields = { ...baseCorrectParams, name: 'super'.repeat(65) } const attaches = baseCorrectAttaches await checkUploadVideoParam(server.url, server.accessToken, { ...fields, ...attaches }, HttpStatusCode.BAD_REQUEST_400, mode) }) it('Should fail with a bad category', async function () { - const fields = immutableAssign(baseCorrectParams, { category: 125 }) + const fields = { ...baseCorrectParams, category: 125 } const attaches = baseCorrectAttaches await checkUploadVideoParam(server.url, server.accessToken, { ...fields, ...attaches }, HttpStatusCode.BAD_REQUEST_400, mode) }) it('Should fail with a bad licence', async function () { - const fields = immutableAssign(baseCorrectParams, { licence: 125 }) + const fields = { ...baseCorrectParams, licence: 125 } const attaches = baseCorrectAttaches await checkUploadVideoParam(server.url, server.accessToken, { ...fields, ...attaches }, HttpStatusCode.BAD_REQUEST_400, mode) }) it('Should fail with a bad language', async function () { - const fields = immutableAssign(baseCorrectParams, { language: 'a'.repeat(15) }) + const fields = { ...baseCorrectParams, language: 'a'.repeat(15) } const attaches = baseCorrectAttaches await checkUploadVideoParam(server.url, server.accessToken, { ...fields, ...attaches }, HttpStatusCode.BAD_REQUEST_400, mode) }) it('Should fail with a long description', async function () { - const fields = immutableAssign(baseCorrectParams, { description: 'super'.repeat(2500) }) + const fields = { ...baseCorrectParams, description: 'super'.repeat(2500) } const attaches = baseCorrectAttaches await checkUploadVideoParam(server.url, server.accessToken, { ...fields, ...attaches }, HttpStatusCode.BAD_REQUEST_400, mode) }) it('Should fail with a long support text', async function () { - const fields = immutableAssign(baseCorrectParams, { support: 'super'.repeat(201) }) + const fields = { ...baseCorrectParams, support: 'super'.repeat(201) } const attaches = baseCorrectAttaches await checkUploadVideoParam(server.url, server.accessToken, { ...fields, ...attaches }, HttpStatusCode.BAD_REQUEST_400, mode) @@ -274,7 +273,7 @@ describe('Test videos API validator', function () { }) it('Should fail with a bad channel', async function () { - const fields = immutableAssign(baseCorrectParams, { channelId: 545454 }) + const fields = { ...baseCorrectParams, channelId: 545454 } const attaches = baseCorrectAttaches await checkUploadVideoParam(server.url, server.accessToken, { ...fields, ...attaches }, HttpStatusCode.BAD_REQUEST_400, mode) @@ -291,54 +290,56 @@ describe('Test videos API validator', function () { const res = await getMyUserInformation(server.url, accessTokenUser) const customChannelId = res.body.videoChannels[0].id - const fields = immutableAssign(baseCorrectParams, { channelId: customChannelId }) + const fields = { ...baseCorrectParams, channelId: customChannelId } const attaches = baseCorrectAttaches await checkUploadVideoParam(server.url, userAccessToken, { ...fields, ...attaches }, HttpStatusCode.BAD_REQUEST_400, mode) }) it('Should fail with too many tags', async function () { - const fields = immutableAssign(baseCorrectParams, { tags: [ 'tag1', 'tag2', 'tag3', 'tag4', 'tag5', 'tag6' ] }) + const fields = { ...baseCorrectParams, tags: [ 'tag1', 'tag2', 'tag3', 'tag4', 'tag5', 'tag6' ] } const attaches = baseCorrectAttaches await checkUploadVideoParam(server.url, server.accessToken, { ...fields, ...attaches }, HttpStatusCode.BAD_REQUEST_400, mode) }) it('Should fail with a tag length too low', async function () { - const fields = immutableAssign(baseCorrectParams, { tags: [ 'tag1', 't' ] }) + const fields = { ...baseCorrectParams, tags: [ 'tag1', 't' ] } const attaches = baseCorrectAttaches await checkUploadVideoParam(server.url, server.accessToken, { ...fields, ...attaches }, HttpStatusCode.BAD_REQUEST_400, mode) }) it('Should fail with a tag length too big', async function () { - const fields = immutableAssign(baseCorrectParams, { tags: [ 'tag1', 'my_super_tag_too_long_long_long_long_long_long' ] }) + const fields = { ...baseCorrectParams, tags: [ 'tag1', 'my_super_tag_too_long_long_long_long_long_long' ] } const attaches = baseCorrectAttaches await checkUploadVideoParam(server.url, server.accessToken, { ...fields, ...attaches }, HttpStatusCode.BAD_REQUEST_400, mode) }) it('Should fail with a bad schedule update (miss updateAt)', async function () { - const fields = immutableAssign(baseCorrectParams, { scheduleUpdate: { privacy: VideoPrivacy.PUBLIC } }) + const fields = { ...baseCorrectParams, scheduleUpdate: { privacy: VideoPrivacy.PUBLIC } } const attaches = baseCorrectAttaches await checkUploadVideoParam(server.url, server.accessToken, { ...fields, ...attaches }, HttpStatusCode.BAD_REQUEST_400, mode) }) it('Should fail with a bad schedule update (wrong updateAt)', async function () { - const fields = immutableAssign(baseCorrectParams, { + const fields = { + ...baseCorrectParams, + scheduleUpdate: { privacy: VideoPrivacy.PUBLIC, updateAt: 'toto' } - }) + } const attaches = baseCorrectAttaches await checkUploadVideoParam(server.url, server.accessToken, { ...fields, ...attaches }, HttpStatusCode.BAD_REQUEST_400, mode) }) it('Should fail with a bad originally published at attribute', async function () { - const fields = immutableAssign(baseCorrectParams, { originallyPublishedAt: 'toto' }) + const fields = { ...baseCorrectParams, originallyPublishedAt: 'toto' } const attaches = baseCorrectAttaches await checkUploadVideoParam(server.url, server.accessToken, { ...fields, ...attaches }, HttpStatusCode.BAD_REQUEST_400, mode) @@ -413,7 +414,7 @@ describe('Test videos API validator', function () { }) it('Should report the appropriate error', async function () { - const fields = immutableAssign(baseCorrectParams, { language: 'a'.repeat(15) }) + const fields = { ...baseCorrectParams, language: 'a'.repeat(15) } const attaches = baseCorrectAttaches const attributes = { ...fields, ...attaches } @@ -448,17 +449,21 @@ describe('Test videos API validator', function () { } { - const attaches = immutableAssign(baseCorrectAttaches, { + const attaches = { + ...baseCorrectAttaches, + videofile: join(root(), 'server', 'tests', 'fixtures', 'video_short.mp4') - }) + } await checkUploadVideoParam(server.url, server.accessToken, { ...fields, ...attaches }, HttpStatusCode.OK_200, mode) } { - const attaches = immutableAssign(baseCorrectAttaches, { + const attaches = { + ...baseCorrectAttaches, + videofile: join(root(), 'server', 'tests', 'fixtures', 'video_short.ogv') - }) + } await checkUploadVideoParam(server.url, server.accessToken, { ...fields, ...attaches }, HttpStatusCode.OK_200, mode) } @@ -516,79 +521,79 @@ describe('Test videos API validator', function () { }) it('Should fail with a long name', async function () { - const fields = immutableAssign(baseCorrectParams, { name: 'super'.repeat(65) }) + const fields = { ...baseCorrectParams, name: 'super'.repeat(65) } await makePutBodyRequest({ url: server.url, path: path + video.shortUUID, token: server.accessToken, fields }) }) it('Should fail with a bad category', async function () { - const fields = immutableAssign(baseCorrectParams, { category: 125 }) + const fields = { ...baseCorrectParams, category: 125 } await makePutBodyRequest({ url: server.url, path: path + video.shortUUID, token: server.accessToken, fields }) }) it('Should fail with a bad licence', async function () { - const fields = immutableAssign(baseCorrectParams, { licence: 125 }) + const fields = { ...baseCorrectParams, licence: 125 } await makePutBodyRequest({ url: server.url, path: path + video.shortUUID, token: server.accessToken, fields }) }) it('Should fail with a bad language', async function () { - const fields = immutableAssign(baseCorrectParams, { language: 'a'.repeat(15) }) + const fields = { ...baseCorrectParams, language: 'a'.repeat(15) } await makePutBodyRequest({ url: server.url, path: path + video.shortUUID, token: server.accessToken, fields }) }) it('Should fail with a long description', async function () { - const fields = immutableAssign(baseCorrectParams, { description: 'super'.repeat(2500) }) + const fields = { ...baseCorrectParams, description: 'super'.repeat(2500) } await makePutBodyRequest({ url: server.url, path: path + video.shortUUID, token: server.accessToken, fields }) }) it('Should fail with a long support text', async function () { - const fields = immutableAssign(baseCorrectParams, { support: 'super'.repeat(201) }) + const fields = { ...baseCorrectParams, support: 'super'.repeat(201) } await makePutBodyRequest({ url: server.url, path: path + video.shortUUID, token: server.accessToken, fields }) }) it('Should fail with a bad channel', async function () { - const fields = immutableAssign(baseCorrectParams, { channelId: 545454 }) + const fields = { ...baseCorrectParams, channelId: 545454 } await makePutBodyRequest({ url: server.url, path: path + video.shortUUID, token: server.accessToken, fields }) }) it('Should fail with too many tags', async function () { - const fields = immutableAssign(baseCorrectParams, { tags: [ 'tag1', 'tag2', 'tag3', 'tag4', 'tag5', 'tag6' ] }) + const fields = { ...baseCorrectParams, tags: [ 'tag1', 'tag2', 'tag3', 'tag4', 'tag5', 'tag6' ] } await makePutBodyRequest({ url: server.url, path: path + video.shortUUID, token: server.accessToken, fields }) }) it('Should fail with a tag length too low', async function () { - const fields = immutableAssign(baseCorrectParams, { tags: [ 'tag1', 't' ] }) + const fields = { ...baseCorrectParams, tags: [ 'tag1', 't' ] } await makePutBodyRequest({ url: server.url, path: path + video.shortUUID, token: server.accessToken, fields }) }) it('Should fail with a tag length too big', async function () { - const fields = immutableAssign(baseCorrectParams, { tags: [ 'tag1', 'my_super_tag_too_long_long_long_long_long_long' ] }) + const fields = { ...baseCorrectParams, tags: [ 'tag1', 'my_super_tag_too_long_long_long_long_long_long' ] } await makePutBodyRequest({ url: server.url, path: path + video.shortUUID, token: server.accessToken, fields }) }) it('Should fail with a bad schedule update (miss updateAt)', async function () { - const fields = immutableAssign(baseCorrectParams, { scheduleUpdate: { privacy: VideoPrivacy.PUBLIC } }) + const fields = { ...baseCorrectParams, scheduleUpdate: { privacy: VideoPrivacy.PUBLIC } } await makePutBodyRequest({ url: server.url, path: path + video.shortUUID, token: server.accessToken, fields }) }) it('Should fail with a bad schedule update (wrong updateAt)', async function () { - const fields = immutableAssign(baseCorrectParams, { scheduleUpdate: { updateAt: 'toto', privacy: VideoPrivacy.PUBLIC } }) + const fields = { ...baseCorrectParams, scheduleUpdate: { updateAt: 'toto', privacy: VideoPrivacy.PUBLIC } } await makePutBodyRequest({ url: server.url, path: path + video.shortUUID, token: server.accessToken, fields }) }) it('Should fail with a bad originally published at param', async function () { - const fields = immutableAssign(baseCorrectParams, { originallyPublishedAt: 'toto' }) + const fields = { ...baseCorrectParams, originallyPublishedAt: 'toto' } await makePutBodyRequest({ url: server.url, path: path + video.shortUUID, token: server.accessToken, fields }) }) @@ -672,7 +677,7 @@ describe('Test videos API validator', function () { it('Should fail with a video of another server') it('Shoud report the appropriate error', async function () { - const fields = immutableAssign(baseCorrectParams, { licence: 125 }) + const fields = { ...baseCorrectParams, licence: 125 } const res = await makePutBodyRequest({ url: server.url, path: path + video.shortUUID, token: server.accessToken, fields }) const error = res.body as PeerTubeProblemDocument diff --git a/server/tests/api/live/live.ts b/server/tests/api/live/live.ts index f9a162df6..999a49051 100644 --- a/server/tests/api/live/live.ts +++ b/server/tests/api/live/live.ts @@ -7,7 +7,6 @@ import { ffprobePromise, getVideoStreamFromFile } from '@server/helpers/ffprobe- import { LiveVideo, LiveVideoCreate, Video, VideoDetails, VideoPrivacy, VideoState, VideoStreamingPlaylistType } from '@shared/models' import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' import { - buildServerDirectory, checkLiveCleanup, checkLiveSegmentHash, checkResolutionsInMasterPlaylist, @@ -532,7 +531,7 @@ describe('Test live', function () { } const filename = `${video.uuid}-${resolution}-fragmented.mp4` - const segmentPath = buildServerDirectory(servers[0], join('streaming-playlists', 'hls', video.uuid, filename)) + const segmentPath = servers[0].serversCommand.buildDirectory(join('streaming-playlists', 'hls', video.uuid, filename)) const probe = await ffprobePromise(segmentPath) const videoStream = await getVideoStreamFromFile(segmentPath, probe) diff --git a/server/tests/api/notifications/moderation-notifications.ts b/server/tests/api/notifications/moderation-notifications.ts index 229f78811..99b434606 100644 --- a/server/tests/api/notifications/moderation-notifications.ts +++ b/server/tests/api/notifications/moderation-notifications.ts @@ -20,7 +20,6 @@ import { createUser, generateUserAccessToken, getVideoIdFromUUID, - immutableAssign, MockInstancesIndex, MockSmtpServer, prepareNotificationsTest, @@ -347,7 +346,7 @@ describe('Test moderation notifications', function () { await checkUserRegistered(baseParams, 'user_45', 'presence') const userOverride = { socketNotifications: userNotifications, token: userAccessToken, check: { web: true, mail: false } } - await checkUserRegistered(immutableAssign(baseParams, userOverride), 'user_45', 'absence') + await checkUserRegistered({ ...baseParams, ...userOverride }, 'user_45', 'absence') }) }) @@ -389,7 +388,7 @@ describe('Test moderation notifications', function () { await checkNewInstanceFollower(baseParams, 'localhost:' + servers[2].port, 'presence') const userOverride = { socketNotifications: userNotifications, token: userAccessToken, check: { web: true, mail: false } } - await checkNewInstanceFollower(immutableAssign(baseParams, userOverride), 'localhost:' + servers[2].port, 'absence') + await checkNewInstanceFollower({ ...baseParams, ...userOverride }, 'localhost:' + servers[2].port, 'absence') }) it('Should send a notification on auto follow back', async function () { @@ -416,7 +415,7 @@ describe('Test moderation notifications', function () { await checkAutoInstanceFollowing(baseParams, followerHost, followingHost, 'presence') const userOverride = { socketNotifications: userNotifications, token: userAccessToken, check: { web: true, mail: false } } - await checkAutoInstanceFollowing(immutableAssign(baseParams, userOverride), followerHost, followingHost, 'absence') + await checkAutoInstanceFollowing({ ...baseParams, ...userOverride }, followerHost, followingHost, 'absence') config.followings.instance.autoFollowBack.enabled = false await servers[0].configCommand.updateCustomSubConfig({ newConfig: config }) @@ -476,7 +475,9 @@ describe('Test moderation notifications', function () { currentCustomConfig = await servers[0].configCommand.getCustomConfig() - const autoBlacklistTestsCustomConfig = immutableAssign(currentCustomConfig, { + const autoBlacklistTestsCustomConfig = { + ...currentCustomConfig, + autoBlacklist: { videos: { ofUsers: { @@ -484,7 +485,7 @@ describe('Test moderation notifications', function () { } } } - }) + } // enable transcoding otherwise own publish notification after transcoding not expected autoBlacklistTestsCustomConfig.transcoding.enabled = true diff --git a/server/tests/api/notifications/notifications-api.ts b/server/tests/api/notifications/notifications-api.ts index 447492c5f..e5864f1c2 100644 --- a/server/tests/api/notifications/notifications-api.ts +++ b/server/tests/api/notifications/notifications-api.ts @@ -8,7 +8,6 @@ import { cleanupTests, getAllNotificationsSettings, getMyUserInformation, - immutableAssign, MockSmtpServer, prepareNotificationsTest, ServerInfo, @@ -118,7 +117,7 @@ describe('Test notifications API', function () { const { name, uuid } = await uploadRandomVideo(server) const check = { web: true, mail: true } - await checkNewVideoFromSubscription(immutableAssign(baseParams, { check }), name, uuid, 'absence') + await checkNewVideoFromSubscription({ ...baseParams, ...check }, name, uuid, 'absence') }) it('Should only have web notifications', async function () { @@ -139,12 +138,12 @@ describe('Test notifications API', function () { { const check = { mail: true, web: false } - await checkNewVideoFromSubscription(immutableAssign(baseParams, { check }), name, uuid, 'absence') + await checkNewVideoFromSubscription({ ...baseParams, ...check }, name, uuid, 'absence') } { const check = { mail: false, web: true } - await checkNewVideoFromSubscription(immutableAssign(baseParams, { check }), name, uuid, 'presence') + await checkNewVideoFromSubscription({ ...baseParams, ...check }, name, uuid, 'presence') } }) @@ -166,12 +165,12 @@ describe('Test notifications API', function () { { const check = { mail: false, web: true } - await checkNewVideoFromSubscription(immutableAssign(baseParams, { check }), name, uuid, 'absence') + await checkNewVideoFromSubscription({ ...baseParams, ...check }, name, uuid, 'absence') } { const check = { mail: true, web: false } - await checkNewVideoFromSubscription(immutableAssign(baseParams, { check }), name, uuid, 'presence') + await checkNewVideoFromSubscription({ ...baseParams, ...check }, name, uuid, 'presence') } }) diff --git a/server/tests/api/redundancy/manage-redundancy.ts b/server/tests/api/redundancy/manage-redundancy.ts index 363e4cbfe..03857f512 100644 --- a/server/tests/api/redundancy/manage-redundancy.ts +++ b/server/tests/api/redundancy/manage-redundancy.ts @@ -12,8 +12,7 @@ import { setAccessTokensToServers, uploadVideo, uploadVideoAndGetId, - waitJobs, - waitUntilLog + waitJobs } from '@shared/extra-utils' import { VideoPrivacy, VideoRedundanciesTarget } from '@shared/models' @@ -91,7 +90,7 @@ describe('Test manage videos redundancy', function () { this.timeout(120000) await waitJobs(servers) - await waitUntilLog(servers[0], 'Duplicated ', 10) + await servers[0].serversCommand.waitUntilLog('Duplicated ', 10) await waitJobs(servers) const body = await commands[1].listVideos({ target: 'remote-videos' }) @@ -214,7 +213,7 @@ describe('Test manage videos redundancy', function () { await commands[0].addVideo({ videoId }) await waitJobs(servers) - await waitUntilLog(servers[0], 'Duplicated ', 15) + await servers[0].serversCommand.waitUntilLog('Duplicated ', 15) await waitJobs(servers) { diff --git a/server/tests/api/redundancy/redundancy-constraints.ts b/server/tests/api/redundancy/redundancy-constraints.ts index 82d952471..a31278de7 100644 --- a/server/tests/api/redundancy/redundancy-constraints.ts +++ b/server/tests/api/redundancy/redundancy-constraints.ts @@ -11,8 +11,7 @@ import { setAccessTokensToServers, updateVideo, uploadVideo, - waitJobs, - waitUntilLog + waitJobs } from '@shared/extra-utils' import { VideoPrivacy } from '@shared/models' @@ -97,7 +96,7 @@ describe('Test redundancy constraints', function () { this.timeout(120000) await waitJobs(servers) - await waitUntilLog(remoteServer, 'Duplicated ', 5) + await remoteServer.serversCommand.waitUntilLog('Duplicated ', 5) await waitJobs(servers) { @@ -126,7 +125,7 @@ describe('Test redundancy constraints', function () { await uploadWrapper('video 2 server 2') - await waitUntilLog(remoteServer, 'Duplicated ', 10) + await remoteServer.serversCommand.waitUntilLog('Duplicated ', 10) await waitJobs(servers) { @@ -155,7 +154,7 @@ describe('Test redundancy constraints', function () { await uploadWrapper('video 3 server 2') - await waitUntilLog(remoteServer, 'Duplicated ', 15) + await remoteServer.serversCommand.waitUntilLog('Duplicated ', 15) await waitJobs(servers) { @@ -176,7 +175,7 @@ describe('Test redundancy constraints', function () { await waitJobs(servers) await uploadWrapper('video 4 server 2') - await waitUntilLog(remoteServer, 'Duplicated ', 20) + await remoteServer.serversCommand.waitUntilLog('Duplicated ', 20) await waitJobs(servers) { diff --git a/server/tests/api/redundancy/redundancy.ts b/server/tests/api/redundancy/redundancy.ts index 56a2af395..00a5e86cc 100644 --- a/server/tests/api/redundancy/redundancy.ts +++ b/server/tests/api/redundancy/redundancy.ts @@ -14,7 +14,6 @@ import { flushAndRunMultipleServers, getVideo, getVideoWithToken, - immutableAssign, killallServers, makeGetRequest, removeVideo, @@ -26,8 +25,7 @@ import { uploadVideo, viewVideo, wait, - waitJobs, - waitUntilLog + waitJobs } from '@shared/extra-utils' import { VideoDetails, VideoPrivacy, VideoRedundancyStrategy, VideoRedundancyStrategyWithManual } from '@shared/models' @@ -53,11 +51,13 @@ async function flushAndRunServers (strategy: VideoRedundancyStrategy | null, add if (strategy !== null) { strategies.push( - immutableAssign({ + { min_lifetime: '1 hour', strategy: strategy, - size: '400KB' - }, additionalParams) + size: '400KB', + + ...additionalParams + } ) } @@ -316,7 +316,7 @@ describe('Test videos redundancy', function () { this.timeout(80000) await waitJobs(servers) - await waitUntilLog(servers[0], 'Duplicated ', 5) + await servers[0].serversCommand.waitUntilLog('Duplicated ', 5) await waitJobs(servers) await check2Webseeds() @@ -335,7 +335,7 @@ describe('Test videos redundancy', function () { await check1WebSeed() await check0PlaylistRedundancies() - await checkVideoFilesWereRemoved(video1Server2UUID, servers[0].internalServerNumber, [ 'videos', join('playlists', 'hls') ]) + await checkVideoFilesWereRemoved(video1Server2UUID, servers[0], [ 'videos', join('playlists', 'hls') ]) }) after(async function () { @@ -366,7 +366,7 @@ describe('Test videos redundancy', function () { this.timeout(80000) await waitJobs(servers) - await waitUntilLog(servers[0], 'Duplicated ', 5) + await servers[0].serversCommand.waitUntilLog('Duplicated ', 5) await waitJobs(servers) await check2Webseeds() @@ -385,7 +385,7 @@ describe('Test videos redundancy', function () { await check1WebSeed() await check0PlaylistRedundancies() - await checkVideoFilesWereRemoved(video1Server2UUID, servers[0].internalServerNumber, [ 'videos' ]) + await checkVideoFilesWereRemoved(video1Server2UUID, servers[0], [ 'videos' ]) }) after(async function () { @@ -438,7 +438,7 @@ describe('Test videos redundancy', function () { this.timeout(80000) await waitJobs(servers) - await waitUntilLog(servers[0], 'Duplicated ', 5) + await servers[0].serversCommand.waitUntilLog('Duplicated ', 5) await waitJobs(servers) await check2Webseeds() @@ -454,7 +454,7 @@ describe('Test videos redundancy', function () { await waitJobs(servers) for (const server of servers) { - await checkVideoFilesWereRemoved(video1Server2UUID, server.internalServerNumber) + await checkVideoFilesWereRemoved(video1Server2UUID, server) } }) @@ -502,7 +502,7 @@ describe('Test videos redundancy', function () { await waitJobs(servers) await waitJobs(servers) - await waitUntilLog(servers[0], 'Duplicated ', 1) + await servers[0].serversCommand.waitUntilLog('Duplicated ', 1) await waitJobs(servers) await check1PlaylistRedundancies() @@ -517,7 +517,7 @@ describe('Test videos redundancy', function () { await waitJobs(servers) for (const server of servers) { - await checkVideoFilesWereRemoved(video1Server2UUID, server.internalServerNumber) + await checkVideoFilesWereRemoved(video1Server2UUID, server) } }) @@ -547,7 +547,7 @@ describe('Test videos redundancy', function () { this.timeout(80000) await waitJobs(servers) - await waitUntilLog(servers[0], 'Duplicated ', 5) + await servers[0].serversCommand.waitUntilLog('Duplicated ', 5) await waitJobs(servers) await check2Webseeds() @@ -575,7 +575,7 @@ describe('Test videos redundancy', function () { await check1WebSeed() await check0PlaylistRedundancies() - await checkVideoFilesWereRemoved(video1Server2UUID, servers[0].serverNumber, [ 'videos' ]) + await checkVideoFilesWereRemoved(video1Server2UUID, servers[0], [ 'videos' ]) }) after(async function () { @@ -658,7 +658,7 @@ describe('Test videos redundancy', function () { await enableRedundancyOnServer1() await waitJobs(servers) - await waitUntilLog(servers[0], 'Duplicated ', 5) + await servers[0].serversCommand.waitUntilLog('Duplicated ', 5) await waitJobs(servers) await check2Webseeds(video1Server2UUID) @@ -715,7 +715,7 @@ describe('Test videos redundancy', function () { await waitJobs(servers) - await checkVideoFilesWereRemoved(video1Server2UUID, servers[0].internalServerNumber, [ join('redundancy', 'hls') ]) + await checkVideoFilesWereRemoved(video1Server2UUID, servers[0], [ join('redundancy', 'hls') ]) }) after(async function () { diff --git a/server/tests/api/search/search-index.ts b/server/tests/api/search/search-index.ts index e4c5f5796..306f84c3a 100644 --- a/server/tests/api/search/search-index.ts +++ b/server/tests/api/search/search-index.ts @@ -2,16 +2,8 @@ import 'mocha' import * as chai from 'chai' -import { - cleanupTests, - flushAndRunServer, - immutableAssign, - SearchCommand, - ServerInfo, - setAccessTokensToServers, - uploadVideo -} from '@shared/extra-utils' -import { VideoPlaylistPrivacy, VideoPlaylistType, VideosSearchQuery } from '@shared/models' +import { cleanupTests, flushAndRunServer, SearchCommand, ServerInfo, setAccessTokensToServers, uploadVideo } from '@shared/extra-utils' +import { BooleanBothQuery, VideoPlaylistPrivacy, VideoPlaylistType, VideosSearchQuery } from '@shared/models' const expect = chai.expect @@ -174,32 +166,32 @@ describe('Test videos search', function () { } { - const search = immutableAssign(baseSearch, { startDate: '2018-10-01T10:54:46.396Z' }) + const search = { ...baseSearch, startDate: '2018-10-01T10:54:46.396Z' } await check(search, false) } { - const search = immutableAssign(baseSearch, { tagsAllOf: [ 'toto', 'framasoft' ] }) + const search = { ...baseSearch, tagsAllOf: [ 'toto', 'framasoft' ] } await check(search, false) } { - const search = immutableAssign(baseSearch, { durationMin: 2000 }) + const search = { ...baseSearch, durationMin: 2000 } await check(search, false) } { - const search = immutableAssign(baseSearch, { nsfw: 'true' }) + const search = { ...baseSearch, nsfw: 'true' as BooleanBothQuery } await check(search, false) } { - const search = immutableAssign(baseSearch, { nsfw: 'false' }) + const search = { ...baseSearch, nsfw: 'false' as BooleanBothQuery } await check(search, true) } { - const search = immutableAssign(baseSearch, { nsfw: 'both' }) + const search = { ...baseSearch, nsfw: 'both' as BooleanBothQuery } await check(search, true) } }) diff --git a/server/tests/api/search/search-videos.ts b/server/tests/api/search/search-videos.ts index 513538917..66f5f3182 100644 --- a/server/tests/api/search/search-videos.ts +++ b/server/tests/api/search/search-videos.ts @@ -5,7 +5,6 @@ import * as chai from 'chai' import { cleanupTests, flushAndRunServer, - immutableAssign, SearchCommand, ServerInfo, setAccessTokensToServers, @@ -44,11 +43,11 @@ describe('Test videos search', function () { } await uploadVideo(server.url, server.accessToken, attributes1) - const attributes2 = immutableAssign(attributes1, { name: attributes1.name + ' - 2', fixture: 'video_short.mp4' }) + const attributes2 = { ...attributes1, name: attributes1.name + ' - 2', fixture: 'video_short.mp4' } await uploadVideo(server.url, server.accessToken, attributes2) { - const attributes3 = immutableAssign(attributes1, { name: attributes1.name + ' - 3', language: undefined }) + const attributes3 = { ...attributes1, name: attributes1.name + ' - 3', language: undefined } const res = await uploadVideo(server.url, server.accessToken, attributes3) const videoId = res.body.video.id videoUUID = res.body.video.uuid @@ -68,26 +67,23 @@ describe('Test videos search', function () { }) } - const attributes4 = immutableAssign(attributes1, { name: attributes1.name + ' - 4', language: 'pl', nsfw: true }) + const attributes4 = { ...attributes1, name: attributes1.name + ' - 4', language: 'pl', nsfw: true } await uploadVideo(server.url, server.accessToken, attributes4) await wait(1000) startDate = new Date().toISOString() - const attributes5 = immutableAssign(attributes1, { name: attributes1.name + ' - 5', licence: 2, language: undefined }) + const attributes5 = { ...attributes1, name: attributes1.name + ' - 5', licence: 2, language: undefined } await uploadVideo(server.url, server.accessToken, attributes5) - const attributes6 = immutableAssign(attributes1, { name: attributes1.name + ' - 6', tags: [ 't1', 't2' ] }) + const attributes6 = { ...attributes1, name: attributes1.name + ' - 6', tags: [ 't1', 't2' ] } await uploadVideo(server.url, server.accessToken, attributes6) - const attributes7 = immutableAssign(attributes1, { - name: attributes1.name + ' - 7', - originallyPublishedAt: '2019-02-12T09:58:08.286Z' - }) + const attributes7 = { ...attributes1, name: attributes1.name + ' - 7', originallyPublishedAt: '2019-02-12T09:58:08.286Z' } await uploadVideo(server.url, server.accessToken, attributes7) - const attributes8 = immutableAssign(attributes1, { name: attributes1.name + ' - 8', licence: 4 }) + const attributes8 = { ...attributes1, name: attributes1.name + ' - 8', licence: 4 } await uploadVideo(server.url, server.accessToken, attributes8) } @@ -101,7 +97,7 @@ describe('Test videos search', function () { } await uploadVideo(server.url, server.accessToken, attributes) - await uploadVideo(server.url, server.accessToken, immutableAssign(attributes, { name: attributes.name + ' duplicate' })) + await uploadVideo(server.url, server.accessToken, { ...attributes, name: attributes.name + ' duplicate' }) } { @@ -122,10 +118,10 @@ describe('Test videos search', function () { category: 1 } await uploadVideo(server.url, server.accessToken, attributes1) - await uploadVideo(server.url, server.accessToken, immutableAssign(attributes1, { category: 2 })) + await uploadVideo(server.url, server.accessToken, { ...attributes1, category: 2 }) - await uploadVideo(server.url, server.accessToken, immutableAssign(attributes1, { tags: [ 'cccc', 'dddd' ] })) - await uploadVideo(server.url, server.accessToken, immutableAssign(attributes1, { tags: [ 'eeee', 'ffff' ] })) + await uploadVideo(server.url, server.accessToken, { ...attributes1, tags: [ 'cccc', 'dddd' ] }) + await uploadVideo(server.url, server.accessToken, { ...attributes1, tags: [ 'eeee', 'ffff' ] }) } { @@ -134,7 +130,7 @@ describe('Test videos search', function () { category: 1 } await uploadVideo(server.url, server.accessToken, attributes1) - await uploadVideo(server.url, server.accessToken, immutableAssign(attributes1, { category: 2 })) + await uploadVideo(server.url, server.accessToken, { ...attributes1, category: 2 }) } command = server.searchCommand @@ -414,7 +410,7 @@ describe('Test videos search', function () { } { - const query = immutableAssign(baseQuery, { originallyPublishedStartDate: '2019-02-11T09:58:08.286Z' }) + const query = { ...baseQuery, originallyPublishedStartDate: '2019-02-11T09:58:08.286Z' } const body = await command.advancedVideoSearch({ search: query }) expect(body.total).to.equal(1) @@ -422,7 +418,7 @@ describe('Test videos search', function () { } { - const query = immutableAssign(baseQuery, { originallyPublishedEndDate: '2019-03-11T09:58:08.286Z' }) + const query = { ...baseQuery, originallyPublishedEndDate: '2019-03-11T09:58:08.286Z' } const body = await command.advancedVideoSearch({ search: query }) expect(body.total).to.equal(1) @@ -430,34 +426,36 @@ describe('Test videos search', function () { } { - const query = immutableAssign(baseQuery, { originallyPublishedEndDate: '2019-01-11T09:58:08.286Z' }) + const query = { ...baseQuery, originallyPublishedEndDate: '2019-01-11T09:58:08.286Z' } const body = await command.advancedVideoSearch({ search: query }) expect(body.total).to.equal(0) } { - const query = immutableAssign(baseQuery, { originallyPublishedStartDate: '2019-03-11T09:58:08.286Z' }) + const query = { ...baseQuery, originallyPublishedStartDate: '2019-03-11T09:58:08.286Z' } const body = await command.advancedVideoSearch({ search: query }) expect(body.total).to.equal(0) } { - const query = immutableAssign(baseQuery, { + const query = { + ...baseQuery, originallyPublishedStartDate: '2019-01-11T09:58:08.286Z', originallyPublishedEndDate: '2019-01-10T09:58:08.286Z' - }) + } const body = await command.advancedVideoSearch({ search: query }) expect(body.total).to.equal(0) } { - const query = immutableAssign(baseQuery, { + const query = { + ...baseQuery, originallyPublishedStartDate: '2019-01-11T09:58:08.286Z', originallyPublishedEndDate: '2019-04-11T09:58:08.286Z' - }) + } const body = await command.advancedVideoSearch({ search: query }) expect(body.total).to.equal(1) diff --git a/server/tests/api/server/handle-down.ts b/server/tests/api/server/handle-down.ts index dd06acb5e..d45c3ae8a 100644 --- a/server/tests/api/server/handle-down.ts +++ b/server/tests/api/server/handle-down.ts @@ -10,7 +10,6 @@ import { flushAndRunMultipleServers, getVideo, getVideosList, - immutableAssign, killallServers, reRunServer, ServerInfo, @@ -50,9 +49,7 @@ describe('Test handle downs', function () { fixture: 'video_short1.webm' } - const unlistedVideoAttributes = immutableAssign(videoAttributes, { - privacy: VideoPrivacy.UNLISTED - }) + const unlistedVideoAttributes = { ...videoAttributes, privacy: VideoPrivacy.UNLISTED } let checkAttributes: any let unlistedCheckAttributes: any @@ -97,9 +94,7 @@ describe('Test handle downs', function () { } ] } - unlistedCheckAttributes = immutableAssign(checkAttributes, { - privacy: VideoPrivacy.UNLISTED - }) + unlistedCheckAttributes = { ...checkAttributes, privacy: VideoPrivacy.UNLISTED } // Get the access tokens await setAccessTokensToServers(servers) diff --git a/server/tests/api/server/logs.ts b/server/tests/api/server/logs.ts index 365f6cc2b..096d63e21 100644 --- a/server/tests/api/server/logs.ts +++ b/server/tests/api/server/logs.ts @@ -7,7 +7,6 @@ import { flushAndRunServer, killallServers, LogsCommand, - makePingRequest, reRunServer, ServerInfo, setAccessTokensToServers, @@ -102,7 +101,7 @@ describe('Test logs', function () { const now = new Date() - await makePingRequest(server) + await server.serversCommand.ping() const body = await logsCommand.getLogs({ startDate: now, level: 'info' }) const logsString = JSON.stringify(body) @@ -119,7 +118,7 @@ describe('Test logs', function () { const now = new Date() - await makePingRequest(server) + await server.serversCommand.ping() const body = await logsCommand.getLogs({ startDate: now, level: 'info' }) const logsString = JSON.stringify(body) diff --git a/server/tests/api/server/plugins.ts b/server/tests/api/server/plugins.ts index d4a43276f..a81ac961a 100644 --- a/server/tests/api/server/plugins.ts +++ b/server/tests/api/server/plugins.ts @@ -14,8 +14,7 @@ import { setAccessTokensToServers, testHelloWorldRegisteredSettings, updateMyUser, - wait, - waitUntilLog + wait } from '@shared/extra-utils' import { PluginType, User } from '@shared/models' @@ -194,7 +193,7 @@ describe('Test plugins', function () { it('Should have watched settings changes', async function () { this.timeout(10000) - await waitUntilLog(server, 'Settings changed!') + await server.serversCommand.waitUntilLog('Settings changed!') }) it('Should get a plugin and a theme', async function () { diff --git a/server/tests/api/users/users-multiple-servers.ts b/server/tests/api/users/users-multiple-servers.ts index 47056be78..7b650cb8f 100644 --- a/server/tests/api/users/users-multiple-servers.ts +++ b/server/tests/api/users/users-multiple-servers.ts @@ -227,7 +227,7 @@ describe('Test users with multiple servers', function () { it('Should not have video files', async () => { for (const server of servers) { - await checkVideoFilesWereRemoved(videoUUID, server.internalServerNumber) + await checkVideoFilesWereRemoved(videoUUID, server) } }) diff --git a/server/tests/api/videos/audio-only.ts b/server/tests/api/videos/audio-only.ts index 7ddbd5cd9..9b516af81 100644 --- a/server/tests/api/videos/audio-only.ts +++ b/server/tests/api/videos/audio-only.ts @@ -5,7 +5,6 @@ import * as chai from 'chai' import { join } from 'path' import { getAudioStream, getVideoStreamSize } from '@server/helpers/ffprobe-utils' import { - buildServerDirectory, cleanupTests, doubleFollow, flushAndRunMultipleServers, @@ -81,8 +80,8 @@ describe('Test audio only video transcoding', function () { it('0p transcoded video should not have video', async function () { const paths = [ - buildServerDirectory(servers[0], join('videos', videoUUID + '-0.mp4')), - buildServerDirectory(servers[0], join('streaming-playlists', 'hls', videoUUID, videoUUID + '-0-fragmented.mp4')) + servers[0].serversCommand.buildDirectory(join('videos', videoUUID + '-0.mp4')), + servers[0].serversCommand.buildDirectory(join('streaming-playlists', 'hls', videoUUID, videoUUID + '-0-fragmented.mp4')) ] for (const path of paths) { diff --git a/server/tests/api/videos/multiple-servers.ts b/server/tests/api/videos/multiple-servers.ts index 1b6f0f48a..1905aac83 100644 --- a/server/tests/api/videos/multiple-servers.ts +++ b/server/tests/api/videos/multiple-servers.ts @@ -689,8 +689,8 @@ describe('Test multiple servers', function () { it('Should not have files of videos 3 and 3-2 on each server', async function () { for (const server of servers) { - await checkVideoFilesWereRemoved(toRemove[0].uuid, server.internalServerNumber) - await checkVideoFilesWereRemoved(toRemove[1].uuid, server.internalServerNumber) + await checkVideoFilesWereRemoved(toRemove[0].uuid, server) + await checkVideoFilesWereRemoved(toRemove[1].uuid, server) } }) diff --git a/server/tests/api/videos/resumable-upload.ts b/server/tests/api/videos/resumable-upload.ts index 6c01c7e78..5845efc86 100644 --- a/server/tests/api/videos/resumable-upload.ts +++ b/server/tests/api/videos/resumable-upload.ts @@ -7,7 +7,6 @@ import { join } from 'path' import { HttpStatusCode } from '@shared/core-utils' import { buildAbsoluteFixturePath, - buildServerDirectory, cleanupTests, flushAndRunServer, getMyUserInformation, @@ -82,7 +81,7 @@ describe('Test resumable upload', function () { const uploadId = uploadIdArg.replace(/^upload_id=/, '') const subPath = join('tmp', 'resumable-uploads', uploadId) - const filePath = buildServerDirectory(server, subPath) + const filePath = server.serversCommand.buildDirectory(subPath) const exists = await pathExists(filePath) if (expectedSize === null) { @@ -97,7 +96,7 @@ describe('Test resumable upload', function () { async function countResumableUploads () { const subPath = join('tmp', 'resumable-uploads') - const filePath = buildServerDirectory(server, subPath) + const filePath = server.serversCommand.buildDirectory(subPath) const files = await readdir(filePath) return files.length diff --git a/server/tests/api/videos/single-server.ts b/server/tests/api/videos/single-server.ts index 1058a1e9c..af1703e02 100644 --- a/server/tests/api/videos/single-server.ts +++ b/server/tests/api/videos/single-server.ts @@ -230,7 +230,7 @@ describe('Test a single server', function () { it('Should remove the video', async function () { await removeVideo(server.url, server.accessToken, videoId) - await checkVideoFilesWereRemoved(videoUUID, 1) + await checkVideoFilesWereRemoved(videoUUID, server) }) it('Should not have videos', async function () { diff --git a/server/tests/api/videos/video-captions.ts b/server/tests/api/videos/video-captions.ts index 83ee809b8..d4a5385ab 100644 --- a/server/tests/api/videos/video-captions.ts +++ b/server/tests/api/videos/video-captions.ts @@ -182,7 +182,7 @@ describe('Test video captions', function () { it('Should remove the video, and thus all video captions', async function () { await removeVideo(servers[0].url, servers[0].accessToken, videoUUID) - await checkVideoFilesWereRemoved(videoUUID, 1) + await checkVideoFilesWereRemoved(videoUUID, servers[0]) }) after(async function () { diff --git a/server/tests/api/videos/video-imports.ts b/server/tests/api/videos/video-imports.ts index 4f9ecbe8e..f6ae8cab1 100644 --- a/server/tests/api/videos/video-imports.ts +++ b/server/tests/api/videos/video-imports.ts @@ -11,7 +11,6 @@ import { getMyVideos, getVideo, getVideosList, - immutableAssign, ImportsCommand, ServerInfo, setAccessTokensToServers, @@ -119,7 +118,7 @@ describe('Test video imports', function () { } { - const attributes = immutableAssign(baseAttributes, { targetUrl: ImportsCommand.getYoutubeVideoUrl() }) + const attributes = { ...baseAttributes, targetUrl: ImportsCommand.getYoutubeVideoUrl() } const { video } = await servers[0].importsCommand.importVideo({ attributes }) expect(video.name).to.equal('small video - youtube') @@ -169,21 +168,23 @@ Ajouter un sous-titre est vraiment facile`) } { - const attributes = immutableAssign(baseAttributes, { + const attributes = { + ...baseAttributes, magnetUri: ImportsCommand.getMagnetURI(), description: 'this is a super torrent description', tags: [ 'tag_torrent1', 'tag_torrent2' ] - }) + } const { video } = await servers[0].importsCommand.importVideo({ attributes }) expect(video.name).to.equal('super peertube2 video') } { - const attributes = immutableAssign(baseAttributes, { + const attributes = { + ...baseAttributes, torrentfile: 'video-720p.torrent' as any, description: 'this is a super torrent description', tags: [ 'tag_torrent1', 'tag_torrent2' ] - }) + } const { video } = await servers[0].importsCommand.importVideo({ attributes }) expect(video.name).to.equal('你好 世界 720p.mp4') } diff --git a/server/tests/api/videos/video-transcoder.ts b/server/tests/api/videos/video-transcoder.ts index e74fb5bef..f16b22bae 100644 --- a/server/tests/api/videos/video-transcoder.ts +++ b/server/tests/api/videos/video-transcoder.ts @@ -9,14 +9,12 @@ import { VIDEO_TRANSCODING_FPS } from '../../../../server/initializers/constants import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' import { buildAbsoluteFixturePath, - buildServerDirectory, cleanupTests, doubleFollow, flushAndRunMultipleServers, generateHighBitrateVideo, generateVideoWithFramerate, getMyVideos, - getServerFileSize, getVideo, getVideoFileMetadataUrl, getVideosList, @@ -285,7 +283,7 @@ describe('Test video transcoding', function () { expect(videoDetails.files).to.have.lengthOf(4) - const path = buildServerDirectory(servers[1], join('videos', video.uuid + '-240.mp4')) + const path = servers[1].serversCommand.buildDirectory(join('videos', video.uuid + '-240.mp4')) const probe = await getAudioStream(path) if (probe.audioStream) { @@ -316,7 +314,7 @@ describe('Test video transcoding', function () { const videoDetails: VideoDetails = res2.body expect(videoDetails.files).to.have.lengthOf(4) - const path = buildServerDirectory(servers[1], join('videos', video.uuid + '-240.mp4')) + const path = servers[1].serversCommand.buildDirectory(join('videos', video.uuid + '-240.mp4')) const probe = await getAudioStream(path) expect(probe).to.not.have.property('audioStream') } @@ -344,7 +342,7 @@ describe('Test video transcoding', function () { const fixturePath = buildAbsoluteFixturePath(videoAttributes.fixture) const fixtureVideoProbe = await getAudioStream(fixturePath) - const path = buildServerDirectory(servers[1], join('videos', video.uuid + '-240.mp4')) + const path = servers[1].serversCommand.buildDirectory(join('videos', video.uuid + '-240.mp4')) const videoProbe = await getAudioStream(path) @@ -506,13 +504,13 @@ describe('Test video transcoding', function () { expect(videoDetails.files[3].fps).to.be.below(31) for (const resolution of [ '240', '360', '480' ]) { - const path = buildServerDirectory(servers[1], join('videos', video.uuid + '-' + resolution + '.mp4')) + const path = servers[1].serversCommand.buildDirectory(join('videos', video.uuid + '-' + resolution + '.mp4')) const fps = await getVideoFileFPS(path) expect(fps).to.be.below(31) } - const path = buildServerDirectory(servers[1], join('videos', video.uuid + '-720.mp4')) + const path = servers[1].serversCommand.buildDirectory(join('videos', video.uuid + '-720.mp4')) const fps = await getVideoFileFPS(path) expect(fps).to.be.above(58).and.below(62) @@ -547,13 +545,13 @@ describe('Test video transcoding', function () { const video = res.body.data.find(v => v.name === videoAttributes.name) { - const path = buildServerDirectory(servers[1], join('videos', video.uuid + '-240.mp4')) + const path = servers[1].serversCommand.buildDirectory(join('videos', video.uuid + '-240.mp4')) const fps = await getVideoFileFPS(path) expect(fps).to.be.equal(25) } { - const path = buildServerDirectory(servers[1], join('videos', video.uuid + '-720.mp4')) + const path = servers[1].serversCommand.buildDirectory(join('videos', video.uuid + '-720.mp4')) const fps = await getVideoFileFPS(path) expect(fps).to.be.equal(59) } @@ -590,7 +588,7 @@ describe('Test video transcoding', function () { const video = res.body.data.find(v => v.name === videoAttributes.name) for (const resolution of [ '240', '360', '480', '720', '1080' ]) { - const path = buildServerDirectory(servers[1], join('videos', video.uuid + '-' + resolution + '.mp4')) + const path = servers[1].serversCommand.buildDirectory(join('videos', video.uuid + '-' + resolution + '.mp4')) const bitrate = await getVideoFileBitrate(path) const fps = await getVideoFileFPS(path) @@ -636,7 +634,7 @@ describe('Test video transcoding', function () { const resolutions = [ 240, 360, 480, 720, 1080 ] for (const r of resolutions) { const path = `videos/${videoUUID}-${r}.mp4` - const size = await getServerFileSize(servers[1], path) + const size = await servers[1].serversCommand.getServerFileSize(path) expect(size, `${path} not below ${60_000}`).to.be.below(60_000) } }) @@ -651,7 +649,7 @@ describe('Test video transcoding', function () { await waitJobs(servers) { - const path = buildServerDirectory(servers[1], join('videos', videoUUID + '-240.mp4')) + const path = servers[1].serversCommand.buildDirectory(join('videos', videoUUID + '-240.mp4')) const metadata = await getMetadataFromFile(path) // expected format properties diff --git a/server/tests/cli/optimize-old-videos.ts b/server/tests/cli/optimize-old-videos.ts index bd15012fe..e369a3305 100644 --- a/server/tests/cli/optimize-old-videos.ts +++ b/server/tests/cli/optimize-old-videos.ts @@ -4,7 +4,6 @@ import 'mocha' import * as chai from 'chai' import { join } from 'path' import { - buildServerDirectory, cleanupTests, doubleFollow, flushAndRunMultipleServers, @@ -96,7 +95,7 @@ describe('Test optimize old videos', function () { expect(file.size).to.be.below(8000000) - const path = buildServerDirectory(servers[0], join('videos', video.uuid + '-' + file.resolution.id + '.mp4')) + const path = servers[0].serversCommand.buildDirectory(join('videos', video.uuid + '-' + file.resolution.id + '.mp4')) const bitrate = await getVideoFileBitrate(path) const fps = await getVideoFileFPS(path) const resolution = await getVideoFileResolution(path) diff --git a/server/tests/cli/prune-storage.ts b/server/tests/cli/prune-storage.ts index d4dbee682..68a59a41d 100644 --- a/server/tests/cli/prune-storage.ts +++ b/server/tests/cli/prune-storage.ts @@ -7,7 +7,6 @@ import { join } from 'path' import { buildUUID } from '@server/helpers/uuid' import { HttpStatusCode } from '@shared/core-utils' import { - buildServerDirectory, cleanupTests, CLICommand, doubleFollow, @@ -26,14 +25,14 @@ import { VideoPlaylistPrivacy } from '@shared/models' const expect = chai.expect -async function countFiles (internalServerNumber: number, directory: string) { - const files = await readdir(buildServerDirectory({ internalServerNumber }, directory)) +async function countFiles (server: ServerInfo, directory: string) { + const files = await readdir(server.serversCommand.buildDirectory(directory)) return files.length } -async function assertNotExists (internalServerNumber: number, directory: string, substring: string) { - const files = await readdir(buildServerDirectory({ internalServerNumber }, directory)) +async function assertNotExists (server: ServerInfo, directory: string, substring: string) { + const files = await readdir(server.serversCommand.buildDirectory(directory)) for (const f of files) { expect(f).to.not.contain(substring) @@ -42,19 +41,19 @@ async function assertNotExists (internalServerNumber: number, directory: string, async function assertCountAreOkay (servers: ServerInfo[]) { for (const server of servers) { - const videosCount = await countFiles(server.internalServerNumber, 'videos') + const videosCount = await countFiles(server, 'videos') expect(videosCount).to.equal(8) - const torrentsCount = await countFiles(server.internalServerNumber, 'torrents') + const torrentsCount = await countFiles(server, 'torrents') expect(torrentsCount).to.equal(16) - const previewsCount = await countFiles(server.internalServerNumber, 'previews') + const previewsCount = await countFiles(server, 'previews') expect(previewsCount).to.equal(2) - const thumbnailsCount = await countFiles(server.internalServerNumber, 'thumbnails') + const thumbnailsCount = await countFiles(server, 'thumbnails') expect(thumbnailsCount).to.equal(6) - const avatarsCount = await countFiles(server.internalServerNumber, 'avatars') + const avatarsCount = await countFiles(server, 'avatars') expect(avatarsCount).to.equal(2) } } @@ -122,7 +121,7 @@ describe('Test prune storage scripts', function () { it('Should create some dirty files', async function () { for (let i = 0; i < 2; i++) { { - const base = buildServerDirectory(servers[0], 'videos') + const base = servers[0].serversCommand.buildDirectory('videos') const n1 = buildUUID() + '.mp4' const n2 = buildUUID() + '.webm' @@ -134,7 +133,7 @@ describe('Test prune storage scripts', function () { } { - const base = buildServerDirectory(servers[0], 'torrents') + const base = servers[0].serversCommand.buildDirectory('torrents') const n1 = buildUUID() + '-240.torrent' const n2 = buildUUID() + '-480.torrent' @@ -146,7 +145,7 @@ describe('Test prune storage scripts', function () { } { - const base = buildServerDirectory(servers[0], 'thumbnails') + const base = servers[0].serversCommand.buildDirectory('thumbnails') const n1 = buildUUID() + '.jpg' const n2 = buildUUID() + '.jpg' @@ -158,7 +157,7 @@ describe('Test prune storage scripts', function () { } { - const base = buildServerDirectory(servers[0], 'previews') + const base = servers[0].serversCommand.buildDirectory('previews') const n1 = buildUUID() + '.jpg' const n2 = buildUUID() + '.jpg' @@ -170,7 +169,7 @@ describe('Test prune storage scripts', function () { } { - const base = buildServerDirectory(servers[0], 'avatars') + const base = servers[0].serversCommand.buildDirectory('avatars') const n1 = buildUUID() + '.png' const n2 = buildUUID() + '.jpg' @@ -195,7 +194,7 @@ describe('Test prune storage scripts', function () { for (const directory of Object.keys(badNames)) { for (const name of badNames[directory]) { - await assertNotExists(servers[0].internalServerNumber, directory, name) + await assertNotExists(servers[0], directory, name) } } }) diff --git a/server/tests/cli/regenerate-thumbnails.ts b/server/tests/cli/regenerate-thumbnails.ts index 1b460e9c0..68a4711b6 100644 --- a/server/tests/cli/regenerate-thumbnails.ts +++ b/server/tests/cli/regenerate-thumbnails.ts @@ -4,7 +4,6 @@ import { writeFile } from 'fs-extra' import { basename, join } from 'path' import { Video, VideoDetails } from '@shared/models' import { - buildServerDirectory, cleanupTests, doubleFollow, flushAndRunMultipleServers, @@ -50,7 +49,7 @@ describe('Test regenerate thumbnails script', function () { const videoUUID1 = (await uploadVideoAndGetId({ server: servers[0], videoName: 'video 1' })).uuid video1 = await (getVideo(servers[0].url, videoUUID1).then(res => res.body)) - thumbnail1Path = join(buildServerDirectory(servers[0], 'thumbnails'), basename(video1.thumbnailPath)) + thumbnail1Path = join(servers[0].serversCommand.buildDirectory('thumbnails'), basename(video1.thumbnailPath)) const videoUUID2 = (await uploadVideoAndGetId({ server: servers[0], videoName: 'video 2' })).uuid video2 = await (getVideo(servers[0].url, videoUUID2).then(res => res.body)) @@ -62,7 +61,7 @@ describe('Test regenerate thumbnails script', function () { remoteVideo = await (getVideo(servers[0].url, videoUUID).then(res => res.body)) - thumbnailRemotePath = join(buildServerDirectory(servers[0], 'thumbnails'), basename(remoteVideo.thumbnailPath)) + thumbnailRemotePath = join(servers[0].serversCommand.buildDirectory('thumbnails'), basename(remoteVideo.thumbnailPath)) } await writeFile(thumbnail1Path, '') diff --git a/server/tests/plugins/action-hooks.ts b/server/tests/plugins/action-hooks.ts index bcf773854..cf81e44b7 100644 --- a/server/tests/plugins/action-hooks.ts +++ b/server/tests/plugins/action-hooks.ts @@ -22,8 +22,7 @@ import { flushAndRunMultipleServers, killallServers, reRunServer, - ServerInfo, - waitUntilLog + ServerInfo } from '../../../shared/extra-utils/server/servers' describe('Test plugin action hooks', function () { @@ -32,7 +31,7 @@ describe('Test plugin action hooks', function () { let threadId: number function checkHook (hook: ServerHookName) { - return waitUntilLog(servers[0], 'Run hook ' + hook) + return servers[0].serversCommand.waitUntilLog('Run hook ' + hook) } before(async function () { diff --git a/server/tests/plugins/external-auth.ts b/server/tests/plugins/external-auth.ts index 09a107ca2..f7cee588a 100644 --- a/server/tests/plugins/external-auth.ts +++ b/server/tests/plugins/external-auth.ts @@ -17,8 +17,7 @@ import { setAccessTokensToServers, updateMyUser, userLogin, - wait, - waitUntilLog + wait } from '@shared/extra-utils' import { User, UserRole } from '@shared/models' @@ -127,7 +126,7 @@ describe('Test external auth plugins', function () { await loginUsingExternalToken(server, 'cyan', externalAuthToken, HttpStatusCode.BAD_REQUEST_400) - await waitUntilLog(server, 'expired external auth token', 2) + await server.serversCommand.waitUntilLog('expired external auth token', 2) }) it('Should auto login Cyan, create the user and use the token', async function () { @@ -217,7 +216,7 @@ describe('Test external auth plugins', function () { }) it('Should have logged out Cyan', async function () { - await waitUntilLog(server, 'On logout cyan') + await server.serversCommand.waitUntilLog('On logout cyan') await getMyUserInformation(server.url, cyanAccessToken, HttpStatusCode.UNAUTHORIZED_401) }) diff --git a/server/tests/plugins/filter-hooks.ts b/server/tests/plugins/filter-hooks.ts index c235508e8..b5e29d298 100644 --- a/server/tests/plugins/filter-hooks.ts +++ b/server/tests/plugins/filter-hooks.ts @@ -24,8 +24,7 @@ import { updateVideo, uploadVideo, uploadVideoAndGetId, - waitJobs, - waitUntilLog + waitJobs } from '@shared/extra-utils' import { VideoDetails, VideoImportState, VideoPlaylist, VideoPlaylistPrivacy, VideoPrivacy } from '@shared/models' @@ -475,8 +474,8 @@ describe('Test plugin filter hooks', function () { } }) - await waitUntilLog(servers[0], 'Run hook filter:api.search.videos.local.list.params', 1) - await waitUntilLog(servers[0], 'Run hook filter:api.search.videos.local.list.result', 1) + await servers[0].serversCommand.waitUntilLog('Run hook filter:api.search.videos.local.list.params', 1) + await servers[0].serversCommand.waitUntilLog('Run hook filter:api.search.videos.local.list.result', 1) }) it('Should run filter:api.search.videos.index.list.{params,result}', async function () { @@ -487,10 +486,10 @@ describe('Test plugin filter hooks', function () { } }) - await waitUntilLog(servers[0], 'Run hook filter:api.search.videos.local.list.params', 1) - await waitUntilLog(servers[0], 'Run hook filter:api.search.videos.local.list.result', 1) - await waitUntilLog(servers[0], 'Run hook filter:api.search.videos.index.list.params', 1) - await waitUntilLog(servers[0], 'Run hook filter:api.search.videos.index.list.result', 1) + await servers[0].serversCommand.waitUntilLog('Run hook filter:api.search.videos.local.list.params', 1) + await servers[0].serversCommand.waitUntilLog('Run hook filter:api.search.videos.local.list.result', 1) + await servers[0].serversCommand.waitUntilLog('Run hook filter:api.search.videos.index.list.params', 1) + await servers[0].serversCommand.waitUntilLog('Run hook filter:api.search.videos.index.list.result', 1) }) it('Should run filter:api.search.video-channels.local.list.{params,result}', async function () { @@ -500,8 +499,8 @@ describe('Test plugin filter hooks', function () { } }) - await waitUntilLog(servers[0], 'Run hook filter:api.search.video-channels.local.list.params', 1) - await waitUntilLog(servers[0], 'Run hook filter:api.search.video-channels.local.list.result', 1) + await servers[0].serversCommand.waitUntilLog('Run hook filter:api.search.video-channels.local.list.params', 1) + await servers[0].serversCommand.waitUntilLog('Run hook filter:api.search.video-channels.local.list.result', 1) }) it('Should run filter:api.search.video-channels.index.list.{params,result}', async function () { @@ -512,10 +511,10 @@ describe('Test plugin filter hooks', function () { } }) - await waitUntilLog(servers[0], 'Run hook filter:api.search.video-channels.local.list.params', 1) - await waitUntilLog(servers[0], 'Run hook filter:api.search.video-channels.local.list.result', 1) - await waitUntilLog(servers[0], 'Run hook filter:api.search.video-channels.index.list.params', 1) - await waitUntilLog(servers[0], 'Run hook filter:api.search.video-channels.index.list.result', 1) + await servers[0].serversCommand.waitUntilLog('Run hook filter:api.search.video-channels.local.list.params', 1) + await servers[0].serversCommand.waitUntilLog('Run hook filter:api.search.video-channels.local.list.result', 1) + await servers[0].serversCommand.waitUntilLog('Run hook filter:api.search.video-channels.index.list.params', 1) + await servers[0].serversCommand.waitUntilLog('Run hook filter:api.search.video-channels.index.list.result', 1) }) it('Should run filter:api.search.video-playlists.local.list.{params,result}', async function () { @@ -525,8 +524,8 @@ describe('Test plugin filter hooks', function () { } }) - await waitUntilLog(servers[0], 'Run hook filter:api.search.video-playlists.local.list.params', 1) - await waitUntilLog(servers[0], 'Run hook filter:api.search.video-playlists.local.list.result', 1) + await servers[0].serversCommand.waitUntilLog('Run hook filter:api.search.video-playlists.local.list.params', 1) + await servers[0].serversCommand.waitUntilLog('Run hook filter:api.search.video-playlists.local.list.result', 1) }) it('Should run filter:api.search.video-playlists.index.list.{params,result}', async function () { @@ -537,10 +536,10 @@ describe('Test plugin filter hooks', function () { } }) - await waitUntilLog(servers[0], 'Run hook filter:api.search.video-playlists.local.list.params', 1) - await waitUntilLog(servers[0], 'Run hook filter:api.search.video-playlists.local.list.result', 1) - await waitUntilLog(servers[0], 'Run hook filter:api.search.video-playlists.index.list.params', 1) - await waitUntilLog(servers[0], 'Run hook filter:api.search.video-playlists.index.list.result', 1) + await servers[0].serversCommand.waitUntilLog('Run hook filter:api.search.video-playlists.local.list.params', 1) + await servers[0].serversCommand.waitUntilLog('Run hook filter:api.search.video-playlists.local.list.result', 1) + await servers[0].serversCommand.waitUntilLog('Run hook filter:api.search.video-playlists.index.list.params', 1) + await servers[0].serversCommand.waitUntilLog('Run hook filter:api.search.video-playlists.index.list.result', 1) }) }) diff --git a/server/tests/plugins/id-and-pass-auth.ts b/server/tests/plugins/id-and-pass-auth.ts index 99de28d3f..a0b31bc1f 100644 --- a/server/tests/plugins/id-and-pass-auth.ts +++ b/server/tests/plugins/id-and-pass-auth.ts @@ -15,8 +15,7 @@ import { setAccessTokensToServers, updateMyUser, userLogin, - wait, - waitUntilLog + wait } from '@shared/extra-utils' import { User, UserRole } from '@shared/models' @@ -137,7 +136,7 @@ describe('Test id and pass auth plugins', function () { }) it('Should have logged out Crash', async function () { - await waitUntilLog(server, 'On logout for auth 1 - 2') + await server.serversCommand.waitUntilLog('On logout for auth 1 - 2') await getMyUserInformation(server.url, crashAccessToken, 401) }) @@ -164,16 +163,16 @@ describe('Test id and pass auth plugins', function () { it('Should reject an invalid username, email, role or display name', async function () { await userLogin(server, { username: 'ward', password: 'ward password' }, 400) - await waitUntilLog(server, 'valid username') + await server.serversCommand.waitUntilLog('valid username') await userLogin(server, { username: 'kiros', password: 'kiros password' }, 400) - await waitUntilLog(server, 'valid display name') + await server.serversCommand.waitUntilLog('valid display name') await userLogin(server, { username: 'raine', password: 'raine password' }, 400) - await waitUntilLog(server, 'valid role') + await server.serversCommand.waitUntilLog('valid role') await userLogin(server, { username: 'ellone', password: 'elonne password' }, 400) - await waitUntilLog(server, 'valid email') + await server.serversCommand.waitUntilLog('valid email') }) it('Should unregister spyro-auth and do not login existing Spyro', async function () { diff --git a/server/tests/plugins/plugin-helpers.ts b/server/tests/plugins/plugin-helpers.ts index 0e0f61638..cbb6887eb 100644 --- a/server/tests/plugins/plugin-helpers.ts +++ b/server/tests/plugins/plugin-helpers.ts @@ -17,8 +17,7 @@ import { setAccessTokensToServers, uploadVideoAndGetId, viewVideo, - waitJobs, - waitUntilLog + waitJobs } from '@shared/extra-utils' function postCommand (server: ServerInfo, command: string, bodyArg?: object) { @@ -50,22 +49,22 @@ describe('Test plugin helpers', function () { describe('Logger', function () { it('Should have logged things', async function () { - await waitUntilLog(servers[0], 'localhost:' + servers[0].port + ' peertube-plugin-test-four', 1, false) - await waitUntilLog(servers[0], 'Hello world from plugin four', 1) + await servers[0].serversCommand.waitUntilLog('localhost:' + servers[0].port + ' peertube-plugin-test-four', 1, false) + await servers[0].serversCommand.waitUntilLog('Hello world from plugin four', 1) }) }) describe('Database', function () { it('Should have made a query', async function () { - await waitUntilLog(servers[0], `root email is admin${servers[0].internalServerNumber}@example.com`) + await servers[0].serversCommand.waitUntilLog(`root email is admin${servers[0].internalServerNumber}@example.com`) }) }) describe('Config', function () { it('Should have the correct webserver url', async function () { - await waitUntilLog(servers[0], `server url is http://localhost:${servers[0].port}`) + await servers[0].serversCommand.waitUntilLog(`server url is http://localhost:${servers[0].port}`) }) it('Should have the correct config', async function () { @@ -83,7 +82,7 @@ describe('Test plugin helpers', function () { describe('Server', function () { it('Should get the server actor', async function () { - await waitUntilLog(servers[0], 'server actor name is peertube') + await servers[0].serversCommand.waitUntilLog('server actor name is peertube') }) }) @@ -248,7 +247,7 @@ describe('Test plugin helpers', function () { // Should delete the video await viewVideo(servers[0].url, videoUUID) - await waitUntilLog(servers[0], 'Video deleted by plugin four.') + await servers[0].serversCommand.waitUntilLog('Video deleted by plugin four.') try { // Should throw because the video should have been deleted @@ -258,11 +257,11 @@ describe('Test plugin helpers', function () { if (err.message.includes('exists')) throw err } - await checkVideoFilesWereRemoved(videoUUID, servers[0].internalServerNumber) + await checkVideoFilesWereRemoved(videoUUID, servers[0]) }) it('Should have fetched the video by URL', async function () { - await waitUntilLog(servers[0], `video from DB uuid is ${videoUUID}`) + await servers[0].serversCommand.waitUntilLog(`video from DB uuid is ${videoUUID}`) }) }) diff --git a/server/tests/plugins/plugin-storage.ts b/server/tests/plugins/plugin-storage.ts index 4c65463f2..9babfc83e 100644 --- a/server/tests/plugins/plugin-storage.ts +++ b/server/tests/plugins/plugin-storage.ts @@ -5,16 +5,7 @@ import { expect } from 'chai' import { pathExists, readdir, readFile } from 'fs-extra' import { join } from 'path' import { HttpStatusCode } from '@shared/core-utils' -import { - buildServerDirectory, - cleanupTests, - flushAndRunServer, - makeGetRequest, - PluginsCommand, - ServerInfo, - setAccessTokensToServers, - waitUntilLog -} from '@shared/extra-utils' +import { cleanupTests, flushAndRunServer, makeGetRequest, PluginsCommand, ServerInfo, setAccessTokensToServers } from '@shared/extra-utils' describe('Test plugin storage', function () { let server: ServerInfo @@ -31,7 +22,7 @@ describe('Test plugin storage', function () { describe('DB storage', function () { it('Should correctly store a subkey', async function () { - await waitUntilLog(server, 'superkey stored value is toto') + await server.serversCommand.waitUntilLog('superkey stored value is toto') }) }) @@ -47,12 +38,12 @@ describe('Test plugin storage', function () { } before(function () { - dataPath = buildServerDirectory(server, 'plugins/data') + dataPath = server.serversCommand.buildDirectory('plugins/data') pluginDataPath = join(dataPath, 'peertube-plugin-test-six') }) it('Should have created the directory on install', async function () { - const dataPath = buildServerDirectory(server, 'plugins/data') + const dataPath = server.serversCommand.buildDirectory('plugins/data') const pluginDataPath = join(dataPath, 'peertube-plugin-test-six') expect(await pathExists(dataPath)).to.be.true diff --git a/server/tests/plugins/plugin-transcoding.ts b/server/tests/plugins/plugin-transcoding.ts index ca4d9f962..4839e8792 100644 --- a/server/tests/plugins/plugin-transcoding.ts +++ b/server/tests/plugins/plugin-transcoding.ts @@ -5,7 +5,6 @@ import { expect } from 'chai' import { join } from 'path' import { getAudioStream, getVideoFileFPS, getVideoStreamFromFile } from '@server/helpers/ffprobe-utils' import { - buildServerDirectory, cleanupTests, flushAndRunServer, getVideo, @@ -247,7 +246,7 @@ describe('Test transcoding plugins', function () { const videoUUID = (await uploadVideoAndGetId({ server, videoName: 'video', fixture: 'video_short_240p.mp4' })).uuid await waitJobs([ server ]) - const path = buildServerDirectory(server, join('videos', videoUUID + '-240.mp4')) + const path = server.serversCommand.buildDirectory(join('videos', videoUUID + '-240.mp4')) const audioProbe = await getAudioStream(path) expect(audioProbe.audioStream.codec_name).to.equal('opus') diff --git a/shared/extra-utils/miscs/checks.ts b/shared/extra-utils/miscs/checks.ts new file mode 100644 index 000000000..86b861cd2 --- /dev/null +++ b/shared/extra-utils/miscs/checks.ts @@ -0,0 +1,46 @@ +/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/no-floating-promises */ + +import { expect } from 'chai' +import { pathExists, readFile } from 'fs-extra' +import { join } from 'path' +import { root } from '@server/helpers/core-utils' +import { HttpStatusCode } from '@shared/core-utils' +import { makeGetRequest } from '../requests' +import { ServerInfo } from '../server' + +// Default interval -> 5 minutes +function dateIsValid (dateString: string, interval = 300000) { + const dateToCheck = new Date(dateString) + const now = new Date() + + return Math.abs(now.getTime() - dateToCheck.getTime()) <= interval +} + +async function testImage (url: string, imageName: string, imagePath: string, extension = '.jpg') { + const res = await makeGetRequest({ + url, + path: imagePath, + statusCodeExpected: HttpStatusCode.OK_200 + }) + + const body = res.body + + const data = await readFile(join(root(), 'server', 'tests', 'fixtures', imageName + extension)) + const minLength = body.length - ((30 * body.length) / 100) + const maxLength = body.length + ((30 * body.length) / 100) + + expect(data.length).to.be.above(minLength, 'the generated image is way smaller than the recorded fixture') + expect(data.length).to.be.below(maxLength, 'the generated image is way larger than the recorded fixture') +} + +async function testFileExistsOrNot (server: ServerInfo, directory: string, filePath: string, exist: boolean) { + const base = server.serversCommand.buildDirectory(directory) + + expect(await pathExists(join(base, filePath))).to.equal(exist) +} + +export { + dateIsValid, + testImage, + testFileExistsOrNot +} diff --git a/shared/extra-utils/miscs/generate.ts b/shared/extra-utils/miscs/generate.ts new file mode 100644 index 000000000..4e70ab853 --- /dev/null +++ b/shared/extra-utils/miscs/generate.ts @@ -0,0 +1,61 @@ +import { ensureDir, pathExists } from 'fs-extra' +import { dirname } from 'path' +import { buildAbsoluteFixturePath } from './tests' +import * as ffmpeg from 'fluent-ffmpeg' + +async function generateHighBitrateVideo () { + const tempFixturePath = buildAbsoluteFixturePath('video_high_bitrate_1080p.mp4', true) + + await ensureDir(dirname(tempFixturePath)) + + const exists = await pathExists(tempFixturePath) + if (!exists) { + console.log('Generating high bitrate video.') + + // Generate a random, high bitrate video on the fly, so we don't have to include + // a large file in the repo. The video needs to have a certain minimum length so + // that FFmpeg properly applies bitrate limits. + // https://stackoverflow.com/a/15795112 + return new Promise((res, rej) => { + ffmpeg() + .outputOptions([ '-f rawvideo', '-video_size 1920x1080', '-i /dev/urandom' ]) + .outputOptions([ '-ac 2', '-f s16le', '-i /dev/urandom', '-t 10' ]) + .outputOptions([ '-maxrate 10M', '-bufsize 10M' ]) + .output(tempFixturePath) + .on('error', rej) + .on('end', () => res(tempFixturePath)) + .run() + }) + } + + return tempFixturePath +} + +async function generateVideoWithFramerate (fps = 60) { + const tempFixturePath = buildAbsoluteFixturePath(`video_${fps}fps.mp4`, true) + + await ensureDir(dirname(tempFixturePath)) + + const exists = await pathExists(tempFixturePath) + if (!exists) { + console.log('Generating video with framerate %d.', fps) + + return new Promise((res, rej) => { + ffmpeg() + .outputOptions([ '-f rawvideo', '-video_size 1280x720', '-i /dev/urandom' ]) + .outputOptions([ '-ac 2', '-f s16le', '-i /dev/urandom', '-t 10' ]) + .outputOptions([ `-r ${fps}` ]) + .output(tempFixturePath) + .on('error', rej) + .on('end', () => res(tempFixturePath)) + .run() + }) + } + + return tempFixturePath +} + +export { + generateHighBitrateVideo, + generateVideoWithFramerate +} diff --git a/shared/extra-utils/miscs/index.ts b/shared/extra-utils/miscs/index.ts index 7e236c329..4474661de 100644 --- a/shared/extra-utils/miscs/index.ts +++ b/shared/extra-utils/miscs/index.ts @@ -1,3 +1,5 @@ -export * from './miscs' +export * from './checks' +export * from './generate' export * from './sql-command' -export * from './stubs' +export * from './tests' +export * from './webtorrent' diff --git a/shared/extra-utils/miscs/miscs.ts b/shared/extra-utils/miscs/miscs.ts deleted file mode 100644 index 462b914d4..000000000 --- a/shared/extra-utils/miscs/miscs.ts +++ /dev/null @@ -1,170 +0,0 @@ -/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ - -import * as chai from 'chai' -import * as ffmpeg from 'fluent-ffmpeg' -import { ensureDir, pathExists, readFile, stat } from 'fs-extra' -import { basename, dirname, isAbsolute, join, resolve } from 'path' -import * as request from 'supertest' -import * as WebTorrent from 'webtorrent' -import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' - -const expect = chai.expect -let webtorrent: WebTorrent.Instance - -function immutableAssign (target: T, source: U) { - return Object.assign<{}, T, U>({}, target, source) -} - -// Default interval -> 5 minutes -function dateIsValid (dateString: string, interval = 300000) { - const dateToCheck = new Date(dateString) - const now = new Date() - - return Math.abs(now.getTime() - dateToCheck.getTime()) <= interval -} - -function wait (milliseconds: number) { - return new Promise(resolve => setTimeout(resolve, milliseconds)) -} - -function webtorrentAdd (torrent: string, refreshWebTorrent = false) { - const WebTorrent = require('webtorrent') - - if (!webtorrent) webtorrent = new WebTorrent() - if (refreshWebTorrent === true) webtorrent = new WebTorrent() - - return new Promise(res => webtorrent.add(torrent, res)) -} - -function root () { - // We are in /miscs - let root = join(__dirname, '..', '..', '..') - - if (basename(root) === 'dist') root = resolve(root, '..') - - return root -} - -function buildServerDirectory (server: { internalServerNumber: number }, directory: string) { - return join(root(), 'test' + server.internalServerNumber, directory) -} - -async function testImage (url: string, imageName: string, imagePath: string, extension = '.jpg') { - const res = await request(url) - .get(imagePath) - .expect(HttpStatusCode.OK_200) - - const body = res.body - - const data = await readFile(join(root(), 'server', 'tests', 'fixtures', imageName + extension)) - const minLength = body.length - ((30 * body.length) / 100) - const maxLength = body.length + ((30 * body.length) / 100) - - expect(data.length).to.be.above(minLength, 'the generated image is way smaller than the recorded fixture') - expect(data.length).to.be.below(maxLength, 'the generated image is way larger than the recorded fixture') -} - -async function testFileExistsOrNot (server: { internalServerNumber: number }, directory: string, filePath: string, exist: boolean) { - const base = buildServerDirectory(server, directory) - - expect(await pathExists(join(base, filePath))).to.equal(exist) -} - -function isGithubCI () { - return !!process.env.GITHUB_WORKSPACE -} - -function buildAbsoluteFixturePath (path: string, customCIPath = false) { - if (isAbsolute(path)) return path - - if (customCIPath && process.env.GITHUB_WORKSPACE) { - return join(process.env.GITHUB_WORKSPACE, 'fixtures', path) - } - - return join(root(), 'server', 'tests', 'fixtures', path) -} - -function areHttpImportTestsDisabled () { - const disabled = process.env.DISABLE_HTTP_IMPORT_TESTS === 'true' - - if (disabled) console.log('Import tests are disabled') - - return disabled -} - -async function generateHighBitrateVideo () { - const tempFixturePath = buildAbsoluteFixturePath('video_high_bitrate_1080p.mp4', true) - - await ensureDir(dirname(tempFixturePath)) - - const exists = await pathExists(tempFixturePath) - if (!exists) { - console.log('Generating high bitrate video.') - - // Generate a random, high bitrate video on the fly, so we don't have to include - // a large file in the repo. The video needs to have a certain minimum length so - // that FFmpeg properly applies bitrate limits. - // https://stackoverflow.com/a/15795112 - return new Promise((res, rej) => { - ffmpeg() - .outputOptions([ '-f rawvideo', '-video_size 1920x1080', '-i /dev/urandom' ]) - .outputOptions([ '-ac 2', '-f s16le', '-i /dev/urandom', '-t 10' ]) - .outputOptions([ '-maxrate 10M', '-bufsize 10M' ]) - .output(tempFixturePath) - .on('error', rej) - .on('end', () => res(tempFixturePath)) - .run() - }) - } - - return tempFixturePath -} - -async function generateVideoWithFramerate (fps = 60) { - const tempFixturePath = buildAbsoluteFixturePath(`video_${fps}fps.mp4`, true) - - await ensureDir(dirname(tempFixturePath)) - - const exists = await pathExists(tempFixturePath) - if (!exists) { - console.log('Generating video with framerate %d.', fps) - - return new Promise((res, rej) => { - ffmpeg() - .outputOptions([ '-f rawvideo', '-video_size 1280x720', '-i /dev/urandom' ]) - .outputOptions([ '-ac 2', '-f s16le', '-i /dev/urandom', '-t 10' ]) - .outputOptions([ `-r ${fps}` ]) - .output(tempFixturePath) - .on('error', rej) - .on('end', () => res(tempFixturePath)) - .run() - }) - } - - return tempFixturePath -} - -async function getFileSize (path: string) { - const stats = await stat(path) - - return stats.size -} - -// --------------------------------------------------------------------------- - -export { - dateIsValid, - wait, - areHttpImportTestsDisabled, - buildServerDirectory, - webtorrentAdd, - getFileSize, - immutableAssign, - testImage, - isGithubCI, - buildAbsoluteFixturePath, - testFileExistsOrNot, - root, - generateHighBitrateVideo, - generateVideoWithFramerate -} diff --git a/shared/extra-utils/miscs/sql-command.ts b/shared/extra-utils/miscs/sql-command.ts index 2a3e9e607..80c8cd271 100644 --- a/shared/extra-utils/miscs/sql-command.ts +++ b/shared/extra-utils/miscs/sql-command.ts @@ -1,5 +1,5 @@ import { QueryTypes, Sequelize } from 'sequelize' -import { AbstractCommand } from '../shared' +import { AbstractCommand } from '../shared/abstract-command' export class SQLCommand extends AbstractCommand { private sequelize: Sequelize diff --git a/shared/extra-utils/miscs/stubs.ts b/shared/extra-utils/miscs/stubs.ts deleted file mode 100644 index 940e4bf29..000000000 --- a/shared/extra-utils/miscs/stubs.ts +++ /dev/null @@ -1,7 +0,0 @@ -function buildRequestStub (): any { - return { } -} - -export { - buildRequestStub -} diff --git a/shared/extra-utils/miscs/tests.ts b/shared/extra-utils/miscs/tests.ts new file mode 100644 index 000000000..8f7a2f92b --- /dev/null +++ b/shared/extra-utils/miscs/tests.ts @@ -0,0 +1,62 @@ +import { stat } from 'fs-extra' +import { basename, isAbsolute, join, resolve } from 'path' + +function parallelTests () { + return process.env.MOCHA_PARALLEL === 'true' +} + +function isGithubCI () { + return !!process.env.GITHUB_WORKSPACE +} + +function areHttpImportTestsDisabled () { + const disabled = process.env.DISABLE_HTTP_IMPORT_TESTS === 'true' + + if (disabled) console.log('Import tests are disabled') + + return disabled +} + +function buildAbsoluteFixturePath (path: string, customCIPath = false) { + if (isAbsolute(path)) return path + + if (customCIPath && process.env.GITHUB_WORKSPACE) { + return join(process.env.GITHUB_WORKSPACE, 'fixtures', path) + } + + return join(root(), 'server', 'tests', 'fixtures', path) +} + +function root () { + // We are in /miscs + let root = join(__dirname, '..', '..', '..') + + if (basename(root) === 'dist') root = resolve(root, '..') + + return root +} + +function wait (milliseconds: number) { + return new Promise(resolve => setTimeout(resolve, milliseconds)) +} + +async function getFileSize (path: string) { + const stats = await stat(path) + + return stats.size +} + +function buildRequestStub (): any { + return { } +} + +export { + parallelTests, + isGithubCI, + areHttpImportTestsDisabled, + buildAbsoluteFixturePath, + getFileSize, + buildRequestStub, + wait, + root +} diff --git a/shared/extra-utils/miscs/webtorrent.ts b/shared/extra-utils/miscs/webtorrent.ts new file mode 100644 index 000000000..82548946d --- /dev/null +++ b/shared/extra-utils/miscs/webtorrent.ts @@ -0,0 +1,16 @@ +import * as WebTorrent from 'webtorrent' + +let webtorrent: WebTorrent.Instance + +function webtorrentAdd (torrent: string, refreshWebTorrent = false) { + const WebTorrent = require('webtorrent') + + if (!webtorrent) webtorrent = new WebTorrent() + if (refreshWebTorrent === true) webtorrent = new WebTorrent() + + return new Promise(res => webtorrent.add(torrent, res)) +} + +export { + webtorrentAdd +} diff --git a/shared/extra-utils/mock-servers/mock-email.ts b/shared/extra-utils/mock-servers/mock-email.ts index 9fc9a5ad0..ffd62e325 100644 --- a/shared/extra-utils/mock-servers/mock-email.ts +++ b/shared/extra-utils/mock-servers/mock-email.ts @@ -1,6 +1,6 @@ import { ChildProcess } from 'child_process' -import { randomInt } from '../../core-utils/miscs/miscs' -import { parallelTests } from '../server/servers' +import { randomInt } from '@shared/core-utils' +import { parallelTests } from '../miscs' const MailDev = require('maildev') diff --git a/shared/extra-utils/requests/check-api-params.ts b/shared/extra-utils/requests/check-api-params.ts index 7f5ff775c..7df63b004 100644 --- a/shared/extra-utils/requests/check-api-params.ts +++ b/shared/extra-utils/requests/check-api-params.ts @@ -1,13 +1,12 @@ +import { HttpStatusCode } from '@shared/core-utils' import { makeGetRequest } from './requests' -import { immutableAssign } from '../miscs/miscs' -import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' function checkBadStartPagination (url: string, path: string, token?: string, query = {}) { return makeGetRequest({ url, path, token, - query: immutableAssign(query, { start: 'hello' }), + query: { ...query, start: 'hello' }, statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) } @@ -17,7 +16,7 @@ async function checkBadCountPagination (url: string, path: string, token?: strin url, path, token, - query: immutableAssign(query, { count: 'hello' }), + query: { ...query, count: 'hello' }, statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) @@ -25,7 +24,7 @@ async function checkBadCountPagination (url: string, path: string, token?: strin url, path, token, - query: immutableAssign(query, { count: 2000 }), + query: { ...query, count: 2000 }, statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) } @@ -35,7 +34,7 @@ function checkBadSortPagination (url: string, path: string, token?: string, quer url, path, token, - query: immutableAssign(query, { sort: 'hello' }), + query: { ...query, sort: 'hello' }, statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) } diff --git a/shared/extra-utils/requests/requests.ts b/shared/extra-utils/requests/requests.ts index 3fbaa31d6..f9d112aca 100644 --- a/shared/extra-utils/requests/requests.ts +++ b/shared/extra-utils/requests/requests.ts @@ -4,8 +4,8 @@ import { isAbsolute, join } from 'path' import { decode } from 'querystring' import * as request from 'supertest' import { URL } from 'url' -import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' -import { buildAbsoluteFixturePath, root } from '../miscs/miscs' +import { HttpStatusCode } from '@shared/core-utils' +import { buildAbsoluteFixturePath, root } from '../miscs/tests' function get4KFileUrl () { return 'https://download.cpy.re/peertube/4k_file.txt' diff --git a/shared/extra-utils/server/directories.ts b/shared/extra-utils/server/directories.ts new file mode 100644 index 000000000..3cd38a561 --- /dev/null +++ b/shared/extra-utils/server/directories.ts @@ -0,0 +1,34 @@ +/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ + +import { expect } from 'chai' +import { pathExists, readdir } from 'fs-extra' +import { join } from 'path' +import { root } from '@server/helpers/core-utils' +import { ServerInfo } from './servers' + +async function checkTmpIsEmpty (server: ServerInfo) { + await checkDirectoryIsEmpty(server, 'tmp', [ 'plugins-global.css', 'hls', 'resumable-uploads' ]) + + if (await pathExists(join('test' + server.internalServerNumber, 'tmp', 'hls'))) { + await checkDirectoryIsEmpty(server, 'tmp/hls') + } +} + +async function checkDirectoryIsEmpty (server: ServerInfo, directory: string, exceptions: string[] = []) { + const testDirectory = 'test' + server.internalServerNumber + + const directoryPath = join(root(), testDirectory, directory) + + const directoryExists = await pathExists(directoryPath) + expect(directoryExists).to.be.true + + const files = await readdir(directoryPath) + const filtered = files.filter(f => exceptions.includes(f) === false) + + expect(filtered).to.have.lengthOf(0) +} + +export { + checkTmpIsEmpty, + checkDirectoryIsEmpty +} diff --git a/shared/extra-utils/server/index.ts b/shared/extra-utils/server/index.ts index 03c3b0123..669b004cd 100644 --- a/shared/extra-utils/server/index.ts +++ b/shared/extra-utils/server/index.ts @@ -1,6 +1,7 @@ export * from './config-command' export * from './contact-form-command' export * from './debug-command' +export * from './directories' export * from './follows-command' export * from './follows' export * from './jobs' @@ -8,5 +9,6 @@ export * from './jobs-command' export * from './plugins-command' export * from './plugins' export * from './redundancy-command' +export * from './servers-command' export * from './servers' export * from './stats-command' diff --git a/shared/extra-utils/server/jobs.ts b/shared/extra-utils/server/jobs.ts index b4b3d52e7..36ef882b3 100644 --- a/shared/extra-utils/server/jobs.ts +++ b/shared/extra-utils/server/jobs.ts @@ -1,6 +1,6 @@ import { JobState } from '../../models' -import { wait } from '../miscs/miscs' +import { wait } from '../miscs' import { ServerInfo } from './servers' async function waitJobs (serversArg: ServerInfo[] | ServerInfo) { diff --git a/shared/extra-utils/server/plugins-command.ts b/shared/extra-utils/server/plugins-command.ts index ff49d58c4..5bed51d1a 100644 --- a/shared/extra-utils/server/plugins-command.ts +++ b/shared/extra-utils/server/plugins-command.ts @@ -15,7 +15,6 @@ import { RegisteredServerSettings, ResultList } from '@shared/models' -import { buildServerDirectory } from '../miscs' import { AbstractCommand, OverrideCommandOptions } from '../shared' export class PluginsCommand extends AbstractCommand { @@ -252,6 +251,6 @@ export class PluginsCommand extends AbstractCommand { } private getPackageJSONPath (npmName: string) { - return buildServerDirectory(this.server, join('plugins', 'node_modules', npmName, 'package.json')) + return this.server.serversCommand.buildDirectory(join('plugins', 'node_modules', npmName, 'package.json')) } } diff --git a/shared/extra-utils/server/servers-command.ts b/shared/extra-utils/server/servers-command.ts new file mode 100644 index 000000000..9ef68fede --- /dev/null +++ b/shared/extra-utils/server/servers-command.ts @@ -0,0 +1,81 @@ +import { exec } from 'child_process' +import { copy, ensureDir, readFile, remove } from 'fs-extra' +import { join } from 'path' +import { root } from '@server/helpers/core-utils' +import { HttpStatusCode } from '@shared/core-utils' +import { getFileSize } from '@uploadx/core' +import { isGithubCI, wait } from '../miscs' +import { AbstractCommand, OverrideCommandOptions } from '../shared' + +export class ServersCommand extends AbstractCommand { + + static flushTests (internalServerNumber: number) { + return new Promise((res, rej) => { + const suffix = ` -- ${internalServerNumber}` + + return exec('npm run clean:server:test' + suffix, (err, _stdout, stderr) => { + if (err || stderr) return rej(err || new Error(stderr)) + + return res() + }) + }) + } + + ping (options: OverrideCommandOptions = {}) { + return this.getRequestBody({ + ...options, + + path: '/api/v1/ping', + implicitToken: false, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } + + async cleanupTests () { + const p: Promise[] = [] + + if (isGithubCI()) { + await ensureDir('artifacts') + + const origin = this.server.serversCommand.buildDirectory('logs/peertube.log') + const destname = `peertube-${this.server.internalServerNumber}.log` + console.log('Saving logs %s.', destname) + + await copy(origin, join('artifacts', destname)) + } + + if (this.server.parallel) { + p.push(ServersCommand.flushTests(this.server.internalServerNumber)) + } + + if (this.server.customConfigFile) { + p.push(remove(this.server.customConfigFile)) + } + + return p + } + + async waitUntilLog (str: string, count = 1, strictCount = true) { + const logfile = this.server.serversCommand.buildDirectory('logs/peertube.log') + + while (true) { + const buf = await readFile(logfile) + + const matches = buf.toString().match(new RegExp(str, 'g')) + if (matches && matches.length === count) return + if (matches && strictCount === false && matches.length >= count) return + + await wait(1000) + } + } + + buildDirectory (directory: string) { + return join(root(), 'test' + this.server.internalServerNumber, directory) + } + + async getServerFileSize (subPath: string) { + const path = this.server.serversCommand.buildDirectory(subPath) + + return getFileSize(path) + } +} diff --git a/shared/extra-utils/server/servers.ts b/shared/extra-utils/server/servers.ts index e0e49d2c4..f5dc0326f 100644 --- a/shared/extra-utils/server/servers.ts +++ b/shared/extra-utils/server/servers.ts @@ -1,9 +1,9 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/no-floating-promises */ -import { expect } from 'chai' -import { ChildProcess, exec, fork } from 'child_process' -import { copy, ensureDir, pathExists, readdir, readFile, remove } from 'fs-extra' +import { ChildProcess, fork } from 'child_process' +import { copy, ensureDir } from 'fs-extra' import { join } from 'path' +import { root } from '@server/helpers/core-utils' import { randomInt } from '../../core-utils/miscs/miscs' import { VideoChannel } from '../../models/videos' import { BulkCommand } from '../bulk' @@ -11,11 +11,9 @@ import { CLICommand } from '../cli' import { CustomPagesCommand } from '../custom-pages' import { FeedCommand } from '../feeds' import { LogsCommand } from '../logs' -import { SQLCommand } from '../miscs' -import { buildServerDirectory, getFileSize, isGithubCI, root, wait } from '../miscs/miscs' +import { isGithubCI, parallelTests, SQLCommand } from '../miscs' import { AbusesCommand } from '../moderation' import { OverviewsCommand } from '../overviews' -import { makeGetRequest } from '../requests/requests' import { SearchCommand } from '../search' import { SocketIOCommand } from '../socket' import { AccountsCommand, BlocklistCommand, NotificationsCommand, SubscriptionsCommand } from '../users' @@ -39,6 +37,7 @@ import { FollowsCommand } from './follows-command' import { JobsCommand } from './jobs-command' import { PluginsCommand } from './plugins-command' import { RedundancyCommand } from './redundancy-command' +import { ServersCommand } from './servers-command' import { StatsCommand } from './stats-command' interface ServerInfo { @@ -126,10 +125,7 @@ interface ServerInfo { commentsCommand?: CommentsCommand sqlCommand?: SQLCommand notificationsCommand?: NotificationsCommand -} - -function parallelTests () { - return process.env.MOCHA_PARALLEL === 'true' + serversCommand?: ServersCommand } function flushAndRunMultipleServers (totalServers: number, configOverride?: Object) { @@ -151,18 +147,6 @@ function flushAndRunMultipleServers (totalServers: number, configOverride?: Obje }) } -function flushTests (serverNumber?: number) { - return new Promise((res, rej) => { - const suffix = serverNumber ? ` -- ${serverNumber}` : '' - - return exec('npm run clean:server:test' + suffix, (err, _stdout, stderr) => { - if (err || stderr) return rej(err || new Error(stderr)) - - return res() - }) - }) -} - function randomServer () { const low = 10 const high = 10000 @@ -189,7 +173,7 @@ async function flushAndRunServer (serverNumber: number, configOverride?: Object, const rtmpPort = parallel ? randomRTMP() : 1936 const port = 9000 + internalServerNumber - await flushTests(internalServerNumber) + await ServersCommand.flushTests(internalServerNumber) const server: ServerInfo = { app: null, @@ -372,6 +356,7 @@ function assignCommands (server: ServerInfo) { server.commentsCommand = new CommentsCommand(server) server.sqlCommand = new SQLCommand(server) server.notificationsCommand = new NotificationsCommand(server) + server.serversCommand = new ServersCommand(server) } async function reRunServer (server: ServerInfo, configOverride?: any) { @@ -381,28 +366,6 @@ async function reRunServer (server: ServerInfo, configOverride?: any) { return server } -async function checkTmpIsEmpty (server: ServerInfo) { - await checkDirectoryIsEmpty(server, 'tmp', [ 'plugins-global.css', 'hls', 'resumable-uploads' ]) - - if (await pathExists(join('test' + server.internalServerNumber, 'tmp', 'hls'))) { - await checkDirectoryIsEmpty(server, 'tmp/hls') - } -} - -async function checkDirectoryIsEmpty (server: ServerInfo, directory: string, exceptions: string[] = []) { - const testDirectory = 'test' + server.internalServerNumber - - const directoryPath = join(root(), testDirectory, directory) - - const directoryExists = await pathExists(directoryPath) - expect(directoryExists).to.be.true - - const files = await readdir(directoryPath) - const filtered = files.filter(f => exceptions.includes(f) === false) - - expect(filtered).to.have.lengthOf(0) -} - async function killallServers (servers: ServerInfo[]) { for (const server of servers) { if (!server.app) continue @@ -422,71 +385,22 @@ async function cleanupTests (servers: ServerInfo[]) { await ensureDir('artifacts') } - const p: Promise[] = [] + let p: Promise[] = [] for (const server of servers) { - if (isGithubCI()) { - const origin = await buildServerDirectory(server, 'logs/peertube.log') - const destname = `peertube-${server.internalServerNumber}.log` - console.log('Saving logs %s.', destname) - - await copy(origin, join('artifacts', destname)) - } - - if (server.parallel) { - p.push(flushTests(server.internalServerNumber)) - } - - if (server.customConfigFile) { - p.push(remove(server.customConfigFile)) - } + p = p.concat(server.serversCommand.cleanupTests()) } return Promise.all(p) } -async function waitUntilLog (server: ServerInfo, str: string, count = 1, strictCount = true) { - const logfile = buildServerDirectory(server, 'logs/peertube.log') - - while (true) { - const buf = await readFile(logfile) - - const matches = buf.toString().match(new RegExp(str, 'g')) - if (matches && matches.length === count) return - if (matches && strictCount === false && matches.length >= count) return - - await wait(1000) - } -} - -async function getServerFileSize (server: ServerInfo, subPath: string) { - const path = buildServerDirectory(server, subPath) - - return getFileSize(path) -} - -function makePingRequest (server: ServerInfo) { - return makeGetRequest({ - url: server.url, - path: '/api/v1/ping', - statusCodeExpected: 200 - }) -} - // --------------------------------------------------------------------------- export { - checkDirectoryIsEmpty, - checkTmpIsEmpty, - getServerFileSize, ServerInfo, - parallelTests, cleanupTests, flushAndRunMultipleServers, - flushTests, - makePingRequest, flushAndRunServer, killallServers, reRunServer, - assignCommands, - waitUntilLog + assignCommands } diff --git a/shared/extra-utils/shared/abstract-command.ts b/shared/extra-utils/shared/abstract-command.ts index fd2deb57e..4e61554a2 100644 --- a/shared/extra-utils/shared/abstract-command.ts +++ b/shared/extra-utils/shared/abstract-command.ts @@ -1,6 +1,6 @@ import { isAbsolute, join } from 'path' import { HttpStatusCode } from '@shared/core-utils' -import { root } from '../miscs/miscs' +import { root } from '../miscs/tests' import { makeDeleteRequest, makeGetRequest, diff --git a/shared/extra-utils/videos/captions-command.ts b/shared/extra-utils/videos/captions-command.ts index 908b6dae6..ac3bde7a9 100644 --- a/shared/extra-utils/videos/captions-command.ts +++ b/shared/extra-utils/videos/captions-command.ts @@ -1,6 +1,6 @@ +import { HttpStatusCode } from '@shared/core-utils' import { ResultList, VideoCaption } from '@shared/models' -import { HttpStatusCode } from '../../core-utils/miscs/http-error-codes' -import { buildAbsoluteFixturePath } from '../miscs/miscs' +import { buildAbsoluteFixturePath } from '../miscs' import { AbstractCommand, OverrideCommandOptions } from '../shared' export class CaptionsCommand extends AbstractCommand { diff --git a/shared/extra-utils/videos/live-command.ts b/shared/extra-utils/videos/live-command.ts index 4f03c9127..a494e60fa 100644 --- a/shared/extra-utils/videos/live-command.ts +++ b/shared/extra-utils/videos/live-command.ts @@ -5,9 +5,8 @@ import { omit } from 'lodash' import { join } from 'path' import { LiveVideo, LiveVideoCreate, LiveVideoUpdate, VideoCreateResult, VideoDetails, VideoState } from '@shared/models' import { HttpStatusCode } from '../../core-utils/miscs/http-error-codes' -import { buildServerDirectory, wait } from '../miscs/miscs' +import { wait } from '../miscs' import { unwrapBody } from '../requests' -import { waitUntilLog } from '../server/servers' import { AbstractCommand, OverrideCommandOptions } from '../shared' import { sendRTMPStream, testFfmpegStreamError } from './live' import { getVideoWithToken } from './videos' @@ -116,7 +115,7 @@ export class LiveCommand extends AbstractCommand { const { resolution, segment, videoUUID } = options const segmentName = `${resolution}-00000${segment}.ts` - return waitUntilLog(this.server, `${videoUUID}/${segmentName}`, 2, false) + return this.server.serversCommand.waitUntilLog(`${videoUUID}/${segmentName}`, 2, false) } async waitUntilSaved (options: OverrideCommandOptions & { @@ -135,7 +134,7 @@ export class LiveCommand extends AbstractCommand { async countPlaylists (options: OverrideCommandOptions & { videoUUID: string }) { - const basePath = buildServerDirectory(this.server, 'streaming-playlists') + const basePath = this.server.serversCommand.buildDirectory('streaming-playlists') const hlsPath = join(basePath, 'hls', options.videoUUID) const files = await readdir(hlsPath) diff --git a/shared/extra-utils/videos/live.ts b/shared/extra-utils/videos/live.ts index 92cb9104c..0efcc2883 100644 --- a/shared/extra-utils/videos/live.ts +++ b/shared/extra-utils/videos/live.ts @@ -4,7 +4,7 @@ import { expect } from 'chai' import * as ffmpeg from 'fluent-ffmpeg' import { pathExists, readdir } from 'fs-extra' import { join } from 'path' -import { buildAbsoluteFixturePath, buildServerDirectory, wait } from '../miscs/miscs' +import { buildAbsoluteFixturePath, wait } from '../miscs' import { ServerInfo } from '../server/servers' function sendRTMPStream (rtmpBaseUrl: string, streamKey: string, fixtureName = 'video_short.mp4') { @@ -77,7 +77,7 @@ async function waitUntilLivePublishedOnAllServers (servers: ServerInfo[], videoI } async function checkLiveCleanup (server: ServerInfo, videoUUID: string, resolutions: number[] = []) { - const basePath = buildServerDirectory(server, 'streaming-playlists') + const basePath = server.serversCommand.buildDirectory('streaming-playlists') const hlsPath = join(basePath, 'hls', videoUUID) if (resolutions.length === 0) { diff --git a/shared/extra-utils/videos/playlists.ts b/shared/extra-utils/videos/playlists.ts index 023333c87..3dde52bb9 100644 --- a/shared/extra-utils/videos/playlists.ts +++ b/shared/extra-utils/videos/playlists.ts @@ -1,7 +1,7 @@ import { expect } from 'chai' import { readdir } from 'fs-extra' import { join } from 'path' -import { root } from '../' +import { root } from '../miscs' async function checkPlaylistFilesWereRemoved ( playlistUUID: string, diff --git a/shared/extra-utils/videos/videos.ts b/shared/extra-utils/videos/videos.ts index 920c93072..5dd71ce8b 100644 --- a/shared/extra-utils/videos/videos.ts +++ b/shared/extra-utils/videos/videos.ts @@ -13,15 +13,7 @@ import { HttpStatusCode } from '@shared/core-utils' import { BooleanBothQuery, VideosCommonQuery } from '@shared/models' import { loadLanguages, VIDEO_CATEGORIES, VIDEO_LANGUAGES, VIDEO_LICENCES, VIDEO_PRIVACIES } from '../../../server/initializers/constants' import { VideoDetails, VideoPrivacy } from '../../models/videos' -import { - buildAbsoluteFixturePath, - buildServerDirectory, - dateIsValid, - immutableAssign, - testImage, - wait, - webtorrentAdd -} from '../miscs/miscs' +import { buildAbsoluteFixturePath, dateIsValid, testImage, wait, webtorrentAdd } from '../miscs' import { makeGetRequest, makePutBodyRequest, makeRawRequest, makeUploadRequest } from '../requests/requests' import { waitJobs } from '../server/jobs' import { ServerInfo } from '../server/servers' @@ -165,7 +157,7 @@ function getVideosListWithToken (url: string, token: string, query: { nsfw?: Boo return request(url) .get(path) .set('Authorization', 'Bearer ' + token) - .query(immutableAssign(query, { sort: 'name' })) + .query({ sort: 'name', ...query }) .set('Accept', 'application/json') .expect(HttpStatusCode.OK_200) .expect('Content-Type', /json/) @@ -228,11 +220,7 @@ function getAccountVideos ( return makeGetRequest({ url, path, - query: immutableAssign(query, { - start, - count, - sort - }), + query: { ...query, start, count, sort }, token: accessToken, statusCodeExpected: HttpStatusCode.OK_200 }) @@ -252,11 +240,7 @@ function getVideoChannelVideos ( return makeGetRequest({ url, path, - query: immutableAssign(query, { - start, - count, - sort - }), + query: { ...query, start, count, sort }, token: accessToken, statusCodeExpected: HttpStatusCode.OK_200 }) @@ -320,7 +304,7 @@ async function removeAllVideos (server: ServerInfo) { async function checkVideoFilesWereRemoved ( videoUUID: string, - serverNumber: number, + server: ServerInfo, directories = [ 'redundancy', 'videos', @@ -333,7 +317,7 @@ async function checkVideoFilesWereRemoved ( ] ) { for (const directory of directories) { - const directoryPath = buildServerDirectory({ internalServerNumber: serverNumber }, directory) + const directoryPath = server.serversCommand.buildDirectory(directory) const directoryExists = await pathExists(directoryPath) if (directoryExists === false) continue @@ -607,7 +591,7 @@ function rateVideo (url: string, accessToken: string, id: number | string, ratin function parseTorrentVideo (server: ServerInfo, videoUUID: string, resolution: number) { return new Promise((res, rej) => { const torrentName = videoUUID + '-' + resolution + '.torrent' - const torrentPath = buildServerDirectory(server, join('torrents', torrentName)) + const torrentPath = server.serversCommand.buildDirectory(join('torrents', torrentName)) readFile(torrentPath, (err, data) => { if (err) return rej(err) -- cgit v1.2.3 From 41d1d075011174e73dccb74006181a92a618d7b4 Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Tue, 13 Jul 2021 11:05:15 +0200 Subject: Introduce login command --- server/tests/api/activitypub/fetch.ts | 3 +- server/tests/api/check-params/abuses.ts | 3 +- server/tests/api/check-params/blocklist.ts | 5 +- server/tests/api/check-params/bulk.ts | 5 +- server/tests/api/check-params/config.ts | 5 +- server/tests/api/check-params/custom-pages.ts | 5 +- server/tests/api/check-params/debug.ts | 5 +- server/tests/api/check-params/follows.ts | 5 +- server/tests/api/check-params/jobs.ts | 5 +- server/tests/api/check-params/live.ts | 7 +- server/tests/api/check-params/logs.ts | 5 +- server/tests/api/check-params/plugins.ts | 5 +- server/tests/api/check-params/redundancy.ts | 3 +- server/tests/api/check-params/upload-quota.ts | 5 +- .../tests/api/check-params/user-subscriptions.ts | 5 +- server/tests/api/check-params/users.ts | 9 +- server/tests/api/check-params/video-blacklist.ts | 5 +- server/tests/api/check-params/video-captions.ts | 5 +- server/tests/api/check-params/video-channels.ts | 5 +- server/tests/api/check-params/video-comments.ts | 7 +- server/tests/api/check-params/video-imports.ts | 7 +- server/tests/api/check-params/videos-filter.ts | 7 +- server/tests/api/check-params/videos.ts | 7 +- server/tests/api/moderation/abuses.ts | 3 +- .../tests/api/moderation/blocklist-notification.ts | 7 +- server/tests/api/moderation/blocklist.ts | 7 +- server/tests/api/moderation/video-blacklist.ts | 5 +- .../search/search-activitypub-video-channels.ts | 3 +- server/tests/api/server/bulk.ts | 11 +- server/tests/api/server/email.ts | 7 +- server/tests/api/server/follow-constraints.ts | 5 +- server/tests/api/server/follows.ts | 3 +- server/tests/api/server/reverse-proxy.ts | 23 ++-- server/tests/api/server/stats.ts | 3 +- server/tests/api/users/user-subscriptions.ts | 3 +- server/tests/api/users/users-multiple-servers.ts | 3 +- server/tests/api/users/users-verification.ts | 28 ++--- server/tests/api/users/users.ts | 91 +++++++------- server/tests/api/videos/multiple-servers.ts | 3 +- server/tests/api/videos/video-change-ownership.ts | 11 +- server/tests/api/videos/video-channels.ts | 3 +- server/tests/api/videos/video-comments.ts | 3 +- server/tests/api/videos/video-nsfw.ts | 5 +- server/tests/api/videos/video-playlists.ts | 6 +- server/tests/api/videos/video-privacy.ts | 23 ++-- server/tests/api/videos/videos-filter.ts | 11 +- server/tests/api/videos/videos-history.ts | 3 +- server/tests/cli/peertube.ts | 3 +- server/tests/cli/reset-password.ts | 13 +- server/tests/external-plugins/auth-ldap.ts | 27 +++-- server/tests/feeds/feeds.ts | 5 +- server/tests/plugins/action-hooks.ts | 3 +- server/tests/plugins/external-auth.ts | 57 ++++----- server/tests/plugins/id-and-pass-auth.ts | 49 ++++---- shared/extra-utils/requests/requests.ts | 4 + shared/extra-utils/server/clients.ts | 20 --- shared/extra-utils/server/servers.ts | 4 +- shared/extra-utils/shared/abstract-command.ts | 10 +- shared/extra-utils/users/index.ts | 1 + shared/extra-utils/users/login-command.ts | 134 +++++++++++++++++++++ shared/extra-utils/users/login.ts | 120 +----------------- shared/extra-utils/users/notifications.ts | 4 +- shared/extra-utils/users/users.ts | 5 +- 63 files changed, 409 insertions(+), 443 deletions(-) delete mode 100644 shared/extra-utils/server/clients.ts create mode 100644 shared/extra-utils/users/login-command.ts diff --git a/server/tests/api/activitypub/fetch.ts b/server/tests/api/activitypub/fetch.ts index d5e21404c..c1af23016 100644 --- a/server/tests/api/activitypub/fetch.ts +++ b/server/tests/api/activitypub/fetch.ts @@ -11,7 +11,6 @@ import { ServerInfo, setAccessTokensToServers, uploadVideo, - userLogin, waitJobs } from '../../../../shared/extra-utils' import { Video } from '../../../../shared/models/videos' @@ -36,7 +35,7 @@ describe('Test ActivityPub fetcher', function () { await createUser({ url: server.url, accessToken: server.accessToken, username: user.username, password: user.password }) } - const userAccessToken = await userLogin(servers[0], user) + const userAccessToken = await servers[0].loginCommand.getAccessToken(user) await uploadVideo(servers[0].url, servers[0].accessToken, { name: 'video root' }) const res = await uploadVideo(servers[0].url, servers[0].accessToken, { name: 'bad video root' }) diff --git a/server/tests/api/check-params/abuses.ts b/server/tests/api/check-params/abuses.ts index e158e50dc..14949d301 100644 --- a/server/tests/api/check-params/abuses.ts +++ b/server/tests/api/check-params/abuses.ts @@ -18,7 +18,6 @@ import { ServerInfo, setAccessTokensToServers, uploadVideo, - userLogin, waitJobs } from '@shared/extra-utils' import { AbuseCreate, AbuseState } from '@shared/models' @@ -47,7 +46,7 @@ describe('Test abuses API validators', function () { const username = 'user1' const password = 'my super password' await createUser({ url: server.url, accessToken: server.accessToken, username: username, password: password }) - userToken = await userLogin(server, { username, password }) + userToken = await server.loginCommand.getAccessToken({ username, password }) userToken2 = await generateUserAccessToken(server, 'user_2') diff --git a/server/tests/api/check-params/blocklist.ts b/server/tests/api/check-params/blocklist.ts index 5ed8810ce..11a79387f 100644 --- a/server/tests/api/check-params/blocklist.ts +++ b/server/tests/api/check-params/blocklist.ts @@ -11,8 +11,7 @@ import { makeGetRequest, makePostBodyRequest, ServerInfo, - setAccessTokensToServers, - userLogin + setAccessTokensToServers } from '../../../../shared/extra-utils' import { checkBadCountPagination, @@ -37,7 +36,7 @@ describe('Test blocklist API validators', function () { const user = { username: 'user1', password: 'password' } await createUser({ url: server.url, accessToken: server.accessToken, username: user.username, password: user.password }) - userAccessToken = await userLogin(server, user) + userAccessToken = await server.loginCommand.getAccessToken(user) await doubleFollow(servers[0], servers[1]) }) diff --git a/server/tests/api/check-params/bulk.ts b/server/tests/api/check-params/bulk.ts index 07b920ba7..85520b3bd 100644 --- a/server/tests/api/check-params/bulk.ts +++ b/server/tests/api/check-params/bulk.ts @@ -6,8 +6,7 @@ import { createUser, flushAndRunServer, ServerInfo, - setAccessTokensToServers, - userLogin + setAccessTokensToServers } from '../../../../shared/extra-utils' import { makePostBodyRequest } from '../../../../shared/extra-utils/requests/requests' import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' @@ -27,7 +26,7 @@ describe('Test bulk API validators', function () { const user = { username: 'user1', password: 'password' } await createUser({ url: server.url, accessToken: server.accessToken, username: user.username, password: user.password }) - userAccessToken = await userLogin(server, user) + userAccessToken = await server.loginCommand.getAccessToken(user) }) describe('When removing comments of', function () { diff --git a/server/tests/api/check-params/config.ts b/server/tests/api/check-params/config.ts index 291de93ea..e93523e4b 100644 --- a/server/tests/api/check-params/config.ts +++ b/server/tests/api/check-params/config.ts @@ -11,8 +11,7 @@ import { makeGetRequest, makePutBodyRequest, ServerInfo, - setAccessTokensToServers, - userLogin + setAccessTokensToServers } from '@shared/extra-utils' import { CustomConfig } from '@shared/models' @@ -208,7 +207,7 @@ describe('Test config API validators', function () { password: 'password' } await createUser({ url: server.url, accessToken: server.accessToken, username: user.username, password: user.password }) - userAccessToken = await userLogin(server, user) + userAccessToken = await server.loginCommand.getAccessToken(user) }) describe('When getting the configuration', function () { diff --git a/server/tests/api/check-params/custom-pages.ts b/server/tests/api/check-params/custom-pages.ts index 74ca3384c..c1dd258aa 100644 --- a/server/tests/api/check-params/custom-pages.ts +++ b/server/tests/api/check-params/custom-pages.ts @@ -7,8 +7,7 @@ import { createUser, flushAndRunServer, ServerInfo, - setAccessTokensToServers, - userLogin + setAccessTokensToServers } from '../../../../shared/extra-utils' import { makeGetRequest, makePutBodyRequest } from '../../../../shared/extra-utils/requests/requests' @@ -29,7 +28,7 @@ describe('Test custom pages validators', function () { const user = { username: 'user1', password: 'password' } await createUser({ url: server.url, accessToken: server.accessToken, username: user.username, password: user.password }) - userAccessToken = await userLogin(server, user) + userAccessToken = await server.loginCommand.getAccessToken(user) }) describe('When updating instance homepage', function () { diff --git a/server/tests/api/check-params/debug.ts b/server/tests/api/check-params/debug.ts index 37bf0f99b..dc033a441 100644 --- a/server/tests/api/check-params/debug.ts +++ b/server/tests/api/check-params/debug.ts @@ -7,8 +7,7 @@ import { createUser, flushAndRunServer, ServerInfo, - setAccessTokensToServers, - userLogin + setAccessTokensToServers } from '../../../../shared/extra-utils' import { makeGetRequest } from '../../../../shared/extra-utils/requests/requests' import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' @@ -32,7 +31,7 @@ describe('Test debug API validators', function () { password: 'my super password' } await createUser({ url: server.url, accessToken: server.accessToken, username: user.username, password: user.password }) - userAccessToken = await userLogin(server, user) + userAccessToken = await server.loginCommand.getAccessToken(user) }) describe('When getting debug endpoint', function () { diff --git a/server/tests/api/check-params/follows.ts b/server/tests/api/check-params/follows.ts index c03dd5c9c..8cf5b130e 100644 --- a/server/tests/api/check-params/follows.ts +++ b/server/tests/api/check-params/follows.ts @@ -9,8 +9,7 @@ import { makeDeleteRequest, makeGetRequest, makePostBodyRequest, ServerInfo, - setAccessTokensToServers, - userLogin + setAccessTokensToServers } from '../../../../shared/extra-utils' import { checkBadCountPagination, @@ -42,7 +41,7 @@ describe('Test server follows API validators', function () { } await createUser({ url: server.url, accessToken: server.accessToken, username: user.username, password: user.password }) - userAccessToken = await userLogin(server, user) + userAccessToken = await server.loginCommand.getAccessToken(user) }) describe('When adding follows', function () { diff --git a/server/tests/api/check-params/jobs.ts b/server/tests/api/check-params/jobs.ts index 3c1d2049b..cbe6a28b8 100644 --- a/server/tests/api/check-params/jobs.ts +++ b/server/tests/api/check-params/jobs.ts @@ -7,8 +7,7 @@ import { createUser, flushAndRunServer, ServerInfo, - setAccessTokensToServers, - userLogin + setAccessTokensToServers } from '../../../../shared/extra-utils' import { checkBadCountPagination, @@ -37,7 +36,7 @@ describe('Test jobs API validators', function () { password: 'my super password' } await createUser({ url: server.url, accessToken: server.accessToken, username: user.username, password: user.password }) - userAccessToken = await userLogin(server, user) + userAccessToken = await server.loginCommand.getAccessToken(user) }) describe('When listing jobs', function () { diff --git a/server/tests/api/check-params/live.ts b/server/tests/api/check-params/live.ts index 394967285..045f3a1b1 100644 --- a/server/tests/api/check-params/live.ts +++ b/server/tests/api/check-params/live.ts @@ -17,8 +17,7 @@ import { ServerInfo, setAccessTokensToServers, stopFfmpeg, - uploadVideoAndGetId, - userLogin + uploadVideoAndGetId } from '../../../../shared/extra-utils' describe('Test video lives API validator', function () { @@ -53,7 +52,7 @@ describe('Test video lives API validator', function () { const username = 'user1' const password = 'my super password' await createUser({ url: server.url, accessToken: server.accessToken, username: username, password: password }) - userAccessToken = await userLogin(server, { username, password }) + userAccessToken = await server.loginCommand.getAccessToken({ username, password }) { const res = await getMyUserInformation(server.url, server.accessToken) @@ -150,7 +149,7 @@ describe('Test video lives API validator', function () { } await createUser({ url: server.url, accessToken: server.accessToken, username: user.username, password: user.password }) - const accessTokenUser = await userLogin(server, user) + const accessTokenUser = await server.loginCommand.getAccessToken(user) const res = await getMyUserInformation(server.url, accessTokenUser) const customChannelId = res.body.videoChannels[0].id diff --git a/server/tests/api/check-params/logs.ts b/server/tests/api/check-params/logs.ts index dac1e6b98..83ecfec93 100644 --- a/server/tests/api/check-params/logs.ts +++ b/server/tests/api/check-params/logs.ts @@ -7,8 +7,7 @@ import { createUser, flushAndRunServer, ServerInfo, - setAccessTokensToServers, - userLogin + setAccessTokensToServers } from '../../../../shared/extra-utils' import { makeGetRequest } from '../../../../shared/extra-utils/requests/requests' import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' @@ -32,7 +31,7 @@ describe('Test logs API validators', function () { password: 'my super password' } await createUser({ url: server.url, accessToken: server.accessToken, username: user.username, password: user.password }) - userAccessToken = await userLogin(server, user) + userAccessToken = await server.loginCommand.getAccessToken(user) }) describe('When getting logs', function () { diff --git a/server/tests/api/check-params/plugins.ts b/server/tests/api/check-params/plugins.ts index 8509b8ac5..130cf6869 100644 --- a/server/tests/api/check-params/plugins.ts +++ b/server/tests/api/check-params/plugins.ts @@ -13,8 +13,7 @@ import { makePostBodyRequest, makePutBodyRequest, ServerInfo, - setAccessTokensToServers, - userLogin + setAccessTokensToServers } from '@shared/extra-utils' import { PeerTubePlugin, PluginType } from '@shared/models' @@ -45,7 +44,7 @@ describe('Test server plugins API validators', function () { } await createUser({ url: server.url, accessToken: server.accessToken, username: user.username, password: user.password }) - userAccessToken = await userLogin(server, user) + userAccessToken = await server.loginCommand.getAccessToken(user) { const res = await server.pluginsCommand.install({ npmName: npmPlugin }) diff --git a/server/tests/api/check-params/redundancy.ts b/server/tests/api/check-params/redundancy.ts index dac6938de..2e10e378a 100644 --- a/server/tests/api/check-params/redundancy.ts +++ b/server/tests/api/check-params/redundancy.ts @@ -19,7 +19,6 @@ import { ServerInfo, setAccessTokensToServers, uploadVideoAndGetId, - userLogin, waitJobs } from '../../../../shared/extra-utils' @@ -45,7 +44,7 @@ describe('Test server redundancy API validators', function () { } await createUser({ url: servers[0].url, accessToken: servers[0].accessToken, username: user.username, password: user.password }) - userAccessToken = await userLogin(servers[0], user) + userAccessToken = await servers[0].loginCommand.getAccessToken(user) videoIdLocal = (await uploadVideoAndGetId({ server: servers[0], videoName: 'video' })).id diff --git a/server/tests/api/check-params/upload-quota.ts b/server/tests/api/check-params/upload-quota.ts index c444663b8..3dc6cf2b4 100644 --- a/server/tests/api/check-params/upload-quota.ts +++ b/server/tests/api/check-params/upload-quota.ts @@ -15,7 +15,6 @@ import { setDefaultVideoChannel, updateUser, uploadVideo, - userLogin, waitJobs } from '../../../../shared/extra-utils' @@ -50,7 +49,7 @@ describe('Test upload quota', function () { const user = { username: 'registered' + randomInt(1, 1500), password: 'password' } await registerUser(server.url, user.username, user.password) - const userAccessToken = await userLogin(server, user) + const userAccessToken = await server.loginCommand.getAccessToken(user) const videoAttributes = { fixture: 'video_short2.webm' } for (let i = 0; i < 5; i++) { @@ -65,7 +64,7 @@ describe('Test upload quota', function () { const user = { username: 'registered' + randomInt(1, 1500), password: 'password' } await registerUser(server.url, user.username, user.password) - const userAccessToken = await userLogin(server, user) + const userAccessToken = await server.loginCommand.getAccessToken(user) const videoAttributes = { fixture: 'video_short2.webm' } for (let i = 0; i < 5; i++) { diff --git a/server/tests/api/check-params/user-subscriptions.ts b/server/tests/api/check-params/user-subscriptions.ts index 538201647..64e2703b9 100644 --- a/server/tests/api/check-params/user-subscriptions.ts +++ b/server/tests/api/check-params/user-subscriptions.ts @@ -10,8 +10,7 @@ import { makeGetRequest, makePostBodyRequest, ServerInfo, - setAccessTokensToServers, - userLogin + setAccessTokensToServers } from '../../../../shared/extra-utils' import { @@ -41,7 +40,7 @@ describe('Test user subscriptions API validators', function () { password: 'my super password' } await createUser({ url: server.url, accessToken: server.accessToken, username: user.username, password: user.password }) - userAccessToken = await userLogin(server, user) + userAccessToken = await server.loginCommand.getAccessToken(user) }) describe('When listing my subscriptions', function () { diff --git a/server/tests/api/check-params/users.ts b/server/tests/api/check-params/users.ts index fda7e9640..54baeebe1 100644 --- a/server/tests/api/check-params/users.ts +++ b/server/tests/api/check-params/users.ts @@ -27,8 +27,7 @@ import { ServerInfo, setAccessTokensToServers, unblockUser, - uploadVideo, - userLogin + uploadVideo } from '../../../../shared/extra-utils' import { MockSmtpServer } from '../../../../shared/extra-utils/mock-servers/mock-email' import { @@ -87,7 +86,7 @@ describe('Test users API validators', function () { password: user.password, videoQuota: videoQuota }) - userAccessToken = await userLogin(server, user) + userAccessToken = await server.loginCommand.getAccessToken(user) } { @@ -104,7 +103,7 @@ describe('Test users API validators', function () { role: UserRole.MODERATOR }) - moderatorAccessToken = await userLogin(server, moderator) + moderatorAccessToken = await server.loginCommand.getAccessToken(moderator) } { @@ -394,7 +393,7 @@ describe('Test users API validators', function () { username: 'user1', password: 'my super password' } - userAccessToken = await userLogin(server, user) + userAccessToken = await server.loginCommand.getAccessToken(user) const fields = { username: 'user3', diff --git a/server/tests/api/check-params/video-blacklist.ts b/server/tests/api/check-params/video-blacklist.ts index 98cf2e11a..c33bc196d 100644 --- a/server/tests/api/check-params/video-blacklist.ts +++ b/server/tests/api/check-params/video-blacklist.ts @@ -19,7 +19,6 @@ import { ServerInfo, setAccessTokensToServers, uploadVideo, - userLogin, waitJobs } from '@shared/extra-utils' import { VideoBlacklistType, VideoDetails } from '@shared/models' @@ -46,14 +45,14 @@ describe('Test video blacklist API validators', function () { const username = 'user1' const password = 'my super password' await createUser({ url: servers[0].url, accessToken: servers[0].accessToken, username: username, password: password }) - userAccessToken1 = await userLogin(servers[0], { username, password }) + userAccessToken1 = await servers[0].loginCommand.getAccessToken({ username, password }) } { const username = 'user2' const password = 'my super password' await createUser({ url: servers[0].url, accessToken: servers[0].accessToken, username: username, password: password }) - userAccessToken2 = await userLogin(servers[0], { username, password }) + userAccessToken2 = await servers[0].loginCommand.getAccessToken({ username, password }) } { diff --git a/server/tests/api/check-params/video-captions.ts b/server/tests/api/check-params/video-captions.ts index baab0f276..f2fd61b91 100644 --- a/server/tests/api/check-params/video-captions.ts +++ b/server/tests/api/check-params/video-captions.ts @@ -12,8 +12,7 @@ import { makeUploadRequest, ServerInfo, setAccessTokensToServers, - uploadVideo, - userLogin + uploadVideo } from '@shared/extra-utils' import { VideoCreateResult } from '@shared/models' @@ -44,7 +43,7 @@ describe('Test video captions API validator', function () { password: 'my super password' } await createUser({ url: server.url, accessToken: server.accessToken, username: user.username, password: user.password }) - userAccessToken = await userLogin(server, user) + userAccessToken = await server.loginCommand.getAccessToken(user) } }) diff --git a/server/tests/api/check-params/video-channels.ts b/server/tests/api/check-params/video-channels.ts index 3b72d3796..5361f6917 100644 --- a/server/tests/api/check-params/video-channels.ts +++ b/server/tests/api/check-params/video-channels.ts @@ -18,8 +18,7 @@ import { makePutBodyRequest, makeUploadRequest, ServerInfo, - setAccessTokensToServers, - userLogin + setAccessTokensToServers } from '@shared/extra-utils' import { VideoChannelUpdate } from '@shared/models' @@ -47,7 +46,7 @@ describe('Test video channels API validator', function () { { await createUser({ url: server.url, accessToken: server.accessToken, username: user.username, password: user.password }) - accessTokenUser = await userLogin(server, user) + accessTokenUser = await server.loginCommand.getAccessToken(user) } command = server.channelsCommand diff --git a/server/tests/api/check-params/video-comments.ts b/server/tests/api/check-params/video-comments.ts index 0f8c81392..c21aebaae 100644 --- a/server/tests/api/check-params/video-comments.ts +++ b/server/tests/api/check-params/video-comments.ts @@ -15,8 +15,7 @@ import { makePostBodyRequest, ServerInfo, setAccessTokensToServers, - uploadVideo, - userLogin + uploadVideo } from '@shared/extra-utils' import { VideoCreateResult } from '@shared/models' @@ -55,13 +54,13 @@ describe('Test video comments API validator', function () { { const user = { username: 'user1', password: 'my super password' } await createUser({ url: server.url, accessToken: server.accessToken, username: user.username, password: user.password }) - userAccessToken = await userLogin(server, user) + userAccessToken = await server.loginCommand.getAccessToken(user) } { const user = { username: 'user2', password: 'my super password' } await createUser({ url: server.url, accessToken: server.accessToken, username: user.username, password: user.password }) - userAccessToken2 = await userLogin(server, user) + userAccessToken2 = await server.loginCommand.getAccessToken(user) } }) diff --git a/server/tests/api/check-params/video-imports.ts b/server/tests/api/check-params/video-imports.ts index 2cc124cc1..51260affa 100644 --- a/server/tests/api/check-params/video-imports.ts +++ b/server/tests/api/check-params/video-imports.ts @@ -17,8 +17,7 @@ import { makePostBodyRequest, makeUploadRequest, ServerInfo, - setAccessTokensToServers, - userLogin + setAccessTokensToServers } from '@shared/extra-utils' import { VideoPrivacy } from '@shared/models' @@ -40,7 +39,7 @@ describe('Test video imports API validator', function () { const username = 'user1' const password = 'my super password' await createUser({ url: server.url, accessToken: server.accessToken, username: username, password: password }) - userAccessToken = await userLogin(server, { username, password }) + userAccessToken = await server.loginCommand.getAccessToken({ username, password }) { const res = await getMyUserInformation(server.url, server.accessToken) @@ -167,7 +166,7 @@ describe('Test video imports API validator', function () { } await createUser({ url: server.url, accessToken: server.accessToken, username: user.username, password: user.password }) - const accessTokenUser = await userLogin(server, user) + const accessTokenUser = await server.loginCommand.getAccessToken(user) const res = await getMyUserInformation(server.url, accessTokenUser) const customChannelId = res.body.videoChannels[0].id diff --git a/server/tests/api/check-params/videos-filter.ts b/server/tests/api/check-params/videos-filter.ts index 4d54a4fd0..095b94656 100644 --- a/server/tests/api/check-params/videos-filter.ts +++ b/server/tests/api/check-params/videos-filter.ts @@ -8,8 +8,7 @@ import { makeGetRequest, ServerInfo, setAccessTokensToServers, - setDefaultVideoChannel, - userLogin + setDefaultVideoChannel } from '../../../../shared/extra-utils' import { UserRole } from '../../../../shared/models/users' import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' @@ -52,7 +51,7 @@ describe('Test video filters validators', function () { const user = { username: 'user1', password: 'my super password' } await createUser({ url: server.url, accessToken: server.accessToken, username: user.username, password: user.password }) - userAccessToken = await userLogin(server, user) + userAccessToken = await server.loginCommand.getAccessToken(user) const moderator = { username: 'moderator', password: 'my super password' } await createUser( @@ -66,7 +65,7 @@ describe('Test video filters validators', function () { role: UserRole.MODERATOR } ) - moderatorAccessToken = await userLogin(server, moderator) + moderatorAccessToken = await server.loginCommand.getAccessToken(moderator) }) describe('When setting a video filter', function () { diff --git a/server/tests/api/check-params/videos.ts b/server/tests/api/check-params/videos.ts index 6549063b1..8e11232bd 100644 --- a/server/tests/api/check-params/videos.ts +++ b/server/tests/api/check-params/videos.ts @@ -22,8 +22,7 @@ import { removeVideo, root, ServerInfo, - setAccessTokensToServers, - userLogin + setAccessTokensToServers } from '../../../../shared/extra-utils' import { checkBadCountPagination, @@ -55,7 +54,7 @@ describe('Test videos API validator', function () { const username = 'user1' const password = 'my super password' await createUser({ url: server.url, accessToken: server.accessToken, username: username, password: password }) - userAccessToken = await userLogin(server, { username, password }) + userAccessToken = await server.loginCommand.getAccessToken({ username, password }) { const res = await getMyUserInformation(server.url, server.accessToken) @@ -286,7 +285,7 @@ describe('Test videos API validator', function () { } await createUser({ url: server.url, accessToken: server.accessToken, username: user.username, password: user.password }) - const accessTokenUser = await userLogin(server, user) + const accessTokenUser = await server.loginCommand.getAccessToken(user) const res = await getMyUserInformation(server.url, accessTokenUser) const customChannelId = res.body.videoChannels[0].id diff --git a/server/tests/api/moderation/abuses.ts b/server/tests/api/moderation/abuses.ts index e428cf1a8..d7462f38f 100644 --- a/server/tests/api/moderation/abuses.ts +++ b/server/tests/api/moderation/abuses.ts @@ -17,7 +17,6 @@ import { setAccessTokensToServers, uploadVideo, uploadVideoAndGetId, - userLogin, waitJobs } from '@shared/extra-utils' import { AbuseMessage, AbusePredefinedReasonsString, AbuseState, AdminAbuse, UserAbuse } from '@shared/models' @@ -280,7 +279,7 @@ describe('Test abuses', function () { // register a second user to have two reporters/reportees const user = { username: 'user2', password: 'password' } await createUser({ url: servers[0].url, accessToken: servers[0].accessToken, ...user }) - const userAccessToken = await userLogin(servers[0], user) + const userAccessToken = await servers[0].loginCommand.getAccessToken(user) // upload a third video via this user const video3Attributes = { diff --git a/server/tests/api/moderation/blocklist-notification.ts b/server/tests/api/moderation/blocklist-notification.ts index b676a4db4..4f2be6198 100644 --- a/server/tests/api/moderation/blocklist-notification.ts +++ b/server/tests/api/moderation/blocklist-notification.ts @@ -10,7 +10,6 @@ import { ServerInfo, setAccessTokensToServers, uploadVideo, - userLogin, waitJobs } from '@shared/extra-utils' import { UserNotificationType } from '@shared/models' @@ -86,7 +85,7 @@ describe('Test blocklist', function () { videoQuotaDaily: -1 }) - userToken1 = await userLogin(servers[0], user) + userToken1 = await servers[0].loginCommand.getAccessToken(user) await uploadVideo(servers[0].url, userToken1, { name: 'video user 1' }) } @@ -94,14 +93,14 @@ describe('Test blocklist', function () { const user = { username: 'user2', password: 'password' } await createUser({ url: servers[0].url, accessToken: servers[0].accessToken, username: user.username, password: user.password }) - userToken2 = await userLogin(servers[0], user) + userToken2 = await servers[0].loginCommand.getAccessToken(user) } { const user = { username: 'user3', password: 'password' } await createUser({ url: servers[1].url, accessToken: servers[1].accessToken, username: user.username, password: user.password }) - remoteUserToken = await userLogin(servers[1], user) + remoteUserToken = await servers[1].loginCommand.getAccessToken(user) } await doubleFollow(servers[0], servers[1]) diff --git a/server/tests/api/moderation/blocklist.ts b/server/tests/api/moderation/blocklist.ts index 44e3de4e4..c38a7dad4 100644 --- a/server/tests/api/moderation/blocklist.ts +++ b/server/tests/api/moderation/blocklist.ts @@ -14,7 +14,6 @@ import { ServerInfo, setAccessTokensToServers, uploadVideo, - userLogin, waitJobs } from '@shared/extra-utils' import { UserNotificationType, Video } from '@shared/models' @@ -94,7 +93,7 @@ describe('Test blocklist', function () { const user = { username: 'user1', password: 'password' } await createUser({ url: servers[0].url, accessToken: servers[0].accessToken, username: user.username, password: user.password }) - userToken1 = await userLogin(servers[0], user) + userToken1 = await servers[0].loginCommand.getAccessToken(user) await uploadVideo(servers[0].url, userToken1, { name: 'video user 1' }) } @@ -102,14 +101,14 @@ describe('Test blocklist', function () { const user = { username: 'moderator', password: 'password' } await createUser({ url: servers[0].url, accessToken: servers[0].accessToken, username: user.username, password: user.password }) - userModeratorToken = await userLogin(servers[0], user) + userModeratorToken = await servers[0].loginCommand.getAccessToken(user) } { const user = { username: 'user2', password: 'password' } await createUser({ url: servers[1].url, accessToken: servers[1].accessToken, username: user.username, password: user.password }) - userToken2 = await userLogin(servers[1], user) + userToken2 = await servers[1].loginCommand.getAccessToken(user) await uploadVideo(servers[1].url, userToken2, { name: 'video user 2' }) } diff --git a/server/tests/api/moderation/video-blacklist.ts b/server/tests/api/moderation/video-blacklist.ts index 8b4723a2b..b61effc57 100644 --- a/server/tests/api/moderation/video-blacklist.ts +++ b/server/tests/api/moderation/video-blacklist.ts @@ -19,7 +19,6 @@ import { setAccessTokensToServers, updateVideo, uploadVideo, - userLogin, waitJobs } from '@shared/extra-utils' import { User, UserAdminFlag, UserRole, VideoBlacklist, VideoBlacklistType } from '@shared/models' @@ -366,7 +365,7 @@ describe('Test video blacklist', function () { role: UserRole.USER }) - userWithoutFlag = await userLogin(servers[0], user) + userWithoutFlag = await servers[0].loginCommand.getAccessToken(user) const res = await getMyUserInformation(servers[0].url, userWithoutFlag) const body: User = res.body @@ -384,7 +383,7 @@ describe('Test video blacklist', function () { role: UserRole.USER }) - userWithFlag = await userLogin(servers[0], user) + userWithFlag = await servers[0].loginCommand.getAccessToken(user) } await waitJobs(servers) diff --git a/server/tests/api/search/search-activitypub-video-channels.ts b/server/tests/api/search/search-activitypub-video-channels.ts index 83be9cd1e..3cba2b019 100644 --- a/server/tests/api/search/search-activitypub-video-channels.ts +++ b/server/tests/api/search/search-activitypub-video-channels.ts @@ -13,7 +13,6 @@ import { updateMyUser, updateVideo, uploadVideo, - userLogin, wait, waitJobs } from '@shared/extra-utils' @@ -47,7 +46,7 @@ describe('Test ActivityPub video channels search', function () { { const user = { username: 'user1_server2', password: 'password' } await createUser({ url: servers[1].url, accessToken: servers[1].accessToken, username: user.username, password: user.password }) - userServer2Token = await userLogin(servers[1], user) + userServer2Token = await servers[1].loginCommand.getAccessToken(user) const channel = { name: 'channel1_server2', diff --git a/server/tests/api/server/bulk.ts b/server/tests/api/server/bulk.ts index 5c8673e00..a09c21228 100644 --- a/server/tests/api/server/bulk.ts +++ b/server/tests/api/server/bulk.ts @@ -2,7 +2,6 @@ import 'mocha' import * as chai from 'chai' -import { Video } from '@shared/models' import { BulkCommand, cleanupTests, @@ -13,9 +12,9 @@ import { ServerInfo, setAccessTokensToServers, uploadVideo, - userLogin, waitJobs -} from '../../../../shared/extra-utils/index' +} from '@shared/extra-utils' +import { Video } from '@shared/models' const expect = chai.expect @@ -41,21 +40,21 @@ describe('Test bulk actions', function () { const user = { username: 'user1', password: 'password' } await createUser({ url: servers[0].url, accessToken: servers[0].accessToken, username: user.username, password: user.password }) - user1Token = await userLogin(servers[0], user) + user1Token = await servers[0].loginCommand.getAccessToken(user) } { const user = { username: 'user2', password: 'password' } await createUser({ url: servers[0].url, accessToken: servers[0].accessToken, username: user.username, password: user.password }) - user2Token = await userLogin(servers[0], user) + user2Token = await servers[0].loginCommand.getAccessToken(user) } { const user = { username: 'user3', password: 'password' } await createUser({ url: servers[1].url, accessToken: servers[1].accessToken, username: user.username, password: user.password }) - user3Token = await userLogin(servers[1], user) + user3Token = await servers[1].loginCommand.getAccessToken(user) } await doubleFollow(servers[0], servers[1]) diff --git a/server/tests/api/server/email.ts b/server/tests/api/server/email.ts index 5d997713b..c64c120e3 100644 --- a/server/tests/api/server/email.ts +++ b/server/tests/api/server/email.ts @@ -15,7 +15,6 @@ import { setAccessTokensToServers, unblockUser, uploadVideo, - userLogin, verifyEmail } from '../../../../shared/extra-utils' import { MockSmtpServer } from '../../../../shared/extra-utils/mock-servers/mock-email' @@ -62,7 +61,7 @@ describe('Test emails', function () { const res = await createUser({ url: server.url, accessToken: server.accessToken, username: user.username, password: user.password }) userId = res.body.user.id - userAccessToken = await userLogin(server, user) + userAccessToken = await server.loginCommand.getAccessToken(user) } { @@ -128,7 +127,7 @@ describe('Test emails', function () { it('Should login with this new password', async function () { user.password = 'super_password2' - await userLogin(server, user) + await server.loginCommand.getAccessToken(user) }) }) @@ -175,7 +174,7 @@ describe('Test emails', function () { }) it('Should login with this new password', async function () { - await userLogin(server, { + await server.loginCommand.getAccessToken({ username: 'create_password', password: 'newly_created_password' }) diff --git a/server/tests/api/server/follow-constraints.ts b/server/tests/api/server/follow-constraints.ts index 0f1c6264d..74cdf353b 100644 --- a/server/tests/api/server/follow-constraints.ts +++ b/server/tests/api/server/follow-constraints.ts @@ -15,8 +15,7 @@ import { getVideoWithToken, ServerInfo, setAccessTokensToServers, - uploadVideo, - userLogin + uploadVideo } from '../../../../shared/extra-utils' const expect = chai.expect @@ -49,7 +48,7 @@ describe('Test follow constraints', function () { password: 'super_password' } await createUser({ url: servers[0].url, accessToken: servers[0].accessToken, username: user.username, password: user.password }) - userAccessToken = await userLogin(servers[0], user) + userAccessToken = await servers[0].loginCommand.getAccessToken(user) await doubleFollow(servers[0], servers[1]) }) diff --git a/server/tests/api/server/follows.ts b/server/tests/api/server/follows.ts index 4a9ed2d05..c2a0620a5 100644 --- a/server/tests/api/server/follows.ts +++ b/server/tests/api/server/follows.ts @@ -16,7 +16,6 @@ import { setAccessTokensToServers, testCaptionFile, uploadVideo, - userLogin, waitJobs } from '@shared/extra-utils' import { Video, VideoPrivacy } from '@shared/models' @@ -330,7 +329,7 @@ describe('Test follows', function () { { const user = { username: 'captain', password: 'password' } await createUser({ url: servers[2].url, accessToken: servers[2].accessToken, username: user.username, password: user.password }) - const userAccessToken = await userLogin(servers[2], user) + const userAccessToken = await servers[2].loginCommand.getAccessToken(user) const resVideos = await getVideosList(servers[2].url) video4 = resVideos.body.data.find(v => v.name === 'server3-4') diff --git a/server/tests/api/server/reverse-proxy.ts b/server/tests/api/server/reverse-proxy.ts index 17d1ee4a5..d9c669571 100644 --- a/server/tests/api/server/reverse-proxy.ts +++ b/server/tests/api/server/reverse-proxy.ts @@ -1,12 +1,17 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ -import 'mocha' -import * as chai from 'chai' -import { cleanupTests, getVideo, registerUser, uploadVideo, userLogin, viewVideo, wait } from '../../../../shared/extra-utils' -import { flushAndRunServer, setAccessTokensToServers } from '../../../../shared/extra-utils/index' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' - -const expect = chai.expect +import { expect } from 'chai' +import { HttpStatusCode } from '@shared/core-utils' +import { + cleanupTests, + flushAndRunServer, + getVideo, + registerUser, + setAccessTokensToServers, + uploadVideo, + viewVideo, + wait +} from '@shared/extra-utils' describe('Test application behind a reverse proxy', function () { let server = null @@ -97,10 +102,10 @@ describe('Test application behind a reverse proxy', function () { const user = { username: 'root', password: 'fail' } for (let i = 0; i < 19; i++) { - await userLogin(server, user, HttpStatusCode.BAD_REQUEST_400) + await server.loginCommand.getAccessToken(user, HttpStatusCode.BAD_REQUEST_400) } - await userLogin(server, user, HttpStatusCode.TOO_MANY_REQUESTS_429) + await server.loginCommand.getAccessToken(user, HttpStatusCode.TOO_MANY_REQUESTS_429) }) it('Should rate limit signup', async function () { diff --git a/server/tests/api/server/stats.ts b/server/tests/api/server/stats.ts index ded305899..aa26f978d 100644 --- a/server/tests/api/server/stats.ts +++ b/server/tests/api/server/stats.ts @@ -10,7 +10,6 @@ import { ServerInfo, setAccessTokensToServers, uploadVideo, - userLogin, viewVideo, wait, waitJobs @@ -119,7 +118,7 @@ describe('Test stats (excluding redundancy)', function () { } { - await userLogin(server, user) + await server.loginCommand.getAccessToken(user) const data = await server.statsCommand.get() diff --git a/server/tests/api/users/user-subscriptions.ts b/server/tests/api/users/user-subscriptions.ts index c119622ad..1d0fc35f1 100644 --- a/server/tests/api/users/user-subscriptions.ts +++ b/server/tests/api/users/user-subscriptions.ts @@ -13,7 +13,6 @@ import { SubscriptionsCommand, updateVideo, uploadVideo, - userLogin, waitJobs } from '@shared/extra-utils' @@ -42,7 +41,7 @@ describe('Test users subscriptions', function () { const user = { username: 'user' + server.serverNumber, password: 'password' } await createUser({ url: server.url, accessToken: server.accessToken, username: user.username, password: user.password }) - const accessToken = await userLogin(server, user) + const accessToken = await server.loginCommand.getAccessToken(user) users.push({ accessToken }) const videoName1 = 'video 1-' + server.serverNumber diff --git a/server/tests/api/users/users-multiple-servers.ts b/server/tests/api/users/users-multiple-servers.ts index 7b650cb8f..99fa08fe2 100644 --- a/server/tests/api/users/users-multiple-servers.ts +++ b/server/tests/api/users/users-multiple-servers.ts @@ -19,7 +19,6 @@ import { updateMyAvatar, updateMyUser, uploadVideo, - userLogin, waitJobs } from '@shared/extra-utils' import { User } from '@shared/models' @@ -64,7 +63,7 @@ describe('Test users with multiple servers', function () { password: user.password }) userId = res.body.user.id - userAccessToken = await userLogin(servers[0], user) + userAccessToken = await servers[0].loginCommand.getAccessToken(user) } { diff --git a/server/tests/api/users/users-verification.ts b/server/tests/api/users/users-verification.ts index 23f81d804..ade730323 100644 --- a/server/tests/api/users/users-verification.ts +++ b/server/tests/api/users/users-verification.ts @@ -2,23 +2,21 @@ import 'mocha' import * as chai from 'chai' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '@shared/core-utils' import { cleanupTests, flushAndRunServer, getMyUserInformation, getUserInformation, - login, + MockSmtpServer, registerUser, ServerInfo, + setAccessTokensToServers, updateMyUser, - userLogin, - verifyEmail -} from '../../../../shared/extra-utils' -import { MockSmtpServer } from '../../../../shared/extra-utils/mock-servers/mock-email' -import { waitJobs } from '../../../../shared/extra-utils/server/jobs' -import { setAccessTokensToServers } from '../../../../shared/extra-utils/users/login' -import { User } from '../../../../shared/models/users' + verifyEmail, + waitJobs +} from '@shared/extra-utils' +import { User } from '@shared/models' const expect = chai.expect @@ -91,15 +89,15 @@ describe('Test users account verification', function () { }) it('Should not allow login for user with unverified email', async function () { - const resLogin = await login(server.url, server.client, user1, HttpStatusCode.BAD_REQUEST_400) - expect(resLogin.body.detail).to.contain('User email is not verified.') + const { detail } = await server.loginCommand.login({ user: user1, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) + expect(detail).to.contain('User email is not verified.') }) it('Should verify the user via email and allow login', async function () { await verifyEmail(server.url, userId, verificationString) - const res = await login(server.url, server.client, user1) - userAccessToken = res.body.access_token + const body = await server.loginCommand.login({ user: user1 }) + userAccessToken = body.access_token const resUserVerified = await getUserInformation(server.url, server.accessToken, userId) expect(resUserVerified.body.emailVerified).to.be.true @@ -164,7 +162,7 @@ describe('Test users account verification', function () { await waitJobs(server) expect(emails).to.have.lengthOf(expectedEmailsLength) - const accessToken = await userLogin(server, user2) + const accessToken = await server.loginCommand.getAccessToken(user2) const resMyUserInfo = await getMyUserInformation(server.url, accessToken) expect(resMyUserInfo.body.emailVerified).to.be.null @@ -181,7 +179,7 @@ describe('Test users account verification', function () { } }) - await userLogin(server, user2) + await server.loginCommand.getAccessToken(user2) }) after(async function () { diff --git a/server/tests/api/users/users.ts b/server/tests/api/users/users.ts index 69a8dba34..608bedb8b 100644 --- a/server/tests/api/users/users.ts +++ b/server/tests/api/users/users.ts @@ -18,11 +18,8 @@ import { getUsersListPaginationAndSort, getVideosList, killallServers, - login, - logout, makePutBodyRequest, rateVideo, - refreshToken, registerUserWithChannel, removeUser, removeVideo, @@ -35,7 +32,6 @@ import { updateMyUser, updateUser, uploadVideo, - userLogin, waitJobs } from '@shared/extra-utils' import { AbuseState, MyUser, OAuth2ErrorCode, User, UserAdminFlag, UserRole, Video, VideoPlaylistType } from '@shared/models' @@ -78,22 +74,22 @@ describe('Test users', function () { it('Should not login with an invalid client id', async function () { const client = { id: 'client', secret: server.client.secret } - const res = await login(server.url, client, server.user, HttpStatusCode.BAD_REQUEST_400) + const body = await server.loginCommand.login({ client, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) - expect(res.body.code).to.equal(OAuth2ErrorCode.INVALID_CLIENT) - expect(res.body.error).to.contain('client is invalid') - expect(res.body.type.startsWith('https://')).to.be.true - expect(res.body.type).to.contain(OAuth2ErrorCode.INVALID_CLIENT) + expect(body.code).to.equal(OAuth2ErrorCode.INVALID_CLIENT) + expect(body.error).to.contain('client is invalid') + expect(body.type.startsWith('https://')).to.be.true + expect(body.type).to.contain(OAuth2ErrorCode.INVALID_CLIENT) }) it('Should not login with an invalid client secret', async function () { const client = { id: server.client.id, secret: 'coucou' } - const res = await login(server.url, client, server.user, HttpStatusCode.BAD_REQUEST_400) + const body = await server.loginCommand.login({ client, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) - expect(res.body.code).to.equal(OAuth2ErrorCode.INVALID_CLIENT) - expect(res.body.error).to.contain('client is invalid') - expect(res.body.type.startsWith('https://')).to.be.true - expect(res.body.type).to.contain(OAuth2ErrorCode.INVALID_CLIENT) + expect(body.code).to.equal(OAuth2ErrorCode.INVALID_CLIENT) + expect(body.error).to.contain('client is invalid') + expect(body.type.startsWith('https://')).to.be.true + expect(body.type).to.contain(OAuth2ErrorCode.INVALID_CLIENT) }) }) @@ -101,22 +97,22 @@ describe('Test users', function () { it('Should not login with an invalid username', async function () { const user = { username: 'captain crochet', password: server.user.password } - const res = await login(server.url, server.client, user, HttpStatusCode.BAD_REQUEST_400) + const body = await server.loginCommand.login({ user, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) - expect(res.body.code).to.equal(OAuth2ErrorCode.INVALID_GRANT) - expect(res.body.error).to.contain('credentials are invalid') - expect(res.body.type.startsWith('https://')).to.be.true - expect(res.body.type).to.contain(OAuth2ErrorCode.INVALID_GRANT) + expect(body.code).to.equal(OAuth2ErrorCode.INVALID_GRANT) + expect(body.error).to.contain('credentials are invalid') + expect(body.type.startsWith('https://')).to.be.true + expect(body.type).to.contain(OAuth2ErrorCode.INVALID_GRANT) }) it('Should not login with an invalid password', async function () { const user = { username: server.user.username, password: 'mew_three' } - const res = await login(server.url, server.client, user, HttpStatusCode.BAD_REQUEST_400) + const body = await server.loginCommand.login({ user, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) - expect(res.body.code).to.equal(OAuth2ErrorCode.INVALID_GRANT) - expect(res.body.error).to.contain('credentials are invalid') - expect(res.body.type.startsWith('https://')).to.be.true - expect(res.body.type).to.contain(OAuth2ErrorCode.INVALID_GRANT) + expect(body.code).to.equal(OAuth2ErrorCode.INVALID_GRANT) + expect(body.error).to.contain('credentials are invalid') + expect(body.type.startsWith('https://')).to.be.true + expect(body.type).to.contain(OAuth2ErrorCode.INVALID_GRANT) }) it('Should not be able to upload a video', async function () { @@ -139,20 +135,20 @@ describe('Test users', function () { it('Should not be able to unfollow') it('Should be able to login', async function () { - const res = await login(server.url, server.client, server.user, HttpStatusCode.OK_200) + const body = await server.loginCommand.login({ expectedStatus: HttpStatusCode.OK_200 }) - accessToken = res.body.access_token + accessToken = body.access_token }) it('Should be able to login with an insensitive username', async function () { const user = { username: 'RoOt', password: server.user.password } - await login(server.url, server.client, user, HttpStatusCode.OK_200) + await server.loginCommand.login({ user, expectedStatus: HttpStatusCode.OK_200 }) const user2 = { username: 'rOoT', password: server.user.password } - await login(server.url, server.client, user2, HttpStatusCode.OK_200) + await server.loginCommand.login({ user: user2, expectedStatus: HttpStatusCode.OK_200 }) const user3 = { username: 'ROOt', password: server.user.password } - await login(server.url, server.client, user3, HttpStatusCode.OK_200) + await server.loginCommand.login({ user: user3, expectedStatus: HttpStatusCode.OK_200 }) }) }) @@ -222,7 +218,7 @@ describe('Test users', function () { describe('Logout', function () { it('Should logout (revoke token)', async function () { - await logout(server.url, server.accessToken) + await server.loginCommand.logout({ token: server.accessToken }) }) it('Should not be able to get the user information', async function () { @@ -250,9 +246,9 @@ describe('Test users', function () { }) it('Should be able to login again', async function () { - const res = await login(server.url, server.client, server.user) - server.accessToken = res.body.access_token - server.refreshToken = res.body.refresh_token + const body = await server.loginCommand.login() + server.accessToken = body.access_token + server.refreshToken = body.refresh_token }) it('Should be able to get my user information again', async function () { @@ -268,11 +264,11 @@ describe('Test users', function () { await killallServers([ server ]) await reRunServer(server) - await getMyUserInformation(server.url, server.accessToken, 401) + await getMyUserInformation(server.url, server.accessToken, HttpStatusCode.UNAUTHORIZED_401) }) it('Should not be able to refresh an access token with an expired refresh token', async function () { - await refreshToken(server, server.refreshToken, 400) + await server.loginCommand.refreshToken({ refreshToken: server.refreshToken, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) it('Should refresh the token', async function () { @@ -284,7 +280,7 @@ describe('Test users', function () { await killallServers([ server ]) await reRunServer(server) - const res = await refreshToken(server, server.refreshToken) + const res = await server.loginCommand.refreshToken({ refreshToken: server.refreshToken }) server.accessToken = res.body.access_token server.refreshToken = res.body.refresh_token }) @@ -308,7 +304,7 @@ describe('Test users', function () { }) it('Should be able to login with this user', async function () { - accessTokenUser = await userLogin(server, user) + accessTokenUser = await server.loginCommand.getAccessToken(user) }) it('Should be able to get user information', async function () { @@ -562,6 +558,7 @@ describe('Test users', function () { }) describe('Update my account', function () { + it('Should update my password', async function () { await updateMyUser({ url: server.url, @@ -571,7 +568,7 @@ describe('Test users', function () { }) user.password = 'new password' - await userLogin(server, user, HttpStatusCode.OK_200) + await server.loginCommand.login({ user }) }) it('Should be able to change the NSFW display attribute', async function () { @@ -781,7 +778,7 @@ describe('Test users', function () { it('Should have removed the user token', async function () { await getMyUserVideoQuotaUsed(server.url, accessTokenUser, HttpStatusCode.UNAUTHORIZED_401) - accessTokenUser = await userLogin(server, user) + accessTokenUser = await server.loginCommand.getAccessToken(user) }) it('Should be able to update another user password', async function () { @@ -794,10 +791,10 @@ describe('Test users', function () { await getMyUserVideoQuotaUsed(server.url, accessTokenUser, HttpStatusCode.UNAUTHORIZED_401) - await userLogin(server, user, HttpStatusCode.BAD_REQUEST_400) + await server.loginCommand.login({ user, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) user.password = 'password updated' - accessTokenUser = await userLogin(server, user) + accessTokenUser = await server.loginCommand.getAccessToken(user) }) }) @@ -813,7 +810,7 @@ describe('Test users', function () { }) it('Should not be able to login with this user', async function () { - await userLogin(server, user, HttpStatusCode.BAD_REQUEST_400) + await server.loginCommand.login({ user, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) it('Should not have videos of this user', async function () { @@ -842,7 +839,7 @@ describe('Test users', function () { password: 'my super password' } - user15AccessToken = await userLogin(server, user15) + user15AccessToken = await server.loginCommand.getAccessToken(user15) }) it('Should have the correct display name', async function () { @@ -897,13 +894,13 @@ describe('Test users', function () { }) user16Id = resUser.body.user.id - user16AccessToken = await userLogin(server, user16) + user16AccessToken = await server.loginCommand.getAccessToken(user16) await getMyUserInformation(server.url, user16AccessToken, HttpStatusCode.OK_200) await blockUser(server.url, user16Id, server.accessToken) await getMyUserInformation(server.url, user16AccessToken, HttpStatusCode.UNAUTHORIZED_401) - await userLogin(server, user16, HttpStatusCode.BAD_REQUEST_400) + await server.loginCommand.login({ user: user16, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) it('Should search user by banned status', async function () { @@ -930,7 +927,7 @@ describe('Test users', function () { it('Should unblock a user', async function () { await unblockUser(server.url, user16Id, server.accessToken) - user16AccessToken = await userLogin(server, user16) + user16AccessToken = await server.loginCommand.getAccessToken(user16) await getMyUserInformation(server.url, user16AccessToken, HttpStatusCode.OK_200) }) }) @@ -952,7 +949,7 @@ describe('Test users', function () { }) user17Id = resUser.body.user.id - user17AccessToken = await userLogin(server, user17) + user17AccessToken = await server.loginCommand.getAccessToken(user17) const res = await getUserInformation(server.url, server.accessToken, user17Id, true) const user: User = res.body diff --git a/server/tests/api/videos/multiple-servers.ts b/server/tests/api/videos/multiple-servers.ts index 1905aac83..740314bfd 100644 --- a/server/tests/api/videos/multiple-servers.ts +++ b/server/tests/api/videos/multiple-servers.ts @@ -24,7 +24,6 @@ import { testImage, updateVideo, uploadVideo, - userLogin, viewVideo, wait, waitJobs, @@ -155,7 +154,7 @@ describe('Test multiple servers', function () { password: 'super_password' } await createUser({ url: servers[1].url, accessToken: servers[1].accessToken, username: user.username, password: user.password }) - const userAccessToken = await userLogin(servers[1], user) + const userAccessToken = await servers[1].loginCommand.getAccessToken(user) const videoAttributes = { name: 'my super name for server 2', diff --git a/server/tests/api/videos/video-change-ownership.ts b/server/tests/api/videos/video-change-ownership.ts index 1b81fe047..17c738e6f 100644 --- a/server/tests/api/videos/video-change-ownership.ts +++ b/server/tests/api/videos/video-change-ownership.ts @@ -16,8 +16,7 @@ import { ServerInfo, setAccessTokensToServers, setDefaultVideoChannel, - uploadVideo, - userLogin + uploadVideo } from '../../../../shared/extra-utils' import { waitJobs } from '../../../../shared/extra-utils/server/jobs' import { User } from '../../../../shared/models/users' @@ -82,8 +81,8 @@ describe('Test video change ownership - nominal', function () { videoQuota: videoQuota }) - firstUserToken = await userLogin(servers[0], firstUser) - secondUserToken = await userLogin(servers[0], secondUser) + firstUserToken = await servers[0].loginCommand.getAccessToken(firstUser) + secondUserToken = await servers[0].loginCommand.getAccessToken(secondUser) { const res = await getMyUserInformation(servers[0].url, firstUserToken) @@ -323,8 +322,8 @@ describe('Test video change ownership - quota too small', function () { videoQuota: limitedVideoQuota }) - firstUserToken = await userLogin(server, firstUser) - secondUserToken = await userLogin(server, secondUser) + firstUserToken = await server.loginCommand.getAccessToken(firstUser) + secondUserToken = await server.loginCommand.getAccessToken(secondUser) // Upload some videos on the server const video1Attributes = { diff --git a/server/tests/api/videos/video-channels.ts b/server/tests/api/videos/video-channels.ts index e441ebbd4..83645640c 100644 --- a/server/tests/api/videos/video-channels.ts +++ b/server/tests/api/videos/video-channels.ts @@ -16,7 +16,6 @@ import { testImage, updateVideo, uploadVideo, - userLogin, wait } from '../../../../shared/extra-utils' import { getMyUserInformation, ServerInfo, setAccessTokensToServers, viewVideo } from '../../../../shared/extra-utils/index' @@ -391,7 +390,7 @@ describe('Test video channels', function () { { await createUser({ url: servers[0].url, accessToken: servers[0].accessToken, username: 'toto', password: 'password' }) - const accessToken = await userLogin(servers[0], { username: 'toto', password: 'password' }) + const accessToken = await servers[0].loginCommand.getAccessToken({ username: 'toto', password: 'password' }) const res = await getMyUserInformation(servers[0].url, accessToken) const videoChannel = res.body.videoChannels[0] diff --git a/server/tests/api/videos/video-comments.ts b/server/tests/api/videos/video-comments.ts index 548d9fbf5..f9bd23646 100644 --- a/server/tests/api/videos/video-comments.ts +++ b/server/tests/api/videos/video-comments.ts @@ -8,7 +8,6 @@ import { createUser, dateIsValid, flushAndRunServer, - getAccessToken, ServerInfo, setAccessTokensToServers, testImage, @@ -52,7 +51,7 @@ describe('Test video comments', function () { username: 'user1', password: 'password' }) - userAccessTokenServer1 = await getAccessToken(server.url, 'user1', 'password') + userAccessTokenServer1 = await server.loginCommand.getAccessToken('user1', 'password') command = server.commentsCommand }) diff --git a/server/tests/api/videos/video-nsfw.ts b/server/tests/api/videos/video-nsfw.ts index c9c3792eb..a30b11ace 100644 --- a/server/tests/api/videos/video-nsfw.ts +++ b/server/tests/api/videos/video-nsfw.ts @@ -15,8 +15,7 @@ import { ServerInfo, setAccessTokensToServers, updateMyUser, - uploadVideo, - userLogin + uploadVideo } from '@shared/extra-utils' import { BooleanBothQuery, CustomConfig, ResultList, User, Video, VideosOverview } from '@shared/models' @@ -151,7 +150,7 @@ describe('Test video NSFW policy', function () { const password = 'my super password' await createUser({ url: server.url, accessToken: server.accessToken, username: username, password: password }) - userAccessToken = await userLogin(server, { username, password }) + userAccessToken = await server.loginCommand.getAccessToken({ username, password }) const res = await getMyUserInformation(server.url, userAccessToken) const user = res.body diff --git a/server/tests/api/videos/video-playlists.ts b/server/tests/api/videos/video-playlists.ts index 2bb019348..38133e2ce 100644 --- a/server/tests/api/videos/video-playlists.ts +++ b/server/tests/api/videos/video-playlists.ts @@ -10,7 +10,6 @@ import { doubleFollow, flushAndRunMultipleServers, generateUserAccessToken, - getAccessToken, getMyUserInformation, PlaylistsCommand, removeUser, @@ -21,7 +20,6 @@ import { updateVideo, uploadVideo, uploadVideoAndGetId, - userLogin, wait, waitJobs } from '@shared/extra-utils' @@ -122,7 +120,7 @@ describe('Test video playlists', function () { username: 'user1', password: 'password' }) - userTokenServer1 = await getAccessToken(servers[0].url, 'user1', 'password') + userTokenServer1 = await servers[0].loginCommand.getAccessToken('user1', 'password') } await waitJobs(servers) @@ -1129,7 +1127,7 @@ describe('Test video playlists', function () { }) const userId = res.body.user.id - const userAccessToken = await userLogin(servers[0], user) + const userAccessToken = await servers[0].loginCommand.getAccessToken(user) const resChannel = await getMyUserInformation(servers[0].url, userAccessToken) const userChannel = (resChannel.body as User).videoChannels[0] diff --git a/server/tests/api/videos/video-privacy.ts b/server/tests/api/videos/video-privacy.ts index 950aeb7cf..f831dd8a9 100644 --- a/server/tests/api/videos/video-privacy.ts +++ b/server/tests/api/videos/video-privacy.ts @@ -2,23 +2,24 @@ import 'mocha' import * as chai from 'chai' -import { HttpStatusCode } from '@shared/core-utils/miscs/http-error-codes' -import { Video, VideoCreateResult } from '@shared/models' +import { HttpStatusCode } from '@shared/core-utils' import { cleanupTests, + createUser, + doubleFollow, flushAndRunServer, + getMyVideos, + getVideo, getVideosList, getVideosListWithToken, + getVideoWithToken, ServerInfo, setAccessTokensToServers, - uploadVideo -} from '../../../../shared/extra-utils/index' -import { doubleFollow } from '../../../../shared/extra-utils/server/follows' -import { waitJobs } from '../../../../shared/extra-utils/server/jobs' -import { userLogin } from '../../../../shared/extra-utils/users/login' -import { createUser } from '../../../../shared/extra-utils/users/users' -import { getMyVideos, getVideo, getVideoWithToken, updateVideo } from '../../../../shared/extra-utils/videos/videos' -import { VideoPrivacy } from '../../../../shared/models/videos/video-privacy.enum' + updateVideo, + uploadVideo, + waitJobs +} from '@shared/extra-utils' +import { Video, VideoCreateResult, VideoPrivacy } from '@shared/models' const expect = chai.expect @@ -126,7 +127,7 @@ describe('Test video privacy', function () { } await createUser({ url: servers[0].url, accessToken: servers[0].accessToken, username: user.username, password: user.password }) - anotherUserToken = await userLogin(servers[0], user) + anotherUserToken = await servers[0].loginCommand.getAccessToken(user) await getVideoWithToken(servers[0].url, anotherUserToken, privateVideoUUID, HttpStatusCode.FORBIDDEN_403) }) diff --git a/server/tests/api/videos/videos-filter.ts b/server/tests/api/videos/videos-filter.ts index 7428b82c5..519dad646 100644 --- a/server/tests/api/videos/videos-filter.ts +++ b/server/tests/api/videos/videos-filter.ts @@ -1,7 +1,8 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ -import * as chai from 'chai' import 'mocha' +import * as chai from 'chai' +import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' import { cleanupTests, createUser, @@ -10,12 +11,10 @@ import { makeGetRequest, ServerInfo, setAccessTokensToServers, - uploadVideo, - userLogin + uploadVideo } from '../../../../shared/extra-utils' -import { Video, VideoPrivacy } from '../../../../shared/models/videos' import { UserRole } from '../../../../shared/models/users' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' +import { Video, VideoPrivacy } from '../../../../shared/models/videos' const expect = chai.expect @@ -72,7 +71,7 @@ describe('Test videos filter', function () { role: UserRole.MODERATOR } ) - server['moderatorAccessToken'] = await userLogin(server, moderator) + server['moderatorAccessToken'] = await server.loginCommand.getAccessToken(moderator) await uploadVideo(server.url, server.accessToken, { name: 'public ' + server.serverNumber }) diff --git a/server/tests/api/videos/videos-history.ts b/server/tests/api/videos/videos-history.ts index 9a7635c35..256271bd0 100644 --- a/server/tests/api/videos/videos-history.ts +++ b/server/tests/api/videos/videos-history.ts @@ -16,7 +16,6 @@ import { setAccessTokensToServers, updateMyUser, uploadVideo, - userLogin, wait } from '@shared/extra-utils' import { Video, VideoDetails } from '@shared/models' @@ -61,7 +60,7 @@ describe('Test videos history', function () { password: 'super password' } await createUser({ url: server.url, accessToken: server.accessToken, username: user.username, password: user.password }) - userAccessToken = await userLogin(server, user) + userAccessToken = await server.loginCommand.getAccessToken(user) }) it('Should get videos, without watching history', async function () { diff --git a/server/tests/cli/peertube.ts b/server/tests/cli/peertube.ts index 5ab07edb0..e055b4684 100644 --- a/server/tests/cli/peertube.ts +++ b/server/tests/cli/peertube.ts @@ -21,7 +21,6 @@ import { setAccessTokensToServers, testHelloWorldRegisteredSettings, uploadVideoAndGetId, - userLogin, waitJobs } from '../../../shared/extra-utils' @@ -41,7 +40,7 @@ describe('Test CLI wrapper', function () { await createUser({ url: server.url, accessToken: server.accessToken, username: 'user_1', password: 'super_password' }) - userAccessToken = await userLogin(server, { username: 'user_1', password: 'super_password' }) + userAccessToken = await server.loginCommand.getAccessToken({ username: 'user_1', password: 'super_password' }) { const attributes = { name: 'user_channel', displayName: 'User channel', support: 'super support text' } diff --git a/server/tests/cli/reset-password.ts b/server/tests/cli/reset-password.ts index 97a6eae15..a5f958bf7 100644 --- a/server/tests/cli/reset-password.ts +++ b/server/tests/cli/reset-password.ts @@ -1,14 +1,5 @@ import 'mocha' -import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' -import { - cleanupTests, - CLICommand, - createUser, - flushAndRunServer, - login, - ServerInfo, - setAccessTokensToServers -} from '../../../shared/extra-utils' +import { cleanupTests, CLICommand, createUser, flushAndRunServer, ServerInfo, setAccessTokensToServers } from '../../../shared/extra-utils' describe('Test reset password scripts', function () { let server: ServerInfo @@ -27,7 +18,7 @@ describe('Test reset password scripts', function () { const env = server.cliCommand.getEnv() await CLICommand.exec(`echo coucou | ${env} npm run reset-password -- -u user_1`) - await login(server.url, server.client, { username: 'user_1', password: 'coucou' }, HttpStatusCode.OK_200) + await server.loginCommand.login({ user: { username: 'user_1', password: 'coucou' } }) }) after(async function () { diff --git a/server/tests/external-plugins/auth-ldap.ts b/server/tests/external-plugins/auth-ldap.ts index 0d4edbee0..8153e2b81 100644 --- a/server/tests/external-plugins/auth-ldap.ts +++ b/server/tests/external-plugins/auth-ldap.ts @@ -2,8 +2,9 @@ import 'mocha' import { expect } from 'chai' +import { HttpStatusCode } from '@shared/core-utils' import { User } from '@shared/models/users/user.model' -import { blockUser, getMyUserInformation, setAccessTokensToServers, unblockUser, uploadVideo, userLogin } from '../../../shared/extra-utils' +import { blockUser, getMyUserInformation, setAccessTokensToServers, unblockUser, uploadVideo } from '../../../shared/extra-utils' import { cleanupTests, flushAndRunServer, ServerInfo } from '../../../shared/extra-utils/server/servers' describe('Official plugin auth-ldap', function () { @@ -21,7 +22,7 @@ describe('Official plugin auth-ldap', function () { }) it('Should not login with without LDAP settings', async function () { - await userLogin(server, { username: 'fry', password: 'fry' }, 400) + await server.loginCommand.login({ user: { username: 'fry', password: 'fry' }, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) it('Should not login with bad LDAP settings', async function () { @@ -39,7 +40,7 @@ describe('Official plugin auth-ldap', function () { } }) - await userLogin(server, { username: 'fry', password: 'fry' }, 400) + await server.loginCommand.login({ user: { username: 'fry', password: 'fry' }, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) it('Should not login with good LDAP settings but wrong username/password', async function () { @@ -57,16 +58,16 @@ describe('Official plugin auth-ldap', function () { } }) - await userLogin(server, { username: 'fry', password: 'bad password' }, 400) - await userLogin(server, { username: 'fryr', password: 'fry' }, 400) + await server.loginCommand.login({ user: { username: 'fry', password: 'bad password' }, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) + await server.loginCommand.login({ user: { username: 'fryr', password: 'fry' }, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) it('Should login with the appropriate username/password', async function () { - accessToken = await userLogin(server, { username: 'fry', password: 'fry' }) + accessToken = await server.loginCommand.getAccessToken({ username: 'fry', password: 'fry' }) }) it('Should login with the appropriate email/password', async function () { - accessToken = await userLogin(server, { username: 'fry@planetexpress.com', password: 'fry' }) + accessToken = await server.loginCommand.getAccessToken({ username: 'fry@planetexpress.com', password: 'fry' }) }) it('Should login get my profile', async function () { @@ -86,19 +87,25 @@ describe('Official plugin auth-ldap', function () { it('Should not be able to login if the user is banned', async function () { await blockUser(server.url, userId, server.accessToken) - await userLogin(server, { username: 'fry@planetexpress.com', password: 'fry' }, 400) + await server.loginCommand.login({ + user: { username: 'fry@planetexpress.com', password: 'fry' }, + expectedStatus: HttpStatusCode.BAD_REQUEST_400 + }) }) it('Should be able to login if the user is unbanned', async function () { await unblockUser(server.url, userId, server.accessToken) - await userLogin(server, { username: 'fry@planetexpress.com', password: 'fry' }) + await server.loginCommand.login({ user: { username: 'fry@planetexpress.com', password: 'fry' } }) }) it('Should not login if the plugin is uninstalled', async function () { await server.pluginsCommand.uninstall({ npmName: 'peertube-plugin-auth-ldap' }) - await userLogin(server, { username: 'fry@planetexpress.com', password: 'fry' }, 400) + await server.loginCommand.login({ + user: { username: 'fry@planetexpress.com', password: 'fry' }, + expectedStatus: HttpStatusCode.BAD_REQUEST_400 + }) }) after(async function () { diff --git a/server/tests/feeds/feeds.ts b/server/tests/feeds/feeds.ts index 610849105..9c78ae0e8 100644 --- a/server/tests/feeds/feeds.ts +++ b/server/tests/feeds/feeds.ts @@ -17,7 +17,6 @@ import { setAccessTokensToServers, uploadVideo, uploadVideoAndGetId, - userLogin, waitJobs } from '@shared/extra-utils' import { User, VideoPrivacy } from '@shared/models' @@ -64,7 +63,7 @@ describe('Test syndication feeds', () => { { const attr = { username: 'john', password: 'password' } await createUser({ url: servers[0].url, accessToken: servers[0].accessToken, username: attr.username, password: attr.password }) - userAccessToken = await userLogin(servers[0], attr) + userAccessToken = await servers[0].loginCommand.getAccessToken(attr) const res = await getMyUserInformation(servers[0].url, userAccessToken) const user: User = res.body @@ -301,7 +300,7 @@ describe('Test syndication feeds', () => { it('Should list no videos for a user with no videos and no subscriptions', async function () { const attr = { username: 'feeduser', password: 'password' } await createUser({ url: servers[0].url, accessToken: servers[0].accessToken, username: attr.username, password: attr.password }) - const feeduserAccessToken = await userLogin(servers[0], attr) + const feeduserAccessToken = await servers[0].loginCommand.getAccessToken(attr) { const res = await getMyUserInformation(servers[0].url, feeduserAccessToken) diff --git a/server/tests/plugins/action-hooks.ts b/server/tests/plugins/action-hooks.ts index cf81e44b7..84f4e8501 100644 --- a/server/tests/plugins/action-hooks.ts +++ b/server/tests/plugins/action-hooks.ts @@ -14,7 +14,6 @@ import { updateUser, updateVideo, uploadVideo, - userLogin, viewVideo } from '../../../shared/extra-utils' import { @@ -138,7 +137,7 @@ describe('Test plugin action hooks', function () { }) it('Should run action:api.user.oauth2-got-token', async function () { - await userLogin(servers[0], { username: 'created_user', password: 'super_password' }) + await servers[0].loginCommand.getAccessToken('created_user', 'super_password') await checkHook('action:api.user.oauth2-got-token') }) diff --git a/server/tests/plugins/external-auth.ts b/server/tests/plugins/external-auth.ts index f7cee588a..e421fd224 100644 --- a/server/tests/plugins/external-auth.ts +++ b/server/tests/plugins/external-auth.ts @@ -9,14 +9,10 @@ import { decodeQueryString, flushAndRunServer, getMyUserInformation, - loginUsingExternalToken, - logout, PluginsCommand, - refreshToken, ServerInfo, setAccessTokensToServers, updateMyUser, - userLogin, wait } from '@shared/extra-utils' import { User, UserRole } from '@shared/models' @@ -43,12 +39,11 @@ async function loginExternal (options: { const location = res.header.location const { externalAuthToken } = decodeQueryString(location) - const resLogin = await loginUsingExternalToken( - options.server, - options.username, - externalAuthToken as string, - options.statusCodeExpectedStep2 - ) + const resLogin = await options.server.loginCommand.loginUsingExternalToken({ + username: options.username, + externalAuthToken: externalAuthToken as string, + expectedStatus: options.statusCodeExpectedStep2 + }) return resLogin.body } @@ -110,13 +105,17 @@ describe('Test external auth plugins', function () { }) it('Should reject auto external login with a missing or invalid token', async function () { - await loginUsingExternalToken(server, 'cyan', '', HttpStatusCode.BAD_REQUEST_400) - await loginUsingExternalToken(server, 'cyan', 'blabla', HttpStatusCode.BAD_REQUEST_400) + const command = server.loginCommand + + await command.loginUsingExternalToken({ username: 'cyan', externalAuthToken: '', expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) + await command.loginUsingExternalToken({ username: 'cyan', externalAuthToken: 'blabla', expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) it('Should reject auto external login with a missing or invalid username', async function () { - await loginUsingExternalToken(server, '', externalAuthToken, HttpStatusCode.BAD_REQUEST_400) - await loginUsingExternalToken(server, '', externalAuthToken, HttpStatusCode.BAD_REQUEST_400) + const command = server.loginCommand + + await command.loginUsingExternalToken({ username: '', externalAuthToken, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) + await command.loginUsingExternalToken({ username: '', externalAuthToken, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) it('Should reject auto external login with an expired token', async function () { @@ -124,7 +123,11 @@ describe('Test external auth plugins', function () { await wait(5000) - await loginUsingExternalToken(server, 'cyan', externalAuthToken, HttpStatusCode.BAD_REQUEST_400) + await server.loginCommand.loginUsingExternalToken({ + username: 'cyan', + externalAuthToken, + expectedStatus: HttpStatusCode.BAD_REQUEST_400 + }) await server.serversCommand.waitUntilLog('expired external auth token', 2) }) @@ -182,7 +185,7 @@ describe('Test external auth plugins', function () { it('Should refresh Cyan token, but not Kefka token', async function () { { - const resRefresh = await refreshToken(server, cyanRefreshToken) + const resRefresh = await server.loginCommand.refreshToken({ refreshToken: cyanRefreshToken }) cyanAccessToken = resRefresh.body.access_token cyanRefreshToken = resRefresh.body.refresh_token @@ -192,7 +195,7 @@ describe('Test external auth plugins', function () { } { - await refreshToken(server, kefkaRefreshToken, HttpStatusCode.BAD_REQUEST_400) + await server.loginCommand.refreshToken({ refreshToken: kefkaRefreshToken, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) } }) @@ -212,7 +215,7 @@ describe('Test external auth plugins', function () { }) it('Should logout Cyan', async function () { - await logout(server.url, cyanAccessToken) + await server.loginCommand.logout({ token: cyanAccessToken }) }) it('Should have logged out Cyan', async function () { @@ -269,7 +272,7 @@ describe('Test external auth plugins', function () { settings: { disableKefka: true } }) - await userLogin(server, { username: 'kefka', password: 'fake' }, HttpStatusCode.BAD_REQUEST_400) + await server.loginCommand.login({ user: { username: 'kefka', password: 'fake' }, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) await loginExternal({ server, @@ -307,9 +310,9 @@ describe('Test external auth plugins', function () { statusCodeExpected: HttpStatusCode.NOT_FOUND_404 }) - await userLogin(server, { username: 'cyan', password: null }, HttpStatusCode.BAD_REQUEST_400) - await userLogin(server, { username: 'cyan', password: '' }, HttpStatusCode.BAD_REQUEST_400) - await userLogin(server, { username: 'cyan', password: 'fake' }, HttpStatusCode.BAD_REQUEST_400) + await server.loginCommand.login({ user: { username: 'cyan', password: null }, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) + await server.loginCommand.login({ user: { username: 'cyan', password: '' }, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) + await server.loginCommand.login({ user: { username: 'cyan', password: 'fake' }, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) it('Should not login kefka with another plugin', async function () { @@ -369,9 +372,8 @@ describe('Test external auth plugins', function () { username: 'cid' }) - const resLogout = await logout(server.url, resLogin.access_token) - - expect(resLogout.body.redirectUrl).to.equal('https://example.com/redirectUrl') + const { redirectUrl } = await server.loginCommand.logout({ token: resLogin.access_token }) + expect(redirectUrl).to.equal('https://example.com/redirectUrl') }) it('Should call the plugin\'s onLogout method with the request', async function () { @@ -382,8 +384,7 @@ describe('Test external auth plugins', function () { username: 'cid' }) - const resLogout = await logout(server.url, resLogin.access_token) - - expect(resLogout.body.redirectUrl).to.equal('https://example.com/redirectUrl?access_token=' + resLogin.access_token) + const { redirectUrl } = await server.loginCommand.logout({ token: resLogin.access_token }) + expect(redirectUrl).to.equal('https://example.com/redirectUrl?access_token=' + resLogin.access_token) }) }) diff --git a/server/tests/plugins/id-and-pass-auth.ts b/server/tests/plugins/id-and-pass-auth.ts index a0b31bc1f..e3da64110 100644 --- a/server/tests/plugins/id-and-pass-auth.ts +++ b/server/tests/plugins/id-and-pass-auth.ts @@ -2,19 +2,16 @@ import 'mocha' import { expect } from 'chai' +import { HttpStatusCode } from '@shared/core-utils' import { cleanupTests, flushAndRunServer, getMyUserInformation, getUsersList, - login, - logout, PluginsCommand, - refreshToken, ServerInfo, setAccessTokensToServers, updateMyUser, - userLogin, wait } from '@shared/extra-utils' import { User, UserRole } from '@shared/models' @@ -52,11 +49,11 @@ describe('Test id and pass auth plugins', function () { }) it('Should not login', async function () { - await userLogin(server, { username: 'toto', password: 'password' }, 400) + await server.loginCommand.login({ user: { username: 'toto', password: 'password' }, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) it('Should login Spyro, create the user and use the token', async function () { - const accessToken = await userLogin(server, { username: 'spyro', password: 'spyro password' }) + const accessToken = await server.loginCommand.getAccessToken({ username: 'spyro', password: 'spyro password' }) const res = await getMyUserInformation(server.url, accessToken) @@ -68,9 +65,9 @@ describe('Test id and pass auth plugins', function () { it('Should login Crash, create the user and use the token', async function () { { - const res = await login(server.url, server.client, { username: 'crash', password: 'crash password' }) - crashAccessToken = res.body.access_token - crashRefreshToken = res.body.refresh_token + const body = await server.loginCommand.login({ user: { username: 'crash', password: 'crash password' } }) + crashAccessToken = body.access_token + crashRefreshToken = body.refresh_token } { @@ -85,9 +82,9 @@ describe('Test id and pass auth plugins', function () { it('Should login the first Laguna, create the user and use the token', async function () { { - const res = await login(server.url, server.client, { username: 'laguna', password: 'laguna password' }) - lagunaAccessToken = res.body.access_token - lagunaRefreshToken = res.body.refresh_token + const body = await server.loginCommand.login({ user: { username: 'laguna', password: 'laguna password' } }) + lagunaAccessToken = body.access_token + lagunaRefreshToken = body.refresh_token } { @@ -102,7 +99,7 @@ describe('Test id and pass auth plugins', function () { it('Should refresh crash token, but not laguna token', async function () { { - const resRefresh = await refreshToken(server, crashRefreshToken) + const resRefresh = await server.loginCommand.refreshToken({ refreshToken: crashRefreshToken }) crashAccessToken = resRefresh.body.access_token crashRefreshToken = resRefresh.body.refresh_token @@ -112,7 +109,7 @@ describe('Test id and pass auth plugins', function () { } { - await refreshToken(server, lagunaRefreshToken, 400) + await server.loginCommand.refreshToken({ refreshToken: lagunaRefreshToken, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) } }) @@ -132,7 +129,7 @@ describe('Test id and pass auth plugins', function () { }) it('Should logout Crash', async function () { - await logout(server.url, crashAccessToken) + await server.loginCommand.logout({ token: crashAccessToken }) }) it('Should have logged out Crash', async function () { @@ -142,7 +139,7 @@ describe('Test id and pass auth plugins', function () { }) it('Should login Crash and keep the old existing profile', async function () { - crashAccessToken = await userLogin(server, { username: 'crash', password: 'crash password' }) + crashAccessToken = await server.loginCommand.getAccessToken({ username: 'crash', password: 'crash password' }) const res = await getMyUserInformation(server.url, crashAccessToken) @@ -162,16 +159,18 @@ describe('Test id and pass auth plugins', function () { }) it('Should reject an invalid username, email, role or display name', async function () { - await userLogin(server, { username: 'ward', password: 'ward password' }, 400) + const command = server.loginCommand + + await command.login({ user: { username: 'ward', password: 'ward password' }, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) await server.serversCommand.waitUntilLog('valid username') - await userLogin(server, { username: 'kiros', password: 'kiros password' }, 400) + await command.login({ user: { username: 'kiros', password: 'kiros password' }, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) await server.serversCommand.waitUntilLog('valid display name') - await userLogin(server, { username: 'raine', password: 'raine password' }, 400) + await command.login({ user: { username: 'raine', password: 'raine password' }, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) await server.serversCommand.waitUntilLog('valid role') - await userLogin(server, { username: 'ellone', password: 'elonne password' }, 400) + await command.login({ user: { username: 'ellone', password: 'elonne password' }, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) await server.serversCommand.waitUntilLog('valid email') }) @@ -181,8 +180,9 @@ describe('Test id and pass auth plugins', function () { settings: { disableSpyro: true } }) - await userLogin(server, { username: 'spyro', password: 'spyro password' }, 400) - await userLogin(server, { username: 'spyro', password: 'fake' }, 400) + const command = server.loginCommand + await command.login({ user: { username: 'spyro', password: 'spyro password' }, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) + await command.login({ user: { username: 'spyro', password: 'fake' }, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) it('Should have disabled this auth', async function () { @@ -198,7 +198,10 @@ describe('Test id and pass auth plugins', function () { it('Should uninstall the plugin one and do not login existing Crash', async function () { await server.pluginsCommand.uninstall({ npmName: 'peertube-plugin-test-id-pass-auth-one' }) - await userLogin(server, { username: 'crash', password: 'crash password' }, 400) + await server.loginCommand.login({ + user: { username: 'crash', password: 'crash password' }, + expectedStatus: HttpStatusCode.BAD_REQUEST_400 + }) }) it('Should display the correct configuration', async function () { diff --git a/shared/extra-utils/requests/requests.ts b/shared/extra-utils/requests/requests.ts index f9d112aca..c5ee63e05 100644 --- a/shared/extra-utils/requests/requests.ts +++ b/shared/extra-utils/requests/requests.ts @@ -27,6 +27,7 @@ function makeGetRequest (options: { range?: string redirects?: number accept?: string + host?: string }) { if (!options.statusCodeExpected) options.statusCodeExpected = HttpStatusCode.BAD_REQUEST_400 if (options.contentType === undefined) options.contentType = 'application/json' @@ -38,6 +39,7 @@ function makeGetRequest (options: { if (options.query) req.query(options.query) if (options.range) req.set('Range', options.range) if (options.accept) req.set('Accept', options.accept) + if (options.host) req.set('Host', options.host) if (options.redirects) req.redirects(options.redirects) return req.expect(options.statusCodeExpected) @@ -113,6 +115,7 @@ function makePostBodyRequest (options: { path: string token?: string fields?: { [ fieldName: string ]: any } + type?: string statusCodeExpected?: HttpStatusCode }) { if (!options.fields) options.fields = {} @@ -123,6 +126,7 @@ function makePostBodyRequest (options: { .set('Accept', 'application/json') if (options.token) req.set('Authorization', 'Bearer ' + options.token) + if (options.type) req.type(options.type) return req.send(options.fields) .expect(options.statusCodeExpected) diff --git a/shared/extra-utils/server/clients.ts b/shared/extra-utils/server/clients.ts deleted file mode 100644 index 894fe4911..000000000 --- a/shared/extra-utils/server/clients.ts +++ /dev/null @@ -1,20 +0,0 @@ -import * as request from 'supertest' -import { URL } from 'url' -import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' - -function getClient (url: string) { - const path = '/api/v1/oauth-clients/local' - - return request(url) - .get(path) - .set('Host', new URL(url).host) - .set('Accept', 'application/json') - .expect(HttpStatusCode.OK_200) - .expect('Content-Type', /json/) -} - -// --------------------------------------------------------------------------- - -export { - getClient -} diff --git a/shared/extra-utils/server/servers.ts b/shared/extra-utils/server/servers.ts index f5dc0326f..4d9599680 100644 --- a/shared/extra-utils/server/servers.ts +++ b/shared/extra-utils/server/servers.ts @@ -16,7 +16,7 @@ import { AbusesCommand } from '../moderation' import { OverviewsCommand } from '../overviews' import { SearchCommand } from '../search' import { SocketIOCommand } from '../socket' -import { AccountsCommand, BlocklistCommand, NotificationsCommand, SubscriptionsCommand } from '../users' +import { AccountsCommand, BlocklistCommand, LoginCommand, NotificationsCommand, SubscriptionsCommand } from '../users' import { BlacklistCommand, CaptionsCommand, @@ -126,6 +126,7 @@ interface ServerInfo { sqlCommand?: SQLCommand notificationsCommand?: NotificationsCommand serversCommand?: ServersCommand + loginCommand?: LoginCommand } function flushAndRunMultipleServers (totalServers: number, configOverride?: Object) { @@ -357,6 +358,7 @@ function assignCommands (server: ServerInfo) { server.sqlCommand = new SQLCommand(server) server.notificationsCommand = new NotificationsCommand(server) server.serversCommand = new ServersCommand(server) + server.loginCommand = new LoginCommand(server) } async function reRunServer (server: ServerInfo, configOverride?: any) { diff --git a/shared/extra-utils/shared/abstract-command.ts b/shared/extra-utils/shared/abstract-command.ts index 4e61554a2..af9ecd926 100644 --- a/shared/extra-utils/shared/abstract-command.ts +++ b/shared/extra-utils/shared/abstract-command.ts @@ -33,6 +33,7 @@ interface InternalGetCommandOptions extends InternalCommonCommandOptions { accept?: string redirects?: number range?: string + host?: string } abstract class AbstractCommand { @@ -78,7 +79,7 @@ abstract class AbstractCommand { } protected getRequest (options: InternalGetCommandOptions) { - const { redirects, query, contentType, accept, range } = options + const { redirects, query, contentType, accept, range, host } = options return makeGetRequest({ ...this.buildCommonRequestOptions(options), @@ -87,6 +88,7 @@ abstract class AbstractCommand { query, contentType, range, + host, accept }) } @@ -109,13 +111,15 @@ abstract class AbstractCommand { protected postBodyRequest (options: InternalCommonCommandOptions & { fields?: { [ fieldName: string ]: any } + type?: string }) { - const { fields } = options + const { type, fields } = options return makePostBodyRequest({ ...this.buildCommonRequestOptions(options), - fields + fields, + type }) } diff --git a/shared/extra-utils/users/index.ts b/shared/extra-utils/users/index.ts index ed166c756..b200ae705 100644 --- a/shared/extra-utils/users/index.ts +++ b/shared/extra-utils/users/index.ts @@ -2,6 +2,7 @@ export * from './accounts-command' export * from './accounts' export * from './blocklist-command' export * from './login' +export * from './login-command' export * from './notifications' export * from './notifications-command' export * from './subscriptions-command' diff --git a/shared/extra-utils/users/login-command.ts b/shared/extra-utils/users/login-command.ts new file mode 100644 index 000000000..97efcb766 --- /dev/null +++ b/shared/extra-utils/users/login-command.ts @@ -0,0 +1,134 @@ +import { PeerTubeRequestError } from '@server/helpers/requests' +import { HttpStatusCode } from '@shared/core-utils' +import { PeerTubeProblemDocument } from '@shared/models' +import { unwrapBody } from '../requests' +import { AbstractCommand, OverrideCommandOptions } from '../shared' + +export class LoginCommand extends AbstractCommand { + + login (options: OverrideCommandOptions & { + client?: { id?: string, secret?: string } + user?: { username: string, password: string } + } = {}) { + const { client = this.server.client, user = this.server.user } = options + const path = '/api/v1/users/token' + + const body = { + client_id: client.id, + client_secret: client.secret, + username: user.username, + password: user.password, + response_type: 'code', + grant_type: 'password', + scope: 'upload' + } + + return unwrapBody<{ access_token: string, refresh_token: string } & PeerTubeProblemDocument>(this.postBodyRequest({ + ...options, + + path, + type: 'form', + fields: body, + implicitToken: false, + defaultExpectedStatus: HttpStatusCode.OK_200 + })) + } + + getAccessToken (user?: { username: string, password: string }): Promise + getAccessToken (username: string, password: string): Promise + async getAccessToken (arg1?: { username: string, password: string } | string, password?: string) { + let user: { username: string, password: string } + + if (!arg1) user = this.server.user + else if (typeof arg1 === 'object') user = arg1 + else user = { username: arg1, password } + + try { + const body = await this.login({ user }) + + return body.access_token + } catch (err) { + throw new Error('Cannot authenticate. Please check your username/password.') + } + } + + loginUsingExternalToken (options: OverrideCommandOptions & { + username: string + externalAuthToken: string + }) { + const { username, externalAuthToken } = options + const path = '/api/v1/users/token' + + const body = { + client_id: this.server.client.id, + client_secret: this.server.client.secret, + username: username, + response_type: 'code', + grant_type: 'password', + scope: 'upload', + externalAuthToken + } + + return this.postBodyRequest({ + ...options, + + path, + type: 'form', + fields: body, + implicitToken: false, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } + + logout (options: OverrideCommandOptions & { + token: string + }) { + const path = '/api/v1/users/revoke-token' + + return unwrapBody<{ redirectUrl: string }>(this.postBodyRequest({ + ...options, + + path, + type: 'form', + implicitToken: false, + defaultExpectedStatus: HttpStatusCode.OK_200 + })) + } + + refreshToken (options: OverrideCommandOptions & { + refreshToken: string + }) { + const path = '/api/v1/users/token' + + const body = { + client_id: this.server.client.id, + client_secret: this.server.client.secret, + refresh_token: options.refreshToken, + response_type: 'code', + grant_type: 'refresh_token' + } + + return this.postBodyRequest({ + ...options, + + path, + type: 'form', + fields: body, + implicitToken: false, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } + + getClient (options: OverrideCommandOptions = {}) { + const path = '/api/v1/oauth-clients/local' + + return this.getRequestBody<{ client_id: string, client_secret: string }>({ + ...options, + + path, + host: this.server.host, + implicitToken: false, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } +} diff --git a/shared/extra-utils/users/login.ts b/shared/extra-utils/users/login.ts index c14367542..d4ee8e517 100644 --- a/shared/extra-utils/users/login.ts +++ b/shared/extra-utils/users/login.ts @@ -1,133 +1,19 @@ -import * as request from 'supertest' - import { ServerInfo } from '../server/servers' -import { getClient } from '../server/clients' -import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' - -type Client = { id?: string, secret?: string } -type User = { username: string, password: string } -type Server = { url?: string, client?: Client, user?: User } - -function login (url: string, client: Client, user: User, expectedStatus = HttpStatusCode.OK_200) { - const path = '/api/v1/users/token' - - const body = { - client_id: client.id, - client_secret: client.secret, - username: user.username, - password: user.password, - response_type: 'code', - grant_type: 'password', - scope: 'upload' - } - - return request(url) - .post(path) - .type('form') - .send(body) - .expect(expectedStatus) -} - -function logout (url: string, token: string, expectedStatus = HttpStatusCode.OK_200) { - const path = '/api/v1/users/revoke-token' - - return request(url) - .post(path) - .set('Authorization', 'Bearer ' + token) - .type('form') - .expect(expectedStatus) -} - -async function serverLogin (server: Server) { - const res = await login(server.url, server.client, server.user, HttpStatusCode.OK_200) - - return res.body.access_token as string -} - -function refreshToken (server: ServerInfo, refreshToken: string, expectedStatus = HttpStatusCode.OK_200) { - const path = '/api/v1/users/token' - - const body = { - client_id: server.client.id, - client_secret: server.client.secret, - refresh_token: refreshToken, - response_type: 'code', - grant_type: 'refresh_token' - } - - return request(server.url) - .post(path) - .type('form') - .send(body) - .expect(expectedStatus) -} - -async function userLogin (server: Server, user: User, expectedStatus = HttpStatusCode.OK_200) { - const res = await login(server.url, server.client, user, expectedStatus) - - return res.body.access_token as string -} - -async function getAccessToken (url: string, username: string, password: string) { - const resClient = await getClient(url) - const client = { - id: resClient.body.client_id, - secret: resClient.body.client_secret - } - - const user = { username, password } - - try { - const res = await login(url, client, user) - return res.body.access_token - } catch (err) { - throw new Error('Cannot authenticate. Please check your username/password.') - } -} function setAccessTokensToServers (servers: ServerInfo[]) { const tasks: Promise[] = [] for (const server of servers) { - const p = serverLogin(server).then(t => { server.accessToken = t }) + const p = server.loginCommand.getAccessToken() + .then(t => { server.accessToken = t }) tasks.push(p) } return Promise.all(tasks) } -function loginUsingExternalToken (server: Server, username: string, externalAuthToken: string, expectedStatus = HttpStatusCode.OK_200) { - const path = '/api/v1/users/token' - - const body = { - client_id: server.client.id, - client_secret: server.client.secret, - username: username, - response_type: 'code', - grant_type: 'password', - scope: 'upload', - externalAuthToken - } - - return request(server.url) - .post(path) - .type('form') - .send(body) - .expect(expectedStatus) -} - // --------------------------------------------------------------------------- export { - login, - logout, - serverLogin, - refreshToken, - userLogin, - getAccessToken, - setAccessTokensToServers, - Server, - Client, - User, - loginUsingExternalToken + setAccessTokensToServers } diff --git a/shared/extra-utils/users/notifications.ts b/shared/extra-utils/users/notifications.ts index 81f0729fa..79cb6f617 100644 --- a/shared/extra-utils/users/notifications.ts +++ b/shared/extra-utils/users/notifications.ts @@ -7,7 +7,7 @@ import { UserNotification, UserNotificationSetting, UserNotificationSettingValue import { MockSmtpServer } from '../mock-servers/mock-email' import { doubleFollow } from '../server/follows' import { flushAndRunMultipleServers, ServerInfo } from '../server/servers' -import { setAccessTokensToServers, userLogin } from './login' +import { setAccessTokensToServers } from './login' import { createUser, getMyUserInformation } from './users' function getAllNotificationsSettings (): UserNotificationSetting { @@ -662,7 +662,7 @@ async function prepareNotificationsTest (serversCount = 3, overrideConfigArg: an password: user.password, videoQuota: 10 * 1000 * 1000 }) - const userAccessToken = await userLogin(servers[0], user) + const userAccessToken = await servers[0].loginCommand.getAccessToken(user) await servers[0].notificationsCommand.updateMySettings({ token: userAccessToken, settings: getAllNotificationsSettings() }) await servers[0].notificationsCommand.updateMySettings({ settings: getAllNotificationsSettings() }) diff --git a/shared/extra-utils/users/users.ts b/shared/extra-utils/users/users.ts index 0f15962ad..835ad08ba 100644 --- a/shared/extra-utils/users/users.ts +++ b/shared/extra-utils/users/users.ts @@ -7,7 +7,6 @@ import { UserRegister } from '../../models/users/user-register.model' import { UserRole } from '../../models/users/user-role' import { makeGetRequest, makePostBodyRequest, makePutBodyRequest, updateImageRequest } from '../requests/requests' import { ServerInfo } from '../server/servers' -import { userLogin } from './login' function createUser (parameters: { url: string @@ -55,7 +54,7 @@ async function generateUser (server: ServerInfo, username: string) { const password = 'my super password' const resCreate = await createUser({ url: server.url, accessToken: server.accessToken, username: username, password: password }) - const token = await userLogin(server, { username, password }) + const token = await server.loginCommand.getAccessToken({ username, password }) const resMe = await getMyUserInformation(server.url, token) @@ -70,7 +69,7 @@ async function generateUserAccessToken (server: ServerInfo, username: string) { const password = 'my super password' await createUser({ url: server.url, accessToken: server.accessToken, username: username, password: password }) - return userLogin(server, { username, password }) + return server.loginCommand.getAccessToken({ username, password }) } function registerUser (url: string, username: string, password: string, specialStatus = HttpStatusCode.NO_CONTENT_204) { -- cgit v1.2.3 From d0a0fa429d4651710ed951a3c11af0219e408964 Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Tue, 13 Jul 2021 11:44:16 +0200 Subject: Adapt CLI to new commands --- server/tools/cli.ts | 31 +++++++++++++++++-------------- server/tools/peertube-auth.ts | 6 +++--- server/tools/peertube-get-access-token.ts | 10 ++++++---- server/tools/peertube-import-videos.ts | 12 ++++++------ server/tools/peertube-plugins.ts | 18 +++++++++--------- server/tools/peertube-redundancy.ts | 14 +++++++------- server/tools/peertube-upload.ts | 9 ++++----- shared/extra-utils/users/login-command.ts | 7 +++---- 8 files changed, 55 insertions(+), 52 deletions(-) diff --git a/server/tools/cli.ts b/server/tools/cli.ts index 0528859a4..3e0e03b97 100644 --- a/server/tools/cli.ts +++ b/server/tools/cli.ts @@ -3,12 +3,10 @@ import { Netrc } from 'netrc-parser' import { join } from 'path' import { createLogger, format, transports } from 'winston' import { assignCommands, ServerInfo } from '@shared/extra-utils' -import { getAccessToken } from '@shared/extra-utils/users/login' import { getMyUserInformation } from '@shared/extra-utils/users/users' import { User, UserRole } from '@shared/models' -import { root } from '../../shared/extra-utils/miscs/miscs' import { VideoPrivacy } from '../../shared/models/videos' -import { getAppNumber, isTestInstance } from '../helpers/core-utils' +import { getAppNumber, isTestInstance, root } from '../helpers/core-utils' let configName = 'PeerTube/CLI' if (isTestInstance()) configName += `-${getAppNumber()}` @@ -17,9 +15,9 @@ const config = require('application-config')(configName) const version = require('../../../package.json').version -async function getAdminTokenOrDie (url: string, username: string, password: string) { - const accessToken = await getAccessToken(url, username, password) - const resMe = await getMyUserInformation(url, accessToken) +async function getAdminTokenOrDie (server: ServerInfo, username: string, password: string) { + const accessToken = await server.loginCommand.getAccessToken(username, password) + const resMe = await getMyUserInformation(server.url, accessToken) const me: User = resMe.body if (me.role !== UserRole.ADMINISTRATOR) { @@ -30,10 +28,6 @@ async function getAdminTokenOrDie (url: string, username: string, password: stri return accessToken } -async function getAccessTokenOrDie (url: string, username: string, password: string) { - return getAccessToken(url, username, password) -} - interface Settings { remotes: any[] default: number @@ -187,13 +181,22 @@ function getServerCredentials (program: Command) { }) } -function buildServer (url: string, accessToken?: string): ServerInfo { - const server = { url, accessToken, internalServerNumber: undefined } +function buildServer (url: string): ServerInfo { + const server = { url, internalServerNumber: undefined } assignCommands(server) return server } +async function assignToken (server: ServerInfo, username: string, password: string) { + const bodyClient = await server.loginCommand.getClient() + const client = { id: bodyClient.client_id, secret: bodyClient.client_secret } + + const body = await server.loginCommand.login({ client, user: { username, password } }) + + server.accessToken = body.access_token +} + function getLogger (logLevel = 'info') { const logLevels = { 0: 0, @@ -241,6 +244,6 @@ export { buildVideoAttributesFromCommander, getAdminTokenOrDie, - getAccessTokenOrDie, - buildServer + buildServer, + assignToken } diff --git a/server/tools/peertube-auth.ts b/server/tools/peertube-auth.ts index 1934e7986..b9f4ef4f8 100644 --- a/server/tools/peertube-auth.ts +++ b/server/tools/peertube-auth.ts @@ -5,9 +5,8 @@ registerTSPaths() import { OptionValues, program } from 'commander' import * as prompt from 'prompt' -import { getNetrc, getSettings, writeSettings } from './cli' +import { assignToken, buildServer, getNetrc, getSettings, writeSettings } from './cli' import { isUserUsernameValid } from '../helpers/custom-validators/users' -import { getAccessToken } from '../../shared/extra-utils' import * as CliTable3 from 'cli-table3' async function delInstance (url: string) { @@ -97,7 +96,8 @@ program // @see https://github.com/Chocobozzz/PeerTube/issues/3520 result.url = stripExtraneousFromPeerTubeUrl(result.url) - await getAccessToken(result.url, result.username, result.password) + const server = buildServer(result.url) + await assignToken(server, result.username, result.password) } catch (err) { console.error(err.message) process.exit(-1) diff --git a/server/tools/peertube-get-access-token.ts b/server/tools/peertube-get-access-token.ts index 5868d0548..a67de9180 100644 --- a/server/tools/peertube-get-access-token.ts +++ b/server/tools/peertube-get-access-token.ts @@ -2,7 +2,7 @@ import { registerTSPaths } from '../helpers/register-ts-paths' registerTSPaths() import { program } from 'commander' -import { getAccessToken } from '../../shared/extra-utils' +import { assignToken, buildServer } from './cli' program .option('-u, --url ', 'Server url') @@ -24,9 +24,11 @@ if ( process.exit(-1) } -getAccessToken(options.url, options.username, options.password) - .then(accessToken => { - console.log(accessToken) +const server = buildServer(options.url) + +assignToken(server, options.username, options.password) + .then(() => { + console.log(server.accessToken) process.exit(0) }) .catch(err => { diff --git a/server/tools/peertube-import-videos.ts b/server/tools/peertube-import-videos.ts index a546a8dbe..0a4d6fa6e 100644 --- a/server/tools/peertube-import-videos.ts +++ b/server/tools/peertube-import-videos.ts @@ -14,10 +14,10 @@ import { sha256 } from '../helpers/core-utils' import { doRequestAndSaveToFile } from '../helpers/requests' import { CONSTRAINTS_FIELDS } from '../initializers/constants' import { + assignToken, buildCommonVideoOptions, buildServer, buildVideoAttributesFromCommander, - getAccessTokenOrDie, getLogger, getServerCredentials } from './cli' @@ -232,8 +232,8 @@ async function uploadVideoOnPeerTube (parameters: { tags } - let accessToken = await getAccessTokenOrDie(url, username, password) - const server = buildServer(url, accessToken) + const server = buildServer(url) + await assignToken(server, username, password) const videoAttributes = await buildVideoAttributesFromCommander(server, program, defaultAttributes) @@ -247,14 +247,14 @@ async function uploadVideoOnPeerTube (parameters: { log.info('\nUploading on PeerTube video "%s".', videoAttributes.name) try { - await uploadVideo(url, accessToken, videoAttributes) + await uploadVideo(url, server.accessToken, videoAttributes) } catch (err) { if (err.message.indexOf('401') !== -1) { log.info('Got 401 Unauthorized, token may have expired, renewing token and retry.') - accessToken = await getAccessTokenOrDie(url, username, password) + server.accessToken = await server.loginCommand.getAccessToken(username, password) - await uploadVideo(url, accessToken, videoAttributes) + await uploadVideo(url, server.accessToken, videoAttributes) } else { exitError(err.message) } diff --git a/server/tools/peertube-plugins.ts b/server/tools/peertube-plugins.ts index 63541bf2c..22a09b779 100644 --- a/server/tools/peertube-plugins.ts +++ b/server/tools/peertube-plugins.ts @@ -4,7 +4,7 @@ import { registerTSPaths } from '../helpers/register-ts-paths' registerTSPaths() import { program, Command, OptionValues } from 'commander' -import { buildServer, getAdminTokenOrDie, getServerCredentials } from './cli' +import { assignToken, buildServer, getServerCredentials } from './cli' import { PluginType } from '../../shared/models' import { isAbsolute } from 'path' import * as CliTable3 from 'cli-table3' @@ -62,8 +62,8 @@ program.parse(process.argv) async function pluginsListCLI (command: Command, options: OptionValues) { const { url, username, password } = await getServerCredentials(command) - const token = await getAdminTokenOrDie(url, username, password) - const server = buildServer(url, token) + const server = buildServer(url) + await assignToken(server, username, password) let pluginType: PluginType if (options.onlyThemes) pluginType = PluginType.THEME @@ -105,8 +105,8 @@ async function installPluginCLI (command: Command, options: OptionValues) { } const { url, username, password } = await getServerCredentials(command) - const token = await getAdminTokenOrDie(url, username, password) - const server = buildServer(url, token) + const server = buildServer(url) + await assignToken(server, username, password) try { await server.pluginsCommand.install({ npmName: options.npmName, path: options.path }) @@ -132,8 +132,8 @@ async function updatePluginCLI (command: Command, options: OptionValues) { } const { url, username, password } = await getServerCredentials(command) - const token = await getAdminTokenOrDie(url, username, password) - const server = buildServer(url, token) + const server = buildServer(url) + await assignToken(server, username, password) try { await server.pluginsCommand.update({ npmName: options.npmName, path: options.path }) @@ -154,8 +154,8 @@ async function uninstallPluginCLI (command: Command, options: OptionValues) { } const { url, username, password } = await getServerCredentials(command) - const token = await getAdminTokenOrDie(url, username, password) - const server = buildServer(url, token) + const server = buildServer(url) + await assignToken(server, username, password) try { await server.pluginsCommand.uninstall({ npmName: options.npmName }) diff --git a/server/tools/peertube-redundancy.ts b/server/tools/peertube-redundancy.ts index 76d633f9e..0f6b3086c 100644 --- a/server/tools/peertube-redundancy.ts +++ b/server/tools/peertube-redundancy.ts @@ -8,7 +8,7 @@ import { URL } from 'url' import validator from 'validator' import { HttpStatusCode } from '@shared/core-utils/miscs/http-error-codes' import { VideoRedundanciesTarget } from '@shared/models' -import { buildServer, getAdminTokenOrDie, getServerCredentials } from './cli' +import { assignToken, buildServer, getServerCredentials } from './cli' import bytes = require('bytes') @@ -60,8 +60,8 @@ program.parse(process.argv) async function listRedundanciesCLI (target: VideoRedundanciesTarget) { const { url, username, password } = await getServerCredentials(program) - const token = await getAdminTokenOrDie(url, username, password) - const server = buildServer(url, token) + const server = buildServer(url) + await assignToken(server, username, password) const { data } = await server.redundancyCommand.listVideos({ start: 0, count: 100, sort: 'name', target }) @@ -104,8 +104,8 @@ async function listRedundanciesCLI (target: VideoRedundanciesTarget) { async function addRedundancyCLI (options: { video: number }, command: Command) { const { url, username, password } = await getServerCredentials(command) - const token = await getAdminTokenOrDie(url, username, password) - const server = buildServer(url, token) + const server = buildServer(url) + await assignToken(server, username, password) if (!options.video || validator.isInt('' + options.video) === false) { console.error('You need to specify the video id to duplicate and it should be a number.\n') @@ -134,8 +134,8 @@ async function addRedundancyCLI (options: { video: number }, command: Command) { async function removeRedundancyCLI (options: { video: number }, command: Command) { const { url, username, password } = await getServerCredentials(command) - const token = await getAdminTokenOrDie(url, username, password) - const server = buildServer(url, token) + const server = buildServer(url) + await assignToken(server, username, password) if (!options.video || validator.isInt('' + options.video) === false) { console.error('You need to specify the video id to remove from your redundancies.\n') diff --git a/server/tools/peertube-upload.ts b/server/tools/peertube-upload.ts index d1c5348d1..c94b05857 100644 --- a/server/tools/peertube-upload.ts +++ b/server/tools/peertube-upload.ts @@ -4,9 +4,8 @@ registerTSPaths() import { program } from 'commander' import { access, constants } from 'fs-extra' import { isAbsolute } from 'path' -import { getAccessToken } from '../../shared/extra-utils' import { uploadVideo } from '../../shared/extra-utils/' -import { buildCommonVideoOptions, buildServer, buildVideoAttributesFromCommander, getServerCredentials } from './cli' +import { assignToken, buildCommonVideoOptions, buildServer, buildVideoAttributesFromCommander, getServerCredentials } from './cli' let command = program .name('upload') @@ -46,8 +45,8 @@ getServerCredentials(command) .catch(err => console.error(err)) async function run (url: string, username: string, password: string) { - const token = await getAccessToken(url, username, password) - const server = buildServer(url, token) + const server = buildServer(url) + await assignToken(server, username, password) await access(options.file, constants.F_OK) @@ -62,7 +61,7 @@ async function run (url: string, username: string, password: string) { }) try { - await uploadVideo(url, token, videoAttributes) + await uploadVideo(url, server.accessToken, videoAttributes) console.log(`Video ${options.videoName} uploaded.`) process.exit(0) } catch (err) { diff --git a/shared/extra-utils/users/login-command.ts b/shared/extra-utils/users/login-command.ts index 97efcb766..8af3531f9 100644 --- a/shared/extra-utils/users/login-command.ts +++ b/shared/extra-utils/users/login-command.ts @@ -1,4 +1,3 @@ -import { PeerTubeRequestError } from '@server/helpers/requests' import { HttpStatusCode } from '@shared/core-utils' import { PeerTubeProblemDocument } from '@shared/models' import { unwrapBody } from '../requests' @@ -34,8 +33,8 @@ export class LoginCommand extends AbstractCommand { })) } - getAccessToken (user?: { username: string, password: string }): Promise - getAccessToken (username: string, password: string): Promise + getAccessToken (arg1?: { username: string, password: string }): Promise + getAccessToken (arg1: string, password: string): Promise async getAccessToken (arg1?: { username: string, password: string } | string, password?: string) { let user: { username: string, password: string } @@ -48,7 +47,7 @@ export class LoginCommand extends AbstractCommand { return body.access_token } catch (err) { - throw new Error('Cannot authenticate. Please check your username/password.') + throw new Error(`Cannot authenticate. Please check your username/password. (${err})`) } } -- cgit v1.2.3 From 7926c5f9b3ffcabb1ffb0dcfa5e48b8e0b88fbc0 Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Tue, 13 Jul 2021 14:23:01 +0200 Subject: Introduce user command --- server/controllers/api/users/index.ts | 4 +- server/tests/api/activitypub/fetch.ts | 3 +- server/tests/api/activitypub/refresher.ts | 5 +- server/tests/api/check-params/abuses.ts | 6 +- server/tests/api/check-params/blocklist.ts | 3 +- server/tests/api/check-params/bulk.ts | 3 +- server/tests/api/check-params/config.ts | 3 +- server/tests/api/check-params/custom-pages.ts | 3 +- server/tests/api/check-params/debug.ts | 3 +- server/tests/api/check-params/follows.ts | 3 +- server/tests/api/check-params/jobs.ts | 3 +- server/tests/api/check-params/live.ts | 20 +- server/tests/api/check-params/logs.ts | 3 +- server/tests/api/check-params/plugins.ts | 3 +- server/tests/api/check-params/redundancy.ts | 3 +- server/tests/api/check-params/upload-quota.ts | 35 +- .../tests/api/check-params/user-subscriptions.ts | 3 +- server/tests/api/check-params/users.ts | 243 ++++++------ server/tests/api/check-params/video-blacklist.ts | 5 +- server/tests/api/check-params/video-captions.ts | 3 +- server/tests/api/check-params/video-channels.ts | 3 +- server/tests/api/check-params/video-comments.ts | 5 +- server/tests/api/check-params/video-imports.ts | 14 +- server/tests/api/check-params/video-playlists.ts | 3 +- server/tests/api/check-params/videos-filter.ts | 16 +- server/tests/api/check-params/videos.ts | 18 +- server/tests/api/live/live-constraints.ts | 8 +- server/tests/api/moderation/abuses.ts | 15 +- .../tests/api/moderation/blocklist-notification.ts | 9 +- server/tests/api/moderation/blocklist.ts | 7 +- server/tests/api/moderation/video-blacklist.ts | 17 +- .../api/notifications/comments-notifications.ts | 14 +- .../api/notifications/moderation-notifications.ts | 11 +- .../tests/api/notifications/notifications-api.ts | 25 +- .../tests/api/notifications/user-notifications.ts | 18 +- .../search/search-activitypub-video-channels.ts | 8 +- server/tests/api/search/search-channels.ts | 4 +- server/tests/api/server/bulk.ts | 7 +- server/tests/api/server/config.ts | 7 +- server/tests/api/server/email.ts | 73 ++-- server/tests/api/server/follow-constraints.ts | 3 +- server/tests/api/server/follows.ts | 5 +- server/tests/api/server/jobs.ts | 2 +- server/tests/api/server/plugins.ts | 18 +- server/tests/api/server/reverse-proxy.ts | 18 +- server/tests/api/server/stats.ts | 3 +- server/tests/api/users/user-subscriptions.ts | 3 +- server/tests/api/users/users-multiple-servers.ts | 45 +-- server/tests/api/users/users-verification.ts | 48 +-- server/tests/api/users/users.ts | 374 ++++++------------- server/tests/api/videos/multiple-servers.ts | 3 +- server/tests/api/videos/resumable-upload.ts | 17 +- server/tests/api/videos/video-change-ownership.ts | 89 ++--- server/tests/api/videos/video-channels.ts | 22 +- server/tests/api/videos/video-comments.ts | 16 +- server/tests/api/videos/video-imports.ts | 9 +- server/tests/api/videos/video-nsfw.ts | 26 +- server/tests/api/videos/video-playlists.ts | 34 +- server/tests/api/videos/video-privacy.ts | 3 +- server/tests/api/videos/videos-filter.ts | 13 +- server/tests/api/videos/videos-history.ts | 12 +- server/tests/api/videos/videos-overview.ts | 12 +- server/tests/cli/peertube.ts | 8 +- server/tests/cli/prune-storage.ts | 3 +- server/tests/cli/reset-password.ts | 4 +- server/tests/cli/update-host.ts | 3 +- server/tests/client.ts | 3 +- server/tests/external-plugins/auth-ldap.ts | 12 +- server/tests/feeds/feeds.ts | 31 +- server/tests/misc-endpoints.ts | 5 +- server/tests/plugins/action-hooks.ts | 41 +- server/tests/plugins/external-auth.ts | 49 +-- server/tests/plugins/filter-hooks.ts | 9 +- server/tests/plugins/id-and-pass-auth.ts | 53 +-- server/tools/cli.ts | 10 +- shared/extra-utils/server/servers.ts | 4 +- shared/extra-utils/users/index.ts | 1 + shared/extra-utils/users/login-command.ts | 12 +- shared/extra-utils/users/notifications.ts | 18 +- shared/extra-utils/users/users-command.ts | 414 +++++++++++++++++++++ shared/extra-utils/users/users.ts | 400 +------------------- shared/extra-utils/videos/channels.ts | 6 +- shared/extra-utils/videos/videos.ts | 4 +- shared/models/users/index.ts | 1 + shared/models/users/user-create-result.model.ts | 7 + 85 files changed, 1009 insertions(+), 1503 deletions(-) create mode 100644 shared/extra-utils/users/users-command.ts create mode 100644 shared/models/users/user-create-result.model.ts diff --git a/server/controllers/api/users/index.ts b/server/controllers/api/users/index.ts index d907b49bf..b86fc94ef 100644 --- a/server/controllers/api/users/index.ts +++ b/server/controllers/api/users/index.ts @@ -4,7 +4,7 @@ import { tokensRouter } from '@server/controllers/api/users/token' import { Hooks } from '@server/lib/plugins/hooks' import { OAuthTokenModel } from '@server/models/oauth/oauth-token' import { MUser, MUserAccountDefault } from '@server/types/models' -import { UserCreate, UserRight, UserRole, UserUpdate } from '../../../../shared' +import { UserCreate, UserCreateResult, UserRight, UserRole, UserUpdate } from '../../../../shared' import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' import { UserAdminFlag } from '../../../../shared/models/users/user-flag.model' import { UserRegister } from '../../../../shared/models/users/user-register.model' @@ -220,7 +220,7 @@ async function createUser (req: express.Request, res: express.Response) { account: { id: account.id } - } + } as UserCreateResult }) } diff --git a/server/tests/api/activitypub/fetch.ts b/server/tests/api/activitypub/fetch.ts index c1af23016..162f3ec83 100644 --- a/server/tests/api/activitypub/fetch.ts +++ b/server/tests/api/activitypub/fetch.ts @@ -4,7 +4,6 @@ import 'mocha' import * as chai from 'chai' import { cleanupTests, - createUser, doubleFollow, flushAndRunMultipleServers, getVideosListSort, @@ -32,7 +31,7 @@ describe('Test ActivityPub fetcher', function () { const user = { username: 'user1', password: 'password' } for (const server of servers) { - await createUser({ url: server.url, accessToken: server.accessToken, username: user.username, password: user.password }) + await server.usersCommand.create({ username: user.username, password: user.password }) } const userAccessToken = await servers[0].loginCommand.getAccessToken(user) diff --git a/server/tests/api/activitypub/refresher.ts b/server/tests/api/activitypub/refresher.ts index af919f2f3..5a37dbc40 100644 --- a/server/tests/api/activitypub/refresher.ts +++ b/server/tests/api/activitypub/refresher.ts @@ -6,7 +6,6 @@ import { cleanupTests, doubleFollow, flushAndRunMultipleServers, - generateUserAccessToken, getVideo, killallServers, reRunServer, @@ -44,10 +43,10 @@ describe('Test AP refresher', function () { } { - const a1 = await generateUserAccessToken(servers[1], 'user1') + const a1 = await servers[1].usersCommand.generateUserAndToken('user1') await uploadVideo(servers[1].url, a1, { name: 'video4' }) - const a2 = await generateUserAccessToken(servers[1], 'user2') + const a2 = await servers[1].usersCommand.generateUserAndToken('user2') await uploadVideo(servers[1].url, a2, { name: 'video5' }) } diff --git a/server/tests/api/check-params/abuses.ts b/server/tests/api/check-params/abuses.ts index 14949d301..4cd10a6fd 100644 --- a/server/tests/api/check-params/abuses.ts +++ b/server/tests/api/check-params/abuses.ts @@ -8,10 +8,8 @@ import { checkBadSortPagination, checkBadStartPagination, cleanupTests, - createUser, doubleFollow, flushAndRunServer, - generateUserAccessToken, getVideoIdFromUUID, makeGetRequest, makePostBodyRequest, @@ -45,10 +43,10 @@ describe('Test abuses API validators', function () { const username = 'user1' const password = 'my super password' - await createUser({ url: server.url, accessToken: server.accessToken, username: username, password: password }) + await server.usersCommand.create({ username: username, password: password }) userToken = await server.loginCommand.getAccessToken({ username, password }) - userToken2 = await generateUserAccessToken(server, 'user_2') + userToken2 = await server.usersCommand.generateUserAndToken('user_2') const res = await uploadVideo(server.url, server.accessToken, {}) server.video = res.body.video diff --git a/server/tests/api/check-params/blocklist.ts b/server/tests/api/check-params/blocklist.ts index 11a79387f..18238bb04 100644 --- a/server/tests/api/check-params/blocklist.ts +++ b/server/tests/api/check-params/blocklist.ts @@ -4,7 +4,6 @@ import 'mocha' import { cleanupTests, - createUser, doubleFollow, flushAndRunMultipleServers, makeDeleteRequest, @@ -34,7 +33,7 @@ describe('Test blocklist API validators', function () { server = servers[0] const user = { username: 'user1', password: 'password' } - await createUser({ url: server.url, accessToken: server.accessToken, username: user.username, password: user.password }) + await server.usersCommand.create({ username: user.username, password: user.password }) userAccessToken = await server.loginCommand.getAccessToken(user) diff --git a/server/tests/api/check-params/bulk.ts b/server/tests/api/check-params/bulk.ts index 85520b3bd..3f80c79a8 100644 --- a/server/tests/api/check-params/bulk.ts +++ b/server/tests/api/check-params/bulk.ts @@ -3,7 +3,6 @@ import 'mocha' import { cleanupTests, - createUser, flushAndRunServer, ServerInfo, setAccessTokensToServers @@ -24,7 +23,7 @@ describe('Test bulk API validators', function () { await setAccessTokensToServers([ server ]) const user = { username: 'user1', password: 'password' } - await createUser({ url: server.url, accessToken: server.accessToken, username: user.username, password: user.password }) + await server.usersCommand.create({ username: user.username, password: user.password }) userAccessToken = await server.loginCommand.getAccessToken(user) }) diff --git a/server/tests/api/check-params/config.ts b/server/tests/api/check-params/config.ts index e93523e4b..c204d9415 100644 --- a/server/tests/api/check-params/config.ts +++ b/server/tests/api/check-params/config.ts @@ -5,7 +5,6 @@ import { omit } from 'lodash' import { HttpStatusCode } from '@shared/core-utils' import { cleanupTests, - createUser, flushAndRunServer, makeDeleteRequest, makeGetRequest, @@ -206,7 +205,7 @@ describe('Test config API validators', function () { username: 'user1', password: 'password' } - await createUser({ url: server.url, accessToken: server.accessToken, username: user.username, password: user.password }) + await server.usersCommand.create({ username: user.username, password: user.password }) userAccessToken = await server.loginCommand.getAccessToken(user) }) diff --git a/server/tests/api/check-params/custom-pages.ts b/server/tests/api/check-params/custom-pages.ts index c1dd258aa..58b0b8600 100644 --- a/server/tests/api/check-params/custom-pages.ts +++ b/server/tests/api/check-params/custom-pages.ts @@ -4,7 +4,6 @@ import 'mocha' import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' import { cleanupTests, - createUser, flushAndRunServer, ServerInfo, setAccessTokensToServers @@ -26,7 +25,7 @@ describe('Test custom pages validators', function () { await setAccessTokensToServers([ server ]) const user = { username: 'user1', password: 'password' } - await createUser({ url: server.url, accessToken: server.accessToken, username: user.username, password: user.password }) + await server.usersCommand.create({ username: user.username, password: user.password }) userAccessToken = await server.loginCommand.getAccessToken(user) }) diff --git a/server/tests/api/check-params/debug.ts b/server/tests/api/check-params/debug.ts index dc033a441..2a7485cf3 100644 --- a/server/tests/api/check-params/debug.ts +++ b/server/tests/api/check-params/debug.ts @@ -4,7 +4,6 @@ import 'mocha' import { cleanupTests, - createUser, flushAndRunServer, ServerInfo, setAccessTokensToServers @@ -30,7 +29,7 @@ describe('Test debug API validators', function () { username: 'user1', password: 'my super password' } - await createUser({ url: server.url, accessToken: server.accessToken, username: user.username, password: user.password }) + await server.usersCommand.create({ username: user.username, password: user.password }) userAccessToken = await server.loginCommand.getAccessToken(user) }) diff --git a/server/tests/api/check-params/follows.ts b/server/tests/api/check-params/follows.ts index 8cf5b130e..24e483448 100644 --- a/server/tests/api/check-params/follows.ts +++ b/server/tests/api/check-params/follows.ts @@ -4,7 +4,6 @@ import 'mocha' import { cleanupTests, - createUser, flushAndRunServer, makeDeleteRequest, makeGetRequest, makePostBodyRequest, @@ -40,7 +39,7 @@ describe('Test server follows API validators', function () { password: 'password' } - await createUser({ url: server.url, accessToken: server.accessToken, username: user.username, password: user.password }) + await server.usersCommand.create({ username: user.username, password: user.password }) userAccessToken = await server.loginCommand.getAccessToken(user) }) diff --git a/server/tests/api/check-params/jobs.ts b/server/tests/api/check-params/jobs.ts index cbe6a28b8..29439bebf 100644 --- a/server/tests/api/check-params/jobs.ts +++ b/server/tests/api/check-params/jobs.ts @@ -4,7 +4,6 @@ import 'mocha' import { cleanupTests, - createUser, flushAndRunServer, ServerInfo, setAccessTokensToServers @@ -35,7 +34,7 @@ describe('Test jobs API validators', function () { username: 'user1', password: 'my super password' } - await createUser({ url: server.url, accessToken: server.accessToken, username: user.username, password: user.password }) + await server.usersCommand.create({ username: user.username, password: user.password }) userAccessToken = await server.loginCommand.getAccessToken(user) }) diff --git a/server/tests/api/check-params/live.ts b/server/tests/api/check-params/live.ts index 045f3a1b1..78863fd50 100644 --- a/server/tests/api/check-params/live.ts +++ b/server/tests/api/check-params/live.ts @@ -2,14 +2,11 @@ import 'mocha' import { omit } from 'lodash' -import { VideoCreateResult, VideoPrivacy } from '@shared/models' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '@shared/core-utils' import { buildAbsoluteFixturePath, cleanupTests, - createUser, flushAndRunServer, - getMyUserInformation, LiveCommand, makePostBodyRequest, makeUploadRequest, @@ -18,7 +15,8 @@ import { setAccessTokensToServers, stopFfmpeg, uploadVideoAndGetId -} from '../../../../shared/extra-utils' +} from '@shared/extra-utils' +import { VideoCreateResult, VideoPrivacy } from '@shared/models' describe('Test video lives API validator', function () { const path = '/api/v1/videos/live' @@ -51,12 +49,12 @@ describe('Test video lives API validator', function () { const username = 'user1' const password = 'my super password' - await createUser({ url: server.url, accessToken: server.accessToken, username: username, password: password }) + await server.usersCommand.create({ username: username, password: password }) userAccessToken = await server.loginCommand.getAccessToken({ username, password }) { - const res = await getMyUserInformation(server.url, server.accessToken) - channelId = res.body.videoChannels[0].id + const { videoChannels } = await server.usersCommand.getMyInfo() + channelId = videoChannels[0].id } { @@ -147,11 +145,11 @@ describe('Test video lives API validator', function () { username: 'fake', password: 'fake_password' } - await createUser({ url: server.url, accessToken: server.accessToken, username: user.username, password: user.password }) + await server.usersCommand.create({ username: user.username, password: user.password }) const accessTokenUser = await server.loginCommand.getAccessToken(user) - const res = await getMyUserInformation(server.url, accessTokenUser) - const customChannelId = res.body.videoChannels[0].id + const { videoChannels } = await server.usersCommand.getMyInfo({ token: accessTokenUser }) + const customChannelId = videoChannels[0].id const fields = { ...baseCorrectParams, channelId: customChannelId } diff --git a/server/tests/api/check-params/logs.ts b/server/tests/api/check-params/logs.ts index 83ecfec93..69eaad69f 100644 --- a/server/tests/api/check-params/logs.ts +++ b/server/tests/api/check-params/logs.ts @@ -4,7 +4,6 @@ import 'mocha' import { cleanupTests, - createUser, flushAndRunServer, ServerInfo, setAccessTokensToServers @@ -30,7 +29,7 @@ describe('Test logs API validators', function () { username: 'user1', password: 'my super password' } - await createUser({ url: server.url, accessToken: server.accessToken, username: user.username, password: user.password }) + await server.usersCommand.create({ username: user.username, password: user.password }) userAccessToken = await server.loginCommand.getAccessToken(user) }) diff --git a/server/tests/api/check-params/plugins.ts b/server/tests/api/check-params/plugins.ts index 130cf6869..08fb2397f 100644 --- a/server/tests/api/check-params/plugins.ts +++ b/server/tests/api/check-params/plugins.ts @@ -7,7 +7,6 @@ import { checkBadSortPagination, checkBadStartPagination, cleanupTests, - createUser, flushAndRunServer, makeGetRequest, makePostBodyRequest, @@ -43,7 +42,7 @@ describe('Test server plugins API validators', function () { password: 'password' } - await createUser({ url: server.url, accessToken: server.accessToken, username: user.username, password: user.password }) + await server.usersCommand.create({ username: user.username, password: user.password }) userAccessToken = await server.loginCommand.getAccessToken(user) { diff --git a/server/tests/api/check-params/redundancy.ts b/server/tests/api/check-params/redundancy.ts index 2e10e378a..d93022c32 100644 --- a/server/tests/api/check-params/redundancy.ts +++ b/server/tests/api/check-params/redundancy.ts @@ -8,7 +8,6 @@ import { checkBadSortPagination, checkBadStartPagination, cleanupTests, - createUser, doubleFollow, flushAndRunMultipleServers, getVideo, @@ -43,7 +42,7 @@ describe('Test server redundancy API validators', function () { password: 'password' } - await createUser({ url: servers[0].url, accessToken: servers[0].accessToken, username: user.username, password: user.password }) + await servers[0].usersCommand.create({ username: user.username, password: user.password }) userAccessToken = await servers[0].loginCommand.getAccessToken(user) videoIdLocal = (await uploadVideoAndGetId({ server: servers[0], videoName: 'video' })).id diff --git a/server/tests/api/check-params/upload-quota.ts b/server/tests/api/check-params/upload-quota.ts index 3dc6cf2b4..d94dec624 100644 --- a/server/tests/api/check-params/upload-quota.ts +++ b/server/tests/api/check-params/upload-quota.ts @@ -3,17 +3,14 @@ import 'mocha' import { expect } from 'chai' import { HttpStatusCode, randomInt } from '@shared/core-utils' -import { MyUser, VideoImportState, VideoPrivacy } from '@shared/models' +import { VideoImportState, VideoPrivacy } from '@shared/models' import { cleanupTests, flushAndRunServer, - getMyUserInformation, ImportsCommand, - registerUser, ServerInfo, setAccessTokensToServers, setDefaultVideoChannel, - updateUser, uploadVideo, waitJobs } from '../../../../shared/extra-utils' @@ -31,15 +28,10 @@ describe('Test upload quota', function () { await setAccessTokensToServers([ server ]) await setDefaultVideoChannel([ server ]) - const res = await getMyUserInformation(server.url, server.accessToken) - rootId = (res.body as MyUser).id + const user = await server.usersCommand.getMyInfo() + rootId = user.id - await updateUser({ - url: server.url, - userId: rootId, - accessToken: server.accessToken, - videoQuota: 42 - }) + await server.usersCommand.update({ userId: rootId, videoQuota: 42 }) }) describe('When having a video quota', function () { @@ -48,7 +40,7 @@ describe('Test upload quota', function () { this.timeout(30000) const user = { username: 'registered' + randomInt(1, 1500), password: 'password' } - await registerUser(server.url, user.username, user.password) + await server.usersCommand.register(user) const userAccessToken = await server.loginCommand.getAccessToken(user) const videoAttributes = { fixture: 'video_short2.webm' } @@ -63,7 +55,7 @@ describe('Test upload quota', function () { this.timeout(30000) const user = { username: 'registered' + randomInt(1, 1500), password: 'password' } - await registerUser(server.url, user.username, user.password) + await server.usersCommand.register(user) const userAccessToken = await server.loginCommand.getAccessToken(user) const videoAttributes = { fixture: 'video_short2.webm' } @@ -103,12 +95,7 @@ describe('Test upload quota', function () { describe('When having a daily video quota', function () { it('Should fail with a user having too many videos daily', async function () { - await updateUser({ - url: server.url, - userId: rootId, - accessToken: server.accessToken, - videoQuotaDaily: 42 - }) + await server.usersCommand.update({ userId: rootId, videoQuotaDaily: 42 }) await uploadVideo(server.url, server.accessToken, {}, HttpStatusCode.PAYLOAD_TOO_LARGE_413, 'legacy') await uploadVideo(server.url, server.accessToken, {}, HttpStatusCode.PAYLOAD_TOO_LARGE_413, 'resumable') @@ -117,10 +104,8 @@ describe('Test upload quota', function () { describe('When having an absolute and daily video quota', function () { it('Should fail if exceeding total quota', async function () { - await updateUser({ - url: server.url, + await server.usersCommand.update({ userId: rootId, - accessToken: server.accessToken, videoQuota: 42, videoQuotaDaily: 1024 * 1024 * 1024 }) @@ -130,10 +115,8 @@ describe('Test upload quota', function () { }) it('Should fail if exceeding daily quota', async function () { - await updateUser({ - url: server.url, + await server.usersCommand.update({ userId: rootId, - accessToken: server.accessToken, videoQuota: 1024 * 1024 * 1024, videoQuotaDaily: 42 }) diff --git a/server/tests/api/check-params/user-subscriptions.ts b/server/tests/api/check-params/user-subscriptions.ts index 64e2703b9..8ce201d61 100644 --- a/server/tests/api/check-params/user-subscriptions.ts +++ b/server/tests/api/check-params/user-subscriptions.ts @@ -4,7 +4,6 @@ import 'mocha' import { cleanupTests, - createUser, flushAndRunServer, makeDeleteRequest, makeGetRequest, @@ -39,7 +38,7 @@ describe('Test user subscriptions API validators', function () { username: 'user1', password: 'my super password' } - await createUser({ url: server.url, accessToken: server.accessToken, username: user.username, password: user.password }) + await server.usersCommand.create({ username: user.username, password: user.password }) userAccessToken = await server.loginCommand.getAccessToken(user) }) diff --git a/server/tests/api/check-params/users.ts b/server/tests/api/check-params/users.ts index 54baeebe1..801131918 100644 --- a/server/tests/api/check-params/users.ts +++ b/server/tests/api/check-params/users.ts @@ -2,32 +2,22 @@ import 'mocha' import { omit } from 'lodash' -import { User, UserRole, VideoCreateResult } from '../../../../shared' +import { UserRole, VideoCreateResult } from '../../../../shared' import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' import { - blockUser, buildAbsoluteFixturePath, cleanupTests, - createUser, - deleteMe, flushAndRunServer, - getMyUserInformation, - getMyUserVideoRating, - getUserScopedTokens, - getUsersList, killallServers, makeGetRequest, makePostBodyRequest, makePutBodyRequest, makeUploadRequest, - registerUser, - removeUser, - renewUserScopedTokens, reRunServer, ServerInfo, setAccessTokensToServers, - unblockUser, - uploadVideo + uploadVideo, + UsersCommand } from '../../../../shared/extra-utils' import { MockSmtpServer } from '../../../../shared/extra-utils/mock-servers/mock-email' import { @@ -45,8 +35,8 @@ describe('Test users API validators', function () { let video: VideoCreateResult let server: ServerInfo let serverWithRegistrationDisabled: ServerInfo - let userAccessToken = '' - let moderatorAccessToken = '' + let userToken = '' + let moderatorToken = '' let emailPort: number let overrideConfig: Object @@ -73,52 +63,20 @@ describe('Test users API validators', function () { } { - const user = { - username: 'user1', - password: 'my super password' - } - - const videoQuota = 42000000 - await createUser({ - url: server.url, - accessToken: server.accessToken, - username: user.username, - password: user.password, - videoQuota: videoQuota - }) - userAccessToken = await server.loginCommand.getAccessToken(user) + const user = { username: 'user1' } + await server.usersCommand.create({ ...user }) + userToken = await server.loginCommand.getAccessToken(user) } { - const moderator = { - username: 'moderator1', - password: 'super password' - } - - await createUser({ - url: server.url, - accessToken: server.accessToken, - username: moderator.username, - password: moderator.password, - role: UserRole.MODERATOR - }) - - moderatorAccessToken = await server.loginCommand.getAccessToken(moderator) + const moderator = { username: 'moderator1' } + await server.usersCommand.create({ ...moderator, role: UserRole.MODERATOR }) + moderatorToken = await server.loginCommand.getAccessToken(moderator) } { - const moderator = { - username: 'moderator2', - password: 'super password' - } - - await createUser({ - url: server.url, - accessToken: server.accessToken, - username: moderator.username, - password: moderator.password, - role: UserRole.MODERATOR - }) + const moderator = { username: 'moderator2' } + await server.usersCommand.create({ ...moderator, role: UserRole.MODERATOR }) } { @@ -127,12 +85,10 @@ describe('Test users API validators', function () { } { - const res = await getUsersList(server.url, server.accessToken) - const users: User[] = res.body.data - - userId = users.find(u => u.username === 'user1').id - rootId = users.find(u => u.username === 'root').id - moderatorId = users.find(u => u.username === 'moderator2').id + const { data } = await server.usersCommand.list() + userId = data.find(u => u.username === 'user1').id + rootId = data.find(u => u.username === 'root').id + moderatorId = data.find(u => u.username === 'moderator2').id } }) @@ -161,7 +117,7 @@ describe('Test users API validators', function () { await makeGetRequest({ url: server.url, path, - token: userAccessToken, + token: userToken, statusCodeExpected: HttpStatusCode.FORBIDDEN_403 }) }) @@ -359,7 +315,7 @@ describe('Test users API validators', function () { await makePostBodyRequest({ url: server.url, path, - token: moderatorAccessToken, + token: moderatorToken, fields, statusCodeExpected: HttpStatusCode.FORBIDDEN_403 }) @@ -372,7 +328,7 @@ describe('Test users API validators', function () { await makePostBodyRequest({ url: server.url, path, - token: moderatorAccessToken, + token: moderatorToken, fields, statusCodeExpected: HttpStatusCode.OK_200 }) @@ -389,11 +345,8 @@ describe('Test users API validators', function () { }) it('Should fail with a non admin user', async function () { - const user = { - username: 'user1', - password: 'my super password' - } - userAccessToken = await server.loginCommand.getAccessToken(user) + const user = { username: 'user1' } + userToken = await server.loginCommand.getAccessToken(user) const fields = { username: 'user3', @@ -401,11 +354,12 @@ describe('Test users API validators', function () { password: 'my super password', videoQuota: 42000000 } - await makePostBodyRequest({ url: server.url, path, token: userAccessToken, fields, statusCodeExpected: HttpStatusCode.FORBIDDEN_403 }) + await makePostBodyRequest({ url: server.url, path, token: userToken, fields, statusCodeExpected: HttpStatusCode.FORBIDDEN_403 }) }) }) describe('When updating my account', function () { + it('Should fail with an invalid email attribute', async function () { const fields = { email: 'blabla' @@ -416,29 +370,29 @@ describe('Test users API validators', function () { it('Should fail with a too small password', async function () { const fields = { - currentPassword: 'my super password', + currentPassword: 'password', password: 'bla' } - await makePutBodyRequest({ url: server.url, path: path + 'me', token: userAccessToken, fields }) + await makePutBodyRequest({ url: server.url, path: path + 'me', token: userToken, fields }) }) it('Should fail with a too long password', async function () { const fields = { - currentPassword: 'my super password', + currentPassword: 'password', password: 'super'.repeat(61) } - await makePutBodyRequest({ url: server.url, path: path + 'me', token: userAccessToken, fields }) + await makePutBodyRequest({ url: server.url, path: path + 'me', token: userToken, fields }) }) it('Should fail without the current password', async function () { const fields = { - currentPassword: 'my super password', + currentPassword: 'password', password: 'super'.repeat(61) } - await makePutBodyRequest({ url: server.url, path: path + 'me', token: userAccessToken, fields }) + await makePutBodyRequest({ url: server.url, path: path + 'me', token: userToken, fields }) }) it('Should fail with an invalid current password', async function () { @@ -450,7 +404,7 @@ describe('Test users API validators', function () { await makePutBodyRequest({ url: server.url, path: path + 'me', - token: userAccessToken, + token: userToken, fields, statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) @@ -461,7 +415,7 @@ describe('Test users API validators', function () { nsfwPolicy: 'hello' } - await makePutBodyRequest({ url: server.url, path: path + 'me', token: userAccessToken, fields }) + await makePutBodyRequest({ url: server.url, path: path + 'me', token: userToken, fields }) }) it('Should fail with an invalid autoPlayVideo attribute', async function () { @@ -469,7 +423,7 @@ describe('Test users API validators', function () { autoPlayVideo: -1 } - await makePutBodyRequest({ url: server.url, path: path + 'me', token: userAccessToken, fields }) + await makePutBodyRequest({ url: server.url, path: path + 'me', token: userToken, fields }) }) it('Should fail with an invalid autoPlayNextVideo attribute', async function () { @@ -477,7 +431,7 @@ describe('Test users API validators', function () { autoPlayNextVideo: -1 } - await makePutBodyRequest({ url: server.url, path: path + 'me', token: userAccessToken, fields }) + await makePutBodyRequest({ url: server.url, path: path + 'me', token: userToken, fields }) }) it('Should fail with an invalid videosHistoryEnabled attribute', async function () { @@ -485,12 +439,12 @@ describe('Test users API validators', function () { videosHistoryEnabled: -1 } - await makePutBodyRequest({ url: server.url, path: path + 'me', token: userAccessToken, fields }) + await makePutBodyRequest({ url: server.url, path: path + 'me', token: userToken, fields }) }) it('Should fail with an non authenticated user', async function () { const fields = { - currentPassword: 'my super password', + currentPassword: 'password', password: 'my super password' } @@ -508,7 +462,7 @@ describe('Test users API validators', function () { description: 'super'.repeat(201) } - await makePutBodyRequest({ url: server.url, path: path + 'me', token: userAccessToken, fields }) + await makePutBodyRequest({ url: server.url, path: path + 'me', token: userToken, fields }) }) it('Should fail with an invalid videoLanguages attribute', async function () { @@ -517,7 +471,7 @@ describe('Test users API validators', function () { videoLanguages: 'toto' } - await makePutBodyRequest({ url: server.url, path: path + 'me', token: userAccessToken, fields }) + await makePutBodyRequest({ url: server.url, path: path + 'me', token: userToken, fields }) } { @@ -530,18 +484,18 @@ describe('Test users API validators', function () { videoLanguages: languages } - await makePutBodyRequest({ url: server.url, path: path + 'me', token: userAccessToken, fields }) + await makePutBodyRequest({ url: server.url, path: path + 'me', token: userToken, fields }) } }) it('Should fail with an invalid theme', async function () { const fields = { theme: 'invalid' } - await makePutBodyRequest({ url: server.url, path: path + 'me', token: userAccessToken, fields }) + await makePutBodyRequest({ url: server.url, path: path + 'me', token: userToken, fields }) }) it('Should fail with an unknown theme', async function () { const fields = { theme: 'peertube-theme-unknown' } - await makePutBodyRequest({ url: server.url, path: path + 'me', token: userAccessToken, fields }) + await makePutBodyRequest({ url: server.url, path: path + 'me', token: userToken, fields }) }) it('Should fail with an invalid noInstanceConfigWarningModal attribute', async function () { @@ -549,7 +503,7 @@ describe('Test users API validators', function () { noInstanceConfigWarningModal: -1 } - await makePutBodyRequest({ url: server.url, path: path + 'me', token: userAccessToken, fields }) + await makePutBodyRequest({ url: server.url, path: path + 'me', token: userToken, fields }) }) it('Should fail with an invalid noWelcomeModal attribute', async function () { @@ -557,12 +511,12 @@ describe('Test users API validators', function () { noWelcomeModal: -1 } - await makePutBodyRequest({ url: server.url, path: path + 'me', token: userAccessToken, fields }) + await makePutBodyRequest({ url: server.url, path: path + 'me', token: userToken, fields }) }) it('Should succeed to change password with the correct params', async function () { const fields = { - currentPassword: 'my super password', + currentPassword: 'password', password: 'my super password', nsfwPolicy: 'blur', autoPlayVideo: false, @@ -575,7 +529,7 @@ describe('Test users API validators', function () { await makePutBodyRequest({ url: server.url, path: path + 'me', - token: userAccessToken, + token: userToken, fields, statusCodeExpected: HttpStatusCode.NO_CONTENT_204 }) @@ -590,7 +544,7 @@ describe('Test users API validators', function () { await makePutBodyRequest({ url: server.url, path: path + 'me', - token: userAccessToken, + token: userToken, fields, statusCodeExpected: HttpStatusCode.NO_CONTENT_204 }) @@ -647,28 +601,28 @@ describe('Test users API validators', function () { describe('When managing my scoped tokens', function () { it('Should fail to get my scoped tokens with an non authenticated user', async function () { - await getUserScopedTokens(server.url, null, HttpStatusCode.UNAUTHORIZED_401) + await server.usersCommand.getMyScopedTokens({ token: null, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should fail to get my scoped tokens with a bad token', async function () { - await getUserScopedTokens(server.url, 'bad', HttpStatusCode.UNAUTHORIZED_401) + await server.usersCommand.getMyScopedTokens({ token: 'bad', expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should succeed to get my scoped tokens', async function () { - await getUserScopedTokens(server.url, server.accessToken) + await server.usersCommand.getMyScopedTokens() }) it('Should fail to renew my scoped tokens with an non authenticated user', async function () { - await renewUserScopedTokens(server.url, null, HttpStatusCode.UNAUTHORIZED_401) + await server.usersCommand.renewMyScopedTokens({ token: null, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should fail to renew my scoped tokens with a bad token', async function () { - await renewUserScopedTokens(server.url, 'bad', HttpStatusCode.UNAUTHORIZED_401) + await server.usersCommand.renewMyScopedTokens({ token: 'bad', expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should succeed to renew my scoped tokens', async function () { - await renewUserScopedTokens(server.url, server.accessToken) + await server.usersCommand.renewMyScopedTokens() }) }) @@ -684,7 +638,7 @@ describe('Test users API validators', function () { }) it('Should fail with a non admin user', async function () { - await makeGetRequest({ url: server.url, path, token: userAccessToken, statusCodeExpected: HttpStatusCode.FORBIDDEN_403 }) + await makeGetRequest({ url: server.url, path, token: userToken, statusCodeExpected: HttpStatusCode.FORBIDDEN_403 }) }) it('Should succeed with the correct params', async function () { @@ -728,7 +682,7 @@ describe('Test users API validators', function () { it('Should fail with a too small password', async function () { const fields = { - currentPassword: 'my super password', + currentPassword: 'password', password: 'bla' } @@ -737,7 +691,7 @@ describe('Test users API validators', function () { it('Should fail with a too long password', async function () { const fields = { - currentPassword: 'my super password', + currentPassword: 'password', password: 'super'.repeat(61) } @@ -780,7 +734,7 @@ describe('Test users API validators', function () { await makePutBodyRequest({ url: server.url, path: path + moderatorId, - token: moderatorAccessToken, + token: moderatorToken, fields, statusCodeExpected: HttpStatusCode.FORBIDDEN_403 }) @@ -794,7 +748,7 @@ describe('Test users API validators', function () { await makePutBodyRequest({ url: server.url, path: path + userId, - token: moderatorAccessToken, + token: moderatorToken, fields, statusCodeExpected: HttpStatusCode.NO_CONTENT_204 }) @@ -820,31 +774,37 @@ describe('Test users API validators', function () { describe('When getting my information', function () { it('Should fail with a non authenticated user', async function () { - await getMyUserInformation(server.url, 'fake_token', HttpStatusCode.UNAUTHORIZED_401) + await server.usersCommand.getMyInfo({ token: 'fake_token', expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should success with the correct parameters', async function () { - await getMyUserInformation(server.url, userAccessToken) + await server.usersCommand.getMyInfo({ token: userToken }) }) }) describe('When getting my video rating', function () { + let command: UsersCommand + + before(function () { + command = server.usersCommand + }) + it('Should fail with a non authenticated user', async function () { - await getMyUserVideoRating(server.url, 'fake_token', video.id, HttpStatusCode.UNAUTHORIZED_401) + await command.getMyRating({ token: 'fake_token', videoId: video.id, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should fail with an incorrect video uuid', async function () { - await getMyUserVideoRating(server.url, server.accessToken, 'blabla', HttpStatusCode.BAD_REQUEST_400) + await command.getMyRating({ videoId: 'blabla', expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) it('Should fail with an unknown video', async function () { - await getMyUserVideoRating(server.url, server.accessToken, '4da6fde3-88f7-4d16-b119-108df5630b06', HttpStatusCode.NOT_FOUND_404) + await command.getMyRating({ videoId: '4da6fde3-88f7-4d16-b119-108df5630b06', expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) it('Should succeed with the correct parameters', async function () { - await getMyUserVideoRating(server.url, server.accessToken, video.id) - await getMyUserVideoRating(server.url, server.accessToken, video.uuid) - await getMyUserVideoRating(server.url, server.accessToken, video.shortUUID) + await command.getMyRating({ videoId: video.id }) + await command.getMyRating({ videoId: video.uuid }) + await command.getMyRating({ videoId: video.shortUUID }) }) }) @@ -852,15 +812,15 @@ describe('Test users API validators', function () { const path = '/api/v1/accounts/user1/ratings' it('Should fail with a bad start pagination', async function () { - await checkBadStartPagination(server.url, path, userAccessToken) + await checkBadStartPagination(server.url, path, userToken) }) it('Should fail with a bad count pagination', async function () { - await checkBadCountPagination(server.url, path, userAccessToken) + await checkBadCountPagination(server.url, path, userToken) }) it('Should fail with an incorrect sort', async function () { - await checkBadSortPagination(server.url, path, userAccessToken) + await checkBadSortPagination(server.url, path, userToken) }) it('Should fail with a unauthenticated user', async function () { @@ -875,57 +835,70 @@ describe('Test users API validators', function () { await makeGetRequest({ url: server.url, path, - token: userAccessToken, + token: userToken, query: { rating: 'toto ' }, statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) }) it('Should succeed with the correct params', async function () { - await makeGetRequest({ url: server.url, path, token: userAccessToken, statusCodeExpected: HttpStatusCode.OK_200 }) + await makeGetRequest({ url: server.url, path, token: userToken, statusCodeExpected: HttpStatusCode.OK_200 }) }) }) describe('When blocking/unblocking/removing user', function () { + it('Should fail with an incorrect id', async function () { - await removeUser(server.url, 'blabla', server.accessToken, HttpStatusCode.BAD_REQUEST_400) - await blockUser(server.url, 'blabla', server.accessToken, HttpStatusCode.BAD_REQUEST_400) - await unblockUser(server.url, 'blabla', server.accessToken, HttpStatusCode.BAD_REQUEST_400) + const options = { userId: 'blabla' as any, expectedStatus: HttpStatusCode.BAD_REQUEST_400 } + + await server.usersCommand.remove(options) + await server.usersCommand.banUser({ userId: 'blabla' as any, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) + await server.usersCommand.unbanUser({ userId: 'blabla' as any, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) it('Should fail with the root user', async function () { - await removeUser(server.url, rootId, server.accessToken, HttpStatusCode.BAD_REQUEST_400) - await blockUser(server.url, rootId, server.accessToken, HttpStatusCode.BAD_REQUEST_400) - await unblockUser(server.url, rootId, server.accessToken, HttpStatusCode.BAD_REQUEST_400) + const options = { userId: rootId, expectedStatus: HttpStatusCode.BAD_REQUEST_400 } + + await server.usersCommand.remove(options) + await server.usersCommand.banUser(options) + await server.usersCommand.unbanUser(options) }) it('Should return 404 with a non existing id', async function () { - await removeUser(server.url, 4545454, server.accessToken, HttpStatusCode.NOT_FOUND_404) - await blockUser(server.url, 4545454, server.accessToken, HttpStatusCode.NOT_FOUND_404) - await unblockUser(server.url, 4545454, server.accessToken, HttpStatusCode.NOT_FOUND_404) + const options = { userId: 4545454, expectedStatus: HttpStatusCode.NOT_FOUND_404 } + + await server.usersCommand.remove(options) + await server.usersCommand.banUser(options) + await server.usersCommand.unbanUser(options) }) it('Should fail with a non admin user', async function () { - await removeUser(server.url, userId, userAccessToken, HttpStatusCode.FORBIDDEN_403) - await blockUser(server.url, userId, userAccessToken, HttpStatusCode.FORBIDDEN_403) - await unblockUser(server.url, userId, userAccessToken, HttpStatusCode.FORBIDDEN_403) + const options = { userId, token: userToken, expectedStatus: HttpStatusCode.FORBIDDEN_403 } + + await server.usersCommand.remove(options) + await server.usersCommand.banUser(options) + await server.usersCommand.unbanUser(options) }) it('Should fail on a moderator with a moderator', async function () { - await removeUser(server.url, moderatorId, moderatorAccessToken, HttpStatusCode.FORBIDDEN_403) - await blockUser(server.url, moderatorId, moderatorAccessToken, HttpStatusCode.FORBIDDEN_403) - await unblockUser(server.url, moderatorId, moderatorAccessToken, HttpStatusCode.FORBIDDEN_403) + const options = { userId: moderatorId, token: moderatorToken, expectedStatus: HttpStatusCode.FORBIDDEN_403 } + + await server.usersCommand.remove(options) + await server.usersCommand.banUser(options) + await server.usersCommand.unbanUser(options) }) it('Should succeed on a user with a moderator', async function () { - await blockUser(server.url, userId, moderatorAccessToken) - await unblockUser(server.url, userId, moderatorAccessToken) + const options = { userId, token: moderatorToken } + + await server.usersCommand.banUser(options) + await server.usersCommand.unbanUser(options) }) }) describe('When deleting our account', function () { it('Should fail with with the root account', async function () { - await deleteMe(server.url, server.accessToken, HttpStatusCode.BAD_REQUEST_400) + await server.usersCommand.deleteMe({ expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) }) @@ -1087,7 +1060,7 @@ describe('Test users API validators', function () { describe('When registering multiple users on a server with users limit', function () { it('Should fail when after 3 registrations', async function () { - await registerUser(server.url, 'user42', 'super password', HttpStatusCode.FORBIDDEN_403) + await server.usersCommand.register({ username: 'user42', expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) }) diff --git a/server/tests/api/check-params/video-blacklist.ts b/server/tests/api/check-params/video-blacklist.ts index c33bc196d..5097f8069 100644 --- a/server/tests/api/check-params/video-blacklist.ts +++ b/server/tests/api/check-params/video-blacklist.ts @@ -9,7 +9,6 @@ import { checkBadSortPagination, checkBadStartPagination, cleanupTests, - createUser, doubleFollow, flushAndRunMultipleServers, getVideo, @@ -44,14 +43,14 @@ describe('Test video blacklist API validators', function () { { const username = 'user1' const password = 'my super password' - await createUser({ url: servers[0].url, accessToken: servers[0].accessToken, username: username, password: password }) + await servers[0].usersCommand.create({ username: username, password: password }) userAccessToken1 = await servers[0].loginCommand.getAccessToken({ username, password }) } { const username = 'user2' const password = 'my super password' - await createUser({ url: servers[0].url, accessToken: servers[0].accessToken, username: username, password: password }) + await servers[0].usersCommand.create({ username: username, password: password }) userAccessToken2 = await servers[0].loginCommand.getAccessToken({ username, password }) } diff --git a/server/tests/api/check-params/video-captions.ts b/server/tests/api/check-params/video-captions.ts index f2fd61b91..631ef4dac 100644 --- a/server/tests/api/check-params/video-captions.ts +++ b/server/tests/api/check-params/video-captions.ts @@ -5,7 +5,6 @@ import { HttpStatusCode } from '@shared/core-utils' import { buildAbsoluteFixturePath, cleanupTests, - createUser, flushAndRunServer, makeDeleteRequest, makeGetRequest, @@ -42,7 +41,7 @@ describe('Test video captions API validator', function () { username: 'user1', password: 'my super password' } - await createUser({ url: server.url, accessToken: server.accessToken, username: user.username, password: user.password }) + await server.usersCommand.create({ username: user.username, password: user.password }) userAccessToken = await server.loginCommand.getAccessToken(user) } }) diff --git a/server/tests/api/check-params/video-channels.ts b/server/tests/api/check-params/video-channels.ts index 5361f6917..2b4c17ea1 100644 --- a/server/tests/api/check-params/video-channels.ts +++ b/server/tests/api/check-params/video-channels.ts @@ -11,7 +11,6 @@ import { checkBadSortPagination, checkBadStartPagination, cleanupTests, - createUser, flushAndRunServer, makeGetRequest, makePostBodyRequest, @@ -45,7 +44,7 @@ describe('Test video channels API validator', function () { } { - await createUser({ url: server.url, accessToken: server.accessToken, username: user.username, password: user.password }) + await server.usersCommand.create({ username: user.username, password: user.password }) accessTokenUser = await server.loginCommand.getAccessToken(user) } diff --git a/server/tests/api/check-params/video-comments.ts b/server/tests/api/check-params/video-comments.ts index c21aebaae..b7656a176 100644 --- a/server/tests/api/check-params/video-comments.ts +++ b/server/tests/api/check-params/video-comments.ts @@ -8,7 +8,6 @@ import { checkBadSortPagination, checkBadStartPagination, cleanupTests, - createUser, flushAndRunServer, makeDeleteRequest, makeGetRequest, @@ -53,13 +52,13 @@ describe('Test video comments API validator', function () { { const user = { username: 'user1', password: 'my super password' } - await createUser({ url: server.url, accessToken: server.accessToken, username: user.username, password: user.password }) + await server.usersCommand.create({ username: user.username, password: user.password }) userAccessToken = await server.loginCommand.getAccessToken(user) } { const user = { username: 'user2', password: 'my super password' } - await createUser({ url: server.url, accessToken: server.accessToken, username: user.username, password: user.password }) + await server.usersCommand.create({ username: user.username, password: user.password }) userAccessToken2 = await server.loginCommand.getAccessToken(user) } }) diff --git a/server/tests/api/check-params/video-imports.ts b/server/tests/api/check-params/video-imports.ts index 51260affa..d09e473de 100644 --- a/server/tests/api/check-params/video-imports.ts +++ b/server/tests/api/check-params/video-imports.ts @@ -9,9 +9,7 @@ import { checkBadSortPagination, checkBadStartPagination, cleanupTests, - createUser, flushAndRunServer, - getMyUserInformation, ImportsCommand, makeGetRequest, makePostBodyRequest, @@ -38,12 +36,12 @@ describe('Test video imports API validator', function () { const username = 'user1' const password = 'my super password' - await createUser({ url: server.url, accessToken: server.accessToken, username: username, password: password }) + await server.usersCommand.create({ username: username, password: password }) userAccessToken = await server.loginCommand.getAccessToken({ username, password }) { - const res = await getMyUserInformation(server.url, server.accessToken) - channelId = res.body.videoChannels[0].id + const { videoChannels } = await server.usersCommand.getMyInfo() + channelId = videoChannels[0].id } }) @@ -164,11 +162,11 @@ describe('Test video imports API validator', function () { username: 'fake', password: 'fake_password' } - await createUser({ url: server.url, accessToken: server.accessToken, username: user.username, password: user.password }) + await server.usersCommand.create({ username: user.username, password: user.password }) const accessTokenUser = await server.loginCommand.getAccessToken(user) - const res = await getMyUserInformation(server.url, accessTokenUser) - const customChannelId = res.body.videoChannels[0].id + const { videoChannels } = await server.usersCommand.getMyInfo({ token: accessTokenUser }) + const customChannelId = videoChannels[0].id const fields = { ...baseCorrectParams, channelId: customChannelId } diff --git a/server/tests/api/check-params/video-playlists.ts b/server/tests/api/check-params/video-playlists.ts index 3799e73b6..46c09bb11 100644 --- a/server/tests/api/check-params/video-playlists.ts +++ b/server/tests/api/check-params/video-playlists.ts @@ -17,7 +17,6 @@ import { checkBadStartPagination, cleanupTests, flushAndRunServer, - generateUserAccessToken, makeGetRequest, PlaylistsCommand, ServerInfo, @@ -49,7 +48,7 @@ describe('Test video playlists API validator', function () { await setAccessTokensToServers([ server ]) await setDefaultVideoChannel([ server ]) - userAccessToken = await generateUserAccessToken(server, 'user1') + userAccessToken = await server.usersCommand.generateUserAndToken('user1') videoId = (await uploadVideoAndGetId({ server, videoName: 'video 1' })).id command = server.playlistsCommand diff --git a/server/tests/api/check-params/videos-filter.ts b/server/tests/api/check-params/videos-filter.ts index 095b94656..d7bf081d4 100644 --- a/server/tests/api/check-params/videos-filter.ts +++ b/server/tests/api/check-params/videos-filter.ts @@ -3,7 +3,6 @@ import 'mocha' import { cleanupTests, - createUser, flushAndRunServer, makeGetRequest, ServerInfo, @@ -50,21 +49,12 @@ describe('Test video filters validators', function () { await setDefaultVideoChannel([ server ]) const user = { username: 'user1', password: 'my super password' } - await createUser({ url: server.url, accessToken: server.accessToken, username: user.username, password: user.password }) + await server.usersCommand.create({ username: user.username, password: user.password }) userAccessToken = await server.loginCommand.getAccessToken(user) const moderator = { username: 'moderator', password: 'my super password' } - await createUser( - { - url: server.url, - accessToken: server.accessToken, - username: moderator.username, - password: moderator.password, - videoQuota: undefined, - videoQuotaDaily: undefined, - role: UserRole.MODERATOR - } - ) + await server.usersCommand.create({ username: moderator.username, password: moderator.password, role: UserRole.MODERATOR }) + moderatorAccessToken = await server.loginCommand.getAccessToken(moderator) }) diff --git a/server/tests/api/check-params/videos.ts b/server/tests/api/check-params/videos.ts index 8e11232bd..855b09f39 100644 --- a/server/tests/api/check-params/videos.ts +++ b/server/tests/api/check-params/videos.ts @@ -10,9 +10,7 @@ import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-c import { checkUploadVideoParam, cleanupTests, - createUser, flushAndRunServer, - getMyUserInformation, getVideo, getVideosList, makeDeleteRequest, @@ -53,14 +51,14 @@ describe('Test videos API validator', function () { const username = 'user1' const password = 'my super password' - await createUser({ url: server.url, accessToken: server.accessToken, username: username, password: password }) + await server.usersCommand.create({ username: username, password: password }) userAccessToken = await server.loginCommand.getAccessToken({ username, password }) { - const res = await getMyUserInformation(server.url, server.accessToken) - channelId = res.body.videoChannels[0].id - channelName = res.body.videoChannels[0].name - accountName = res.body.account.name + '@' + res.body.account.host + const body = await server.usersCommand.getMyInfo() + channelId = body.videoChannels[0].id + channelName = body.videoChannels[0].name + accountName = body.account.name + '@' + body.account.host } }) @@ -283,11 +281,11 @@ describe('Test videos API validator', function () { username: 'fake' + randomInt(0, 1500), password: 'fake_password' } - await createUser({ url: server.url, accessToken: server.accessToken, username: user.username, password: user.password }) + await server.usersCommand.create({ username: user.username, password: user.password }) const accessTokenUser = await server.loginCommand.getAccessToken(user) - const res = await getMyUserInformation(server.url, accessTokenUser) - const customChannelId = res.body.videoChannels[0].id + const { videoChannels } = await server.usersCommand.getMyInfo({ token: accessTokenUser }) + const customChannelId = videoChannels[0].id const fields = { ...baseCorrectParams, channelId: customChannelId } const attaches = baseCorrectAttaches diff --git a/server/tests/api/live/live-constraints.ts b/server/tests/api/live/live-constraints.ts index 46153f7b1..290d325d4 100644 --- a/server/tests/api/live/live-constraints.ts +++ b/server/tests/api/live/live-constraints.ts @@ -9,12 +9,10 @@ import { ConfigCommand, doubleFollow, flushAndRunMultipleServers, - generateUser, getVideo, ServerInfo, setAccessTokensToServers, setDefaultVideoChannel, - updateUser, wait, waitJobs } from '../../../../shared/extra-utils' @@ -58,9 +56,7 @@ describe('Test live constraints', function () { } function updateQuota (options: { total: number, daily: number }) { - return updateUser({ - url: servers[0].url, - accessToken: servers[0].accessToken, + return servers[0].usersCommand.update({ userId, videoQuota: options.total, videoQuotaDaily: options.daily @@ -89,7 +85,7 @@ describe('Test live constraints', function () { }) { - const res = await generateUser(servers[0], 'user1') + const res = await servers[0].usersCommand.generate('user1') userId = res.userId userChannelId = res.userChannelId userAccessToken = res.token diff --git a/server/tests/api/moderation/abuses.ts b/server/tests/api/moderation/abuses.ts index d7462f38f..a7119263c 100644 --- a/server/tests/api/moderation/abuses.ts +++ b/server/tests/api/moderation/abuses.ts @@ -5,13 +5,10 @@ import * as chai from 'chai' import { AbusesCommand, cleanupTests, - createUser, doubleFollow, flushAndRunMultipleServers, - generateUserAccessToken, getVideoIdFromUUID, getVideosList, - removeUser, removeVideo, ServerInfo, setAccessTokensToServers, @@ -278,7 +275,7 @@ describe('Test abuses', function () { // register a second user to have two reporters/reportees const user = { username: 'user2', password: 'password' } - await createUser({ url: servers[0].url, accessToken: servers[0].accessToken, ...user }) + await servers[0].usersCommand.create({ ...user }) const userAccessToken = await servers[0].loginCommand.getAccessToken(user) // upload a third video via this user @@ -604,9 +601,9 @@ describe('Test abuses', function () { before(async function () { this.timeout(50000) - await createUser({ url: servers[0].url, accessToken: servers[0].accessToken, username: 'user_1', password: 'donald' }) + await servers[0].usersCommand.create({ username: 'user_1', password: 'donald' }) - const token = await generateUserAccessToken(servers[1], 'user_2') + const token = await servers[1].usersCommand.generateUserAndToken('user_2') await uploadVideo(servers[1].url, token, { name: 'super video' }) await waitJobs(servers) @@ -708,7 +705,7 @@ describe('Test abuses', function () { this.timeout(10000) const account = await getAccountFromServer(servers[1], 'user_2', servers[1]) - await removeUser(servers[1].url, account.userId, servers[1].accessToken) + await servers[1].usersCommand.remove({ userId: account.userId }) await waitJobs(servers) @@ -765,7 +762,7 @@ describe('Test abuses', function () { let userAccessToken: string before(async function () { - userAccessToken = await generateUserAccessToken(servers[0], 'user_42') + userAccessToken = await servers[0].usersCommand.generateUserAndToken('user_42') await commands[0].report({ token: userAccessToken, videoId: servers[0].video.id, reason: 'user reason 1' }) @@ -836,7 +833,7 @@ describe('Test abuses', function () { let abuseMessageModerationId: number before(async function () { - userToken = await generateUserAccessToken(servers[0], 'user_43') + userToken = await servers[0].usersCommand.generateUserAndToken('user_43') const body = await commands[0].report({ token: userToken, videoId: servers[0].video.id, reason: 'user 43 reason 1' }) abuseId = body.abuse.id diff --git a/server/tests/api/moderation/blocklist-notification.ts b/server/tests/api/moderation/blocklist-notification.ts index 4f2be6198..b44bcb012 100644 --- a/server/tests/api/moderation/blocklist-notification.ts +++ b/server/tests/api/moderation/blocklist-notification.ts @@ -4,7 +4,6 @@ import 'mocha' import * as chai from 'chai' import { cleanupTests, - createUser, doubleFollow, flushAndRunMultipleServers, ServerInfo, @@ -76,9 +75,7 @@ describe('Test blocklist', function () { { const user = { username: 'user1', password: 'password' } - await createUser({ - url: servers[0].url, - accessToken: servers[0].accessToken, + await servers[0].usersCommand.create({ username: user.username, password: user.password, videoQuota: -1, @@ -91,14 +88,14 @@ describe('Test blocklist', function () { { const user = { username: 'user2', password: 'password' } - await createUser({ url: servers[0].url, accessToken: servers[0].accessToken, username: user.username, password: user.password }) + await servers[0].usersCommand.create({ username: user.username, password: user.password }) userToken2 = await servers[0].loginCommand.getAccessToken(user) } { const user = { username: 'user3', password: 'password' } - await createUser({ url: servers[1].url, accessToken: servers[1].accessToken, username: user.username, password: user.password }) + await servers[1].usersCommand.create({ username: user.username, password: user.password }) remoteUserToken = await servers[1].loginCommand.getAccessToken(user) } diff --git a/server/tests/api/moderation/blocklist.ts b/server/tests/api/moderation/blocklist.ts index c38a7dad4..c253b5c11 100644 --- a/server/tests/api/moderation/blocklist.ts +++ b/server/tests/api/moderation/blocklist.ts @@ -6,7 +6,6 @@ import { BlocklistCommand, cleanupTests, CommentsCommand, - createUser, doubleFollow, flushAndRunMultipleServers, getVideosList, @@ -91,7 +90,7 @@ describe('Test blocklist', function () { { const user = { username: 'user1', password: 'password' } - await createUser({ url: servers[0].url, accessToken: servers[0].accessToken, username: user.username, password: user.password }) + await servers[0].usersCommand.create({ username: user.username, password: user.password }) userToken1 = await servers[0].loginCommand.getAccessToken(user) await uploadVideo(servers[0].url, userToken1, { name: 'video user 1' }) @@ -99,14 +98,14 @@ describe('Test blocklist', function () { { const user = { username: 'moderator', password: 'password' } - await createUser({ url: servers[0].url, accessToken: servers[0].accessToken, username: user.username, password: user.password }) + await servers[0].usersCommand.create({ username: user.username, password: user.password }) userModeratorToken = await servers[0].loginCommand.getAccessToken(user) } { const user = { username: 'user2', password: 'password' } - await createUser({ url: servers[1].url, accessToken: servers[1].accessToken, username: user.username, password: user.password }) + await servers[1].usersCommand.create({ username: user.username, password: user.password }) userToken2 = await servers[1].loginCommand.getAccessToken(user) await uploadVideo(servers[1].url, userToken2, { name: 'video user 2' }) diff --git a/server/tests/api/moderation/video-blacklist.ts b/server/tests/api/moderation/video-blacklist.ts index b61effc57..ef25cfb8e 100644 --- a/server/tests/api/moderation/video-blacklist.ts +++ b/server/tests/api/moderation/video-blacklist.ts @@ -6,10 +6,8 @@ import { orderBy } from 'lodash' import { BlacklistCommand, cleanupTests, - createUser, doubleFollow, flushAndRunMultipleServers, - getMyUserInformation, getMyVideos, getVideosList, ImportsCommand, @@ -21,7 +19,7 @@ import { uploadVideo, waitJobs } from '@shared/extra-utils' -import { User, UserAdminFlag, UserRole, VideoBlacklist, VideoBlacklistType } from '@shared/models' +import { UserAdminFlag, UserRole, VideoBlacklist, VideoBlacklistType } from '@shared/models' const expect = chai.expect @@ -356,9 +354,7 @@ describe('Test video blacklist', function () { { const user = { username: 'user_without_flag', password: 'password' } - await createUser({ - url: servers[0].url, - accessToken: servers[0].accessToken, + await servers[0].usersCommand.create({ username: user.username, adminFlags: UserAdminFlag.NONE, password: user.password, @@ -367,16 +363,13 @@ describe('Test video blacklist', function () { userWithoutFlag = await servers[0].loginCommand.getAccessToken(user) - const res = await getMyUserInformation(servers[0].url, userWithoutFlag) - const body: User = res.body - channelOfUserWithoutFlag = body.videoChannels[0].id + const { videoChannels } = await servers[0].usersCommand.getMyInfo({ token: userWithoutFlag }) + channelOfUserWithoutFlag = videoChannels[0].id } { const user = { username: 'user_with_flag', password: 'password' } - await createUser({ - url: servers[0].url, - accessToken: servers[0].accessToken, + await servers[0].usersCommand.create({ username: user.username, adminFlags: UserAdminFlag.BYPASS_VIDEO_AUTO_BLACKLIST, password: user.password, diff --git a/server/tests/api/notifications/comments-notifications.ts b/server/tests/api/notifications/comments-notifications.ts index ea6055386..62569f810 100644 --- a/server/tests/api/notifications/comments-notifications.ts +++ b/server/tests/api/notifications/comments-notifications.ts @@ -10,7 +10,6 @@ import { MockSmtpServer, prepareNotificationsTest, ServerInfo, - updateMyUser, uploadVideo, waitJobs } from '@shared/extra-utils' @@ -193,17 +192,8 @@ describe('Test comments notifications', function () { token: userToken } - await updateMyUser({ - url: servers[0].url, - accessToken: servers[0].accessToken, - displayName: 'super root name' - }) - - await updateMyUser({ - url: servers[1].url, - accessToken: servers[1].accessToken, - displayName: 'super root 2 name' - }) + await servers[0].usersCommand.updateMe({ displayName: 'super root name' }) + await servers[1].usersCommand.updateMe({ displayName: 'super root 2 name' }) }) it('Should not send a new mention comment notification if I mention the video owner', async function () { diff --git a/server/tests/api/notifications/moderation-notifications.ts b/server/tests/api/notifications/moderation-notifications.ts index 99b434606..0269124c5 100644 --- a/server/tests/api/notifications/moderation-notifications.ts +++ b/server/tests/api/notifications/moderation-notifications.ts @@ -17,13 +17,10 @@ import { checkVideoAutoBlacklistForModerators, checkVideoIsPublished, cleanupTests, - createUser, - generateUserAccessToken, getVideoIdFromUUID, MockInstancesIndex, MockSmtpServer, prepareNotificationsTest, - registerUser, ServerInfo, uploadVideo, wait, @@ -139,8 +136,8 @@ describe('Test moderation notifications', function () { this.timeout(20000) const username = 'user' + new Date().getTime() - const resUser = await createUser({ url: servers[0].url, accessToken: servers[0].accessToken, username, password: 'donald' }) - const accountId = resUser.body.user.account.id + const { account } = await servers[0].usersCommand.create({ username, password: 'donald' }) + const accountId = account.id await servers[0].abusesCommand.report({ accountId, reason: 'super reason' }) @@ -152,7 +149,7 @@ describe('Test moderation notifications', function () { this.timeout(20000) const username = 'user' + new Date().getTime() - const tmpToken = await generateUserAccessToken(servers[0], username) + const tmpToken = await servers[0].usersCommand.generateUserAndToken(username) await uploadVideo(servers[0].url, tmpToken, { name: 'super video' }) await waitJobs(servers) @@ -339,7 +336,7 @@ describe('Test moderation notifications', function () { it('Should send a notification only to moderators when a user registers on the instance', async function () { this.timeout(10000) - await registerUser(servers[0].url, 'user_45', 'password') + await servers[0].usersCommand.register({ username: 'user_45' }) await waitJobs(servers) diff --git a/server/tests/api/notifications/notifications-api.ts b/server/tests/api/notifications/notifications-api.ts index e5864f1c2..f33d8e64d 100644 --- a/server/tests/api/notifications/notifications-api.ts +++ b/server/tests/api/notifications/notifications-api.ts @@ -7,14 +7,13 @@ import { checkNewVideoFromSubscription, cleanupTests, getAllNotificationsSettings, - getMyUserInformation, MockSmtpServer, prepareNotificationsTest, ServerInfo, uploadRandomVideo, waitJobs } from '@shared/extra-utils' -import { User, UserNotification, UserNotificationSettingValue } from '@shared/models' +import { UserNotification, UserNotificationSettingValue } from '@shared/models' const expect = chai.expect @@ -109,15 +108,14 @@ describe('Test notifications API', function () { }) { - const res = await getMyUserInformation(server.url, userToken) - const info = res.body as User + const info = await server.usersCommand.getMyInfo({ token: userToken }) expect(info.notificationSettings.newVideoFromSubscription).to.equal(UserNotificationSettingValue.NONE) } const { name, uuid } = await uploadRandomVideo(server) const check = { web: true, mail: true } - await checkNewVideoFromSubscription({ ...baseParams, ...check }, name, uuid, 'absence') + await checkNewVideoFromSubscription({ ...baseParams, check }, name, uuid, 'absence') }) it('Should only have web notifications', async function () { @@ -129,8 +127,7 @@ describe('Test notifications API', function () { }) { - const res = await getMyUserInformation(server.url, userToken) - const info = res.body as User + const info = await server.usersCommand.getMyInfo({ token: userToken }) expect(info.notificationSettings.newVideoFromSubscription).to.equal(UserNotificationSettingValue.WEB) } @@ -138,12 +135,12 @@ describe('Test notifications API', function () { { const check = { mail: true, web: false } - await checkNewVideoFromSubscription({ ...baseParams, ...check }, name, uuid, 'absence') + await checkNewVideoFromSubscription({ ...baseParams, check }, name, uuid, 'absence') } { const check = { mail: false, web: true } - await checkNewVideoFromSubscription({ ...baseParams, ...check }, name, uuid, 'presence') + await checkNewVideoFromSubscription({ ...baseParams, check }, name, uuid, 'presence') } }) @@ -156,8 +153,7 @@ describe('Test notifications API', function () { }) { - const res = await getMyUserInformation(server.url, userToken) - const info = res.body as User + const info = await server.usersCommand.getMyInfo({ token: userToken }) expect(info.notificationSettings.newVideoFromSubscription).to.equal(UserNotificationSettingValue.EMAIL) } @@ -165,12 +161,12 @@ describe('Test notifications API', function () { { const check = { mail: false, web: true } - await checkNewVideoFromSubscription({ ...baseParams, ...check }, name, uuid, 'absence') + await checkNewVideoFromSubscription({ ...baseParams, check }, name, uuid, 'absence') } { const check = { mail: true, web: false } - await checkNewVideoFromSubscription({ ...baseParams, ...check }, name, uuid, 'presence') + await checkNewVideoFromSubscription({ ...baseParams, check }, name, uuid, 'presence') } }) @@ -186,8 +182,7 @@ describe('Test notifications API', function () { }) { - const res = await getMyUserInformation(server.url, userToken) - const info = res.body as User + const info = await server.usersCommand.getMyInfo({ token: userToken }) expect(info.notificationSettings.newVideoFromSubscription).to.equal( UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL ) diff --git a/server/tests/api/notifications/user-notifications.ts b/server/tests/api/notifications/user-notifications.ts index 4b31edf25..465349fb9 100644 --- a/server/tests/api/notifications/user-notifications.ts +++ b/server/tests/api/notifications/user-notifications.ts @@ -14,7 +14,6 @@ import { MockSmtpServer, prepareNotificationsTest, ServerInfo, - updateMyUser, updateVideo, uploadRandomVideoOnServers, wait, @@ -384,23 +383,14 @@ describe('Test user notifications', function () { token: userAccessToken } - await updateMyUser({ - url: servers[0].url, - accessToken: servers[0].accessToken, - displayName: 'super root name' - }) + await servers[0].usersCommand.updateMe({ displayName: 'super root name' }) - await updateMyUser({ - url: servers[0].url, - accessToken: userAccessToken, + await servers[0].usersCommand.updateMe({ + token: userAccessToken, displayName: myUserName }) - await updateMyUser({ - url: servers[1].url, - accessToken: servers[1].accessToken, - displayName: 'super root 2 name' - }) + await servers[1].usersCommand.updateMe({ displayName: 'super root 2 name' }) await servers[0].channelsCommand.update({ token: userAccessToken, diff --git a/server/tests/api/search/search-activitypub-video-channels.ts b/server/tests/api/search/search-activitypub-video-channels.ts index 3cba2b019..bcc21381c 100644 --- a/server/tests/api/search/search-activitypub-video-channels.ts +++ b/server/tests/api/search/search-activitypub-video-channels.ts @@ -4,13 +4,11 @@ import 'mocha' import * as chai from 'chai' import { cleanupTests, - createUser, flushAndRunMultipleServers, getVideoChannelVideos, SearchCommand, ServerInfo, setAccessTokensToServers, - updateMyUser, updateVideo, uploadVideo, wait, @@ -35,7 +33,7 @@ describe('Test ActivityPub video channels search', function () { await setAccessTokensToServers(servers) { - await createUser({ url: servers[0].url, accessToken: servers[0].accessToken, username: 'user1_server1', password: 'password' }) + await servers[0].usersCommand.create({ username: 'user1_server1', password: 'password' }) const channel = { name: 'channel1_server1', displayName: 'Channel 1 server 1' @@ -45,7 +43,7 @@ describe('Test ActivityPub video channels search', function () { { const user = { username: 'user1_server2', password: 'password' } - await createUser({ url: servers[1].url, accessToken: servers[1].accessToken, username: user.username, password: user.password }) + await servers[1].usersCommand.create({ username: user.username, password: user.password }) userServer2Token = await servers[1].loginCommand.getAccessToken(user) const channel = { @@ -171,7 +169,7 @@ describe('Test ActivityPub video channels search', function () { channelName: 'channel1_server2', attributes: { displayName: 'channel updated' } }) - await updateMyUser({ url: servers[1].url, accessToken: userServer2Token, displayName: 'user updated' }) + await servers[1].usersCommand.updateMe({ token: userServer2Token, displayName: 'user updated' }) await waitJobs(servers) // Expire video channel diff --git a/server/tests/api/search/search-channels.ts b/server/tests/api/search/search-channels.ts index 6c9ee73ce..4d2104708 100644 --- a/server/tests/api/search/search-channels.ts +++ b/server/tests/api/search/search-channels.ts @@ -2,7 +2,7 @@ import 'mocha' import * as chai from 'chai' -import { cleanupTests, createUser, flushAndRunServer, SearchCommand, ServerInfo, setAccessTokensToServers } from '@shared/extra-utils' +import { cleanupTests, flushAndRunServer, SearchCommand, ServerInfo, setAccessTokensToServers } from '@shared/extra-utils' import { VideoChannel } from '@shared/models' const expect = chai.expect @@ -19,7 +19,7 @@ describe('Test channels search', function () { await setAccessTokensToServers([ server ]) { - await createUser({ url: server.url, accessToken: server.accessToken, username: 'user1', password: 'password' }) + await server.usersCommand.create({ username: 'user1', password: 'password' }) const channel = { name: 'squall_channel', displayName: 'Squall channel' diff --git a/server/tests/api/server/bulk.ts b/server/tests/api/server/bulk.ts index a09c21228..20a9a3dc7 100644 --- a/server/tests/api/server/bulk.ts +++ b/server/tests/api/server/bulk.ts @@ -5,7 +5,6 @@ import * as chai from 'chai' import { BulkCommand, cleanupTests, - createUser, doubleFollow, flushAndRunMultipleServers, getVideosList, @@ -38,21 +37,21 @@ describe('Test bulk actions', function () { { const user = { username: 'user1', password: 'password' } - await createUser({ url: servers[0].url, accessToken: servers[0].accessToken, username: user.username, password: user.password }) + await servers[0].usersCommand.create({ username: user.username, password: user.password }) user1Token = await servers[0].loginCommand.getAccessToken(user) } { const user = { username: 'user2', password: 'password' } - await createUser({ url: servers[0].url, accessToken: servers[0].accessToken, username: user.username, password: user.password }) + await servers[0].usersCommand.create({ username: user.username, password: user.password }) user2Token = await servers[0].loginCommand.getAccessToken(user) } { const user = { username: 'user3', password: 'password' } - await createUser({ url: servers[1].url, accessToken: servers[1].accessToken, username: user.username, password: user.password }) + await servers[1].usersCommand.create({ username: user.username, password: user.password }) user3Token = await servers[1].loginCommand.getAccessToken(user) } diff --git a/server/tests/api/server/config.ts b/server/tests/api/server/config.ts index 55cf2a1b8..95dafd378 100644 --- a/server/tests/api/server/config.ts +++ b/server/tests/api/server/config.ts @@ -9,7 +9,6 @@ import { killallServers, makeGetRequest, parallelTests, - registerUser, reRunServer, ServerInfo, setAccessTokensToServers, @@ -225,9 +224,9 @@ describe('Test config', function () { this.timeout(5000) await Promise.all([ - registerUser(server.url, 'user1', 'super password'), - registerUser(server.url, 'user2', 'super password'), - registerUser(server.url, 'user3', 'super password') + server.usersCommand.register({ username: 'user1' }), + server.usersCommand.register({ username: 'user2' }), + server.usersCommand.register({ username: 'user3' }) ]) const data = await server.configCommand.getConfig() diff --git a/server/tests/api/server/email.ts b/server/tests/api/server/email.ts index c64c120e3..422db6ceb 100644 --- a/server/tests/api/server/email.ts +++ b/server/tests/api/server/email.ts @@ -2,23 +2,16 @@ import 'mocha' import * as chai from 'chai' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '@shared/core-utils' import { - askResetPassword, - askSendVerifyEmail, - blockUser, cleanupTests, - createUser, flushAndRunServer, - resetPassword, + MockSmtpServer, ServerInfo, setAccessTokensToServers, - unblockUser, uploadVideo, - verifyEmail -} from '../../../../shared/extra-utils' -import { MockSmtpServer } from '../../../../shared/extra-utils/mock-servers/mock-email' -import { waitJobs } from '../../../../shared/extra-utils/server/jobs' + waitJobs +} from '@shared/extra-utils' const expect = chai.expect @@ -58,8 +51,8 @@ describe('Test emails', function () { await setAccessTokensToServers([ server ]) { - const res = await createUser({ url: server.url, accessToken: server.accessToken, username: user.username, password: user.password }) - userId = res.body.user.id + const created = await server.usersCommand.create({ username: user.username, password: user.password }) + userId = created.id userAccessToken = await server.loginCommand.getAccessToken(user) } @@ -87,7 +80,7 @@ describe('Test emails', function () { it('Should ask to reset the password', async function () { this.timeout(10000) - await askResetPassword(server.url, 'user_1@example.com') + await server.usersCommand.askResetPassword({ email: 'user_1@example.com' }) await waitJobs(server) expect(emails).to.have.lengthOf(1) @@ -113,15 +106,25 @@ describe('Test emails', function () { }) it('Should not reset the password with an invalid verification string', async function () { - await resetPassword(server.url, userId, verificationString + 'b', 'super_password2', HttpStatusCode.FORBIDDEN_403) + await server.usersCommand.resetPassword({ + userId, + verificationString: verificationString + 'b', + password: 'super_password2', + expectedStatus: HttpStatusCode.FORBIDDEN_403 + }) }) it('Should reset the password', async function () { - await resetPassword(server.url, userId, verificationString, 'super_password2') + await server.usersCommand.resetPassword({ userId, verificationString, password: 'super_password2' }) }) it('Should not reset the password with the same verification string', async function () { - await resetPassword(server.url, userId, verificationString, 'super_password3', HttpStatusCode.FORBIDDEN_403) + await server.usersCommand.resetPassword({ + userId, + verificationString, + password: 'super_password3', + expectedStatus: HttpStatusCode.FORBIDDEN_403 + }) }) it('Should login with this new password', async function () { @@ -132,15 +135,11 @@ describe('Test emails', function () { }) describe('When creating a user without password', function () { + it('Should send a create password email', async function () { this.timeout(10000) - await createUser({ - url: server.url, - accessToken: server.accessToken, - username: 'create_password', - password: '' - }) + await server.usersCommand.create({ username: 'create_password', password: '' }) await waitJobs(server) expect(emails).to.have.lengthOf(2) @@ -166,11 +165,20 @@ describe('Test emails', function () { }) it('Should not reset the password with an invalid verification string', async function () { - await resetPassword(server.url, userId2, verificationString2 + 'c', 'newly_created_password', HttpStatusCode.FORBIDDEN_403) + await server.usersCommand.resetPassword({ + userId: userId2, + verificationString: verificationString2 + 'c', + password: 'newly_created_password', + expectedStatus: HttpStatusCode.FORBIDDEN_403 + }) }) it('Should reset the password', async function () { - await resetPassword(server.url, userId2, verificationString2, 'newly_created_password') + await server.usersCommand.resetPassword({ + userId: userId2, + verificationString: verificationString2, + password: 'newly_created_password' + }) }) it('Should login with this new password', async function () { @@ -207,7 +215,7 @@ describe('Test emails', function () { this.timeout(10000) const reason = 'my super bad reason' - await blockUser(server.url, userId, server.accessToken, HttpStatusCode.NO_CONTENT_204, reason) + await server.usersCommand.banUser({ userId, reason }) await waitJobs(server) expect(emails).to.have.lengthOf(4) @@ -225,7 +233,7 @@ describe('Test emails', function () { it('Should send the notification email when unblocking a user', async function () { this.timeout(10000) - await unblockUser(server.url, userId, server.accessToken, HttpStatusCode.NO_CONTENT_204) + await server.usersCommand.unbanUser({ userId }) await waitJobs(server) expect(emails).to.have.lengthOf(5) @@ -288,7 +296,7 @@ describe('Test emails', function () { it('Should ask to send the verification email', async function () { this.timeout(10000) - await askSendVerifyEmail(server.url, 'user_1@example.com') + await server.usersCommand.askSendVerifyEmail({ email: 'user_1@example.com' }) await waitJobs(server) expect(emails).to.have.lengthOf(8) @@ -314,11 +322,16 @@ describe('Test emails', function () { }) it('Should not verify the email with an invalid verification string', async function () { - await verifyEmail(server.url, userId, verificationString + 'b', false, HttpStatusCode.FORBIDDEN_403) + await server.usersCommand.verifyEmail({ + userId, + verificationString: verificationString + 'b', + isPendingEmail: false, + expectedStatus: HttpStatusCode.FORBIDDEN_403 + }) }) it('Should verify the email', async function () { - await verifyEmail(server.url, userId, verificationString) + await server.usersCommand.verifyEmail({ userId, verificationString }) }) }) diff --git a/server/tests/api/server/follow-constraints.ts b/server/tests/api/server/follow-constraints.ts index 74cdf353b..29ccb264d 100644 --- a/server/tests/api/server/follow-constraints.ts +++ b/server/tests/api/server/follow-constraints.ts @@ -6,7 +6,6 @@ import { HttpStatusCode } from '@shared/core-utils' import { PeerTubeProblemDocument, ServerErrorCode } from '@shared/models' import { cleanupTests, - createUser, doubleFollow, flushAndRunMultipleServers, getAccountVideos, @@ -47,7 +46,7 @@ describe('Test follow constraints', function () { username: 'user1', password: 'super_password' } - await createUser({ url: servers[0].url, accessToken: servers[0].accessToken, username: user.username, password: user.password }) + await servers[0].usersCommand.create({ username: user.username, password: user.password }) userAccessToken = await servers[0].loginCommand.getAccessToken(user) await doubleFollow(servers[0], servers[1]) diff --git a/server/tests/api/server/follows.ts b/server/tests/api/server/follows.ts index c2a0620a5..02d25e67f 100644 --- a/server/tests/api/server/follows.ts +++ b/server/tests/api/server/follows.ts @@ -5,7 +5,6 @@ import * as chai from 'chai' import { cleanupTests, completeVideoCheck, - createUser, dateIsValid, expectAccountFollows, flushAndRunMultipleServers, @@ -327,9 +326,7 @@ describe('Test follows', function () { await uploadVideo(servers[2].url, servers[2].accessToken, { name: 'server3-6' }) { - const user = { username: 'captain', password: 'password' } - await createUser({ url: servers[2].url, accessToken: servers[2].accessToken, username: user.username, password: user.password }) - const userAccessToken = await servers[2].loginCommand.getAccessToken(user) + const userAccessToken = await servers[2].usersCommand.generateUserAndToken('captain') const resVideos = await getVideosList(servers[2].url) video4 = resVideos.body.data.find(v => v.name === 'server3-4') diff --git a/server/tests/api/server/jobs.ts b/server/tests/api/server/jobs.ts index c0b9facff..6854568d3 100644 --- a/server/tests/api/server/jobs.ts +++ b/server/tests/api/server/jobs.ts @@ -30,7 +30,7 @@ describe('Test jobs', function () { }) it('Should create some jobs', async function () { - this.timeout(60000) + this.timeout(120000) await uploadVideo(servers[1].url, servers[1].accessToken, { name: 'video1' }) await uploadVideo(servers[1].url, servers[1].accessToken, { name: 'video2' }) diff --git a/server/tests/api/server/plugins.ts b/server/tests/api/server/plugins.ts index a81ac961a..1fd5e613b 100644 --- a/server/tests/api/server/plugins.ts +++ b/server/tests/api/server/plugins.ts @@ -6,17 +6,15 @@ import { HttpStatusCode } from '@shared/core-utils' import { cleanupTests, flushAndRunServer, - getMyUserInformation, killallServers, PluginsCommand, reRunServer, ServerInfo, setAccessTokensToServers, testHelloWorldRegisteredSettings, - updateMyUser, wait } from '@shared/extra-utils' -import { PluginType, User } from '@shared/models' +import { PluginType } from '@shared/models' const expect = chai.expect @@ -120,14 +118,10 @@ describe('Test plugins', function () { }) it('Should update my default theme', async function () { - await updateMyUser({ - url: server.url, - accessToken: server.accessToken, - theme: 'background-red' - }) + await server.usersCommand.updateMe({ theme: 'background-red' }) - const res = await getMyUserInformation(server.url, server.accessToken) - expect((res.body as User).theme).to.equal('background-red') + const user = await server.usersCommand.getMyInfo() + expect(user.theme).to.equal('background-red') }) it('Should list plugins and themes', async function () { @@ -311,8 +305,8 @@ describe('Test plugins', function () { }) it('Should have updated the user theme', async function () { - const res = await getMyUserInformation(server.url, server.accessToken) - expect((res.body as User).theme).to.equal('instance-default') + const user = await server.usersCommand.getMyInfo() + expect(user.theme).to.equal('instance-default') }) it('Should not install a broken plugin', async function () { diff --git a/server/tests/api/server/reverse-proxy.ts b/server/tests/api/server/reverse-proxy.ts index d9c669571..b8bae161a 100644 --- a/server/tests/api/server/reverse-proxy.ts +++ b/server/tests/api/server/reverse-proxy.ts @@ -6,7 +6,7 @@ import { cleanupTests, flushAndRunServer, getVideo, - registerUser, + ServerInfo, setAccessTokensToServers, uploadVideo, viewVideo, @@ -14,8 +14,8 @@ import { } from '@shared/extra-utils' describe('Test application behind a reverse proxy', function () { - let server = null - let videoId + let server: ServerInfo + let videoId: number before(async function () { this.timeout(30000) @@ -102,22 +102,22 @@ describe('Test application behind a reverse proxy', function () { const user = { username: 'root', password: 'fail' } for (let i = 0; i < 19; i++) { - await server.loginCommand.getAccessToken(user, HttpStatusCode.BAD_REQUEST_400) + await server.loginCommand.login({ user, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) } - await server.loginCommand.getAccessToken(user, HttpStatusCode.TOO_MANY_REQUESTS_429) + await server.loginCommand.login({ user, expectedStatus: HttpStatusCode.TOO_MANY_REQUESTS_429 }) }) it('Should rate limit signup', async function () { for (let i = 0; i < 10; i++) { try { - await registerUser(server.url, 'test' + i, 'password') + await server.usersCommand.register({ username: 'test' + i }) } catch { // empty } } - await registerUser(server.url, 'test42', 'password', HttpStatusCode.TOO_MANY_REQUESTS_429) + await server.usersCommand.register({ username: 'test42', expectedStatus: HttpStatusCode.TOO_MANY_REQUESTS_429 }) }) it('Should not rate limit failed signup', async function () { @@ -126,10 +126,10 @@ describe('Test application behind a reverse proxy', function () { await wait(7000) for (let i = 0; i < 3; i++) { - await registerUser(server.url, 'test' + i, 'password', HttpStatusCode.CONFLICT_409) + await server.usersCommand.register({ username: 'test' + i, expectedStatus: HttpStatusCode.CONFLICT_409 }) } - await registerUser(server.url, 'test43', 'password', HttpStatusCode.NO_CONTENT_204) + await server.usersCommand.register({ username: 'test43', expectedStatus: HttpStatusCode.NO_CONTENT_204 }) }) diff --git a/server/tests/api/server/stats.ts b/server/tests/api/server/stats.ts index aa26f978d..a35709c26 100644 --- a/server/tests/api/server/stats.ts +++ b/server/tests/api/server/stats.ts @@ -4,7 +4,6 @@ import 'mocha' import * as chai from 'chai' import { cleanupTests, - createUser, doubleFollow, flushAndRunMultipleServers, ServerInfo, @@ -35,7 +34,7 @@ describe('Test stats (excluding redundancy)', function () { await doubleFollow(servers[0], servers[1]) - await createUser({ url: servers[0].url, accessToken: servers[0].accessToken, username: user.username, password: user.password }) + await servers[0].usersCommand.create({ username: user.username, password: user.password }) const resVideo = await uploadVideo(servers[0].url, servers[0].accessToken, { fixture: 'video_short.webm' }) const videoUUID = resVideo.body.video.uuid diff --git a/server/tests/api/users/user-subscriptions.ts b/server/tests/api/users/user-subscriptions.ts index 1d0fc35f1..c09a85a32 100644 --- a/server/tests/api/users/user-subscriptions.ts +++ b/server/tests/api/users/user-subscriptions.ts @@ -4,7 +4,6 @@ import 'mocha' import * as chai from 'chai' import { cleanupTests, - createUser, doubleFollow, flushAndRunMultipleServers, getVideosList, @@ -39,7 +38,7 @@ describe('Test users subscriptions', function () { { for (const server of servers) { const user = { username: 'user' + server.serverNumber, password: 'password' } - await createUser({ url: server.url, accessToken: server.accessToken, username: user.username, password: user.password }) + await server.usersCommand.create({ username: user.username, password: user.password }) const accessToken = await server.loginCommand.getAccessToken(user) users.push({ accessToken }) diff --git a/server/tests/api/users/users-multiple-servers.ts b/server/tests/api/users/users-multiple-servers.ts index 99fa08fe2..43e67ee60 100644 --- a/server/tests/api/users/users-multiple-servers.ts +++ b/server/tests/api/users/users-multiple-servers.ts @@ -7,17 +7,12 @@ import { checkTmpIsEmpty, checkVideoFilesWereRemoved, cleanupTests, - createUser, doubleFollow, flushAndRunMultipleServers, getAccountVideos, - getMyUserInformation, - removeUser, ServerInfo, setAccessTokensToServers, testImage, - updateMyAvatar, - updateMyUser, uploadVideo, waitJobs } from '@shared/extra-utils' @@ -56,13 +51,8 @@ describe('Test users with multiple servers', function () { username: 'user1', password: 'password' } - const res = await createUser({ - url: servers[0].url, - accessToken: servers[0].accessToken, - username: user.username, - password: user.password - }) - userId = res.body.user.id + const created = await servers[0].usersCommand.create(user) + userId = created.id userAccessToken = await servers[0].loginCommand.getAccessToken(user) } @@ -77,15 +67,9 @@ describe('Test users with multiple servers', function () { it('Should be able to update my display name', async function () { this.timeout(10000) - await updateMyUser({ - url: servers[0].url, - accessToken: servers[0].accessToken, - displayName: 'my super display name' - }) - - const res = await getMyUserInformation(servers[0].url, servers[0].accessToken) - user = res.body + await servers[0].usersCommand.updateMe({ displayName: 'my super display name' }) + user = await servers[0].usersCommand.getMyInfo() expect(user.account.displayName).to.equal('my super display name') await waitJobs(servers) @@ -94,14 +78,9 @@ describe('Test users with multiple servers', function () { it('Should be able to update my description', async function () { this.timeout(10_000) - await updateMyUser({ - url: servers[0].url, - accessToken: servers[0].accessToken, - description: 'my super description updated' - }) + await servers[0].usersCommand.updateMe({ description: 'my super description updated' }) - const res = await getMyUserInformation(servers[0].url, servers[0].accessToken) - user = res.body + user = await servers[0].usersCommand.getMyInfo() expect(user.account.displayName).to.equal('my super display name') expect(user.account.description).to.equal('my super description updated') @@ -113,15 +92,9 @@ describe('Test users with multiple servers', function () { const fixture = 'avatar2.png' - await updateMyAvatar({ - url: servers[0].url, - accessToken: servers[0].accessToken, - fixture - }) - - const res = await getMyUserInformation(servers[0].url, servers[0].accessToken) - user = res.body + await servers[0].usersCommand.updateMyAvatar({ fixture }) + user = await servers[0].usersCommand.getMyInfo() userAvatarFilename = user.account.avatar.path await testImage(servers[0].url, 'avatar2-resized', userAvatarFilename, '.png') @@ -202,7 +175,7 @@ describe('Test users with multiple servers', function () { expect(videoChannelDeleted).not.to.be.undefined } - await removeUser(servers[0].url, userId, servers[0].accessToken) + await servers[0].usersCommand.remove({ userId }) await waitJobs(servers) diff --git a/server/tests/api/users/users-verification.ts b/server/tests/api/users/users-verification.ts index ade730323..271aa3c7a 100644 --- a/server/tests/api/users/users-verification.ts +++ b/server/tests/api/users/users-verification.ts @@ -3,20 +3,7 @@ import 'mocha' import * as chai from 'chai' import { HttpStatusCode } from '@shared/core-utils' -import { - cleanupTests, - flushAndRunServer, - getMyUserInformation, - getUserInformation, - MockSmtpServer, - registerUser, - ServerInfo, - setAccessTokensToServers, - updateMyUser, - verifyEmail, - waitJobs -} from '@shared/extra-utils' -import { User } from '@shared/models' +import { cleanupTests, flushAndRunServer, MockSmtpServer, ServerInfo, setAccessTokensToServers, waitJobs } from '@shared/extra-utils' const expect = chai.expect @@ -65,7 +52,7 @@ describe('Test users account verification', function () { } }) - await registerUser(server.url, user1.username, user1.password) + await server.usersCommand.register(user1) await waitJobs(server) expectedEmailsLength++ @@ -84,8 +71,8 @@ describe('Test users account verification', function () { userId = parseInt(userIdMatches[1], 10) - const resUserInfo = await getUserInformation(server.url, server.accessToken, userId) - expect(resUserInfo.body.emailVerified).to.be.false + const body = await server.usersCommand.get({ userId }) + expect(body.emailVerified).to.be.false }) it('Should not allow login for user with unverified email', async function () { @@ -94,13 +81,13 @@ describe('Test users account verification', function () { }) it('Should verify the user via email and allow login', async function () { - await verifyEmail(server.url, userId, verificationString) + await server.usersCommand.verifyEmail({ userId, verificationString }) const body = await server.loginCommand.login({ user: user1 }) userAccessToken = body.access_token - const resUserVerified = await getUserInformation(server.url, server.accessToken, userId) - expect(resUserVerified.body.emailVerified).to.be.true + const user = await server.usersCommand.get({ userId }) + expect(user.emailVerified).to.be.true }) it('Should be able to change the user email', async function () { @@ -109,9 +96,8 @@ describe('Test users account verification', function () { let updateVerificationString: string { - await updateMyUser({ - url: server.url, - accessToken: userAccessToken, + await server.usersCommand.updateMe({ + token: userAccessToken, email: 'updated@example.com', currentPassword: user1.password }) @@ -127,19 +113,15 @@ describe('Test users account verification', function () { } { - const res = await getMyUserInformation(server.url, userAccessToken) - const me: User = res.body - + const me = await server.usersCommand.getMyInfo({ token: userAccessToken }) expect(me.email).to.equal('user_1@example.com') expect(me.pendingEmail).to.equal('updated@example.com') } { - await verifyEmail(server.url, userId, updateVerificationString, true) - - const res = await getMyUserInformation(server.url, userAccessToken) - const me: User = res.body + await server.usersCommand.verifyEmail({ userId, verificationString: updateVerificationString, isPendingEmail: true }) + const me = await server.usersCommand.getMyInfo({ token: userAccessToken }) expect(me.email).to.equal('updated@example.com') expect(me.pendingEmail).to.be.null } @@ -157,15 +139,15 @@ describe('Test users account verification', function () { } }) - await registerUser(server.url, user2.username, user2.password) + await server.usersCommand.register(user2) await waitJobs(server) expect(emails).to.have.lengthOf(expectedEmailsLength) const accessToken = await server.loginCommand.getAccessToken(user2) - const resMyUserInfo = await getMyUserInformation(server.url, accessToken) - expect(resMyUserInfo.body.emailVerified).to.be.null + const user = await server.usersCommand.getMyInfo({ token: accessToken }) + expect(user.emailVerified).to.be.null }) it('Should allow login for user with unverified email when setting later enabled', async function () { diff --git a/server/tests/api/users/users.ts b/server/tests/api/users/users.ts index 608bedb8b..30d7e850d 100644 --- a/server/tests/api/users/users.ts +++ b/server/tests/api/users/users.ts @@ -4,37 +4,22 @@ import 'mocha' import * as chai from 'chai' import { HttpStatusCode } from '@shared/core-utils' import { - blockUser, cleanupTests, - createUser, - deleteMe, flushAndRunServer, - getMyUserInformation, - getMyUserVideoQuotaUsed, - getMyUserVideoRating, getMyVideos, - getUserInformation, - getUsersList, - getUsersListPaginationAndSort, getVideosList, killallServers, makePutBodyRequest, rateVideo, - registerUserWithChannel, - removeUser, removeVideo, reRunServer, ServerInfo, setAccessTokensToServers, testImage, - unblockUser, - updateMyAvatar, - updateMyUser, - updateUser, uploadVideo, waitJobs } from '@shared/extra-utils' -import { AbuseState, MyUser, OAuth2ErrorCode, User, UserAdminFlag, UserRole, Video, VideoPlaylistType } from '@shared/models' +import { AbuseState, OAuth2ErrorCode, UserAdminFlag, UserRole, Video, VideoPlaylistType } from '@shared/models' const expect = chai.expect @@ -174,8 +159,7 @@ describe('Test users', function () { it('Should retrieve a video rating', async function () { await rateVideo(server.url, accessToken, videoId, 'like') - const res = await getMyUserVideoRating(server.url, accessToken, videoId) - const rating = res.body + const rating = await server.usersCommand.getMyRating({ token: accessToken, videoId }) expect(rating.videoId).to.equal(videoId) expect(rating.rating).to.equal('like') @@ -222,7 +206,7 @@ describe('Test users', function () { }) it('Should not be able to get the user information', async function () { - await getMyUserInformation(server.url, server.accessToken, HttpStatusCode.UNAUTHORIZED_401) + await server.usersCommand.getMyInfo({ expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should not be able to upload a video', async function () { @@ -252,7 +236,7 @@ describe('Test users', function () { }) it('Should be able to get my user information again', async function () { - await getMyUserInformation(server.url, server.accessToken) + await server.usersCommand.getMyInfo() }) it('Should have an expired access token', async function () { @@ -264,7 +248,7 @@ describe('Test users', function () { await killallServers([ server ]) await reRunServer(server) - await getMyUserInformation(server.url, server.accessToken, HttpStatusCode.UNAUTHORIZED_401) + await server.usersCommand.getMyInfo({ expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should not be able to refresh an access token with an expired refresh token', async function () { @@ -286,21 +270,14 @@ describe('Test users', function () { }) it('Should be able to get my user information again', async function () { - await getMyUserInformation(server.url, server.accessToken) + await server.usersCommand.getMyInfo() }) }) describe('Creating a user', function () { it('Should be able to create a new user', async function () { - await createUser({ - url: server.url, - accessToken: accessToken, - username: user.username, - password: user.password, - videoQuota: 2 * 1024 * 1024, - adminFlags: UserAdminFlag.BYPASS_VIDEO_AUTO_BLACKLIST - }) + await server.usersCommand.create({ ...user, videoQuota: 2 * 1024 * 1024, adminFlags: UserAdminFlag.BYPASS_VIDEO_AUTO_BLACKLIST }) }) it('Should be able to login with this user', async function () { @@ -308,11 +285,9 @@ describe('Test users', function () { }) it('Should be able to get user information', async function () { - const res1 = await getMyUserInformation(server.url, accessTokenUser) - const userMe: MyUser = res1.body + const userMe = await server.usersCommand.getMyInfo({ token: accessTokenUser }) - const res2 = await getUserInformation(server.url, server.accessToken, userMe.id, true) - const userGet: User = res2.body + const userGet = await server.usersCommand.get({ userId: userMe.id, withStats: true }) for (const user of [ userMe, userGet ]) { expect(user.username).to.equal('user_1') @@ -356,15 +331,11 @@ describe('Test users', function () { }) it('Should have video quota updated', async function () { - const res = await getMyUserVideoQuotaUsed(server.url, accessTokenUser) - const data = res.body - - expect(data.videoQuotaUsed).to.equal(218910) - - const resUsers = await getUsersList(server.url, server.accessToken) + const quota = await server.usersCommand.getMyQuotaUsed({ token: accessTokenUser }) + expect(quota.videoQuotaUsed).to.equal(218910) - const users: User[] = resUsers.body.data - const tmpUser = users.find(u => u.username === user.username) + const { data } = await server.usersCommand.list() + const tmpUser = data.find(u => u.username === user.username) expect(tmpUser.videoQuotaUsed).to.equal(218910) }) @@ -421,9 +392,7 @@ describe('Test users', function () { } { - const res = await getMyUserVideoQuotaUsed(server.url, accessTokenUser) - const data = res.body - + const data = await server.usersCommand.getMyQuotaUsed({ token: accessTokenUser }) expect(data.videoQuotaUsed).to.be.greaterThan(220000) } }) @@ -432,21 +401,18 @@ describe('Test users', function () { describe('Users listing', function () { it('Should list all the users', async function () { - const res = await getUsersList(server.url, server.accessToken) - const result = res.body - const total = result.total - const users = result.data + const { data, total } = await server.usersCommand.list() expect(total).to.equal(2) - expect(users).to.be.an('array') - expect(users.length).to.equal(2) + expect(data).to.be.an('array') + expect(data.length).to.equal(2) - const user = users[0] + const user = data[0] expect(user.username).to.equal('user_1') expect(user.email).to.equal('user_1@example.com') expect(user.nsfwPolicy).to.equal('display') - const rootUser = users[1] + const rootUser = data[1] expect(rootUser.username).to.equal('root') expect(rootUser.email).to.equal('admin' + server.internalServerNumber + '@example.com') expect(user.nsfwPolicy).to.equal('display') @@ -458,16 +424,12 @@ describe('Test users', function () { }) it('Should list only the first user by username asc', async function () { - const res = await getUsersListPaginationAndSort(server.url, server.accessToken, 0, 1, 'username') - - const result = res.body - const total = result.total - const users = result.data + const { total, data } = await server.usersCommand.list({ start: 0, count: 1, sort: 'username' }) expect(total).to.equal(2) - expect(users.length).to.equal(1) + expect(data.length).to.equal(1) - const user = users[0] + const user = data[0] expect(user.username).to.equal('root') expect(user.email).to.equal('admin' + server.internalServerNumber + '@example.com') expect(user.roleLabel).to.equal('Administrator') @@ -475,84 +437,66 @@ describe('Test users', function () { }) it('Should list only the first user by username desc', async function () { - const res = await getUsersListPaginationAndSort(server.url, server.accessToken, 0, 1, '-username') - const result = res.body - const total = result.total - const users = result.data + const { total, data } = await server.usersCommand.list({ start: 0, count: 1, sort: '-username' }) expect(total).to.equal(2) - expect(users.length).to.equal(1) + expect(data.length).to.equal(1) - const user = users[0] + const user = data[0] expect(user.username).to.equal('user_1') expect(user.email).to.equal('user_1@example.com') expect(user.nsfwPolicy).to.equal('display') }) it('Should list only the second user by createdAt desc', async function () { - const res = await getUsersListPaginationAndSort(server.url, server.accessToken, 0, 1, '-createdAt') - const result = res.body - const total = result.total - const users = result.data - + const { data, total } = await server.usersCommand.list({ start: 0, count: 1, sort: '-createdAt' }) expect(total).to.equal(2) - expect(users.length).to.equal(1) - const user = users[0] + expect(data.length).to.equal(1) + + const user = data[0] expect(user.username).to.equal('user_1') expect(user.email).to.equal('user_1@example.com') expect(user.nsfwPolicy).to.equal('display') }) it('Should list all the users by createdAt asc', async function () { - const res = await getUsersListPaginationAndSort(server.url, server.accessToken, 0, 2, 'createdAt') - const result = res.body - const total = result.total - const users = result.data + const { data, total } = await server.usersCommand.list({ start: 0, count: 2, sort: 'createdAt' }) expect(total).to.equal(2) - expect(users.length).to.equal(2) + expect(data.length).to.equal(2) - expect(users[0].username).to.equal('root') - expect(users[0].email).to.equal('admin' + server.internalServerNumber + '@example.com') - expect(users[0].nsfwPolicy).to.equal('display') + expect(data[0].username).to.equal('root') + expect(data[0].email).to.equal('admin' + server.internalServerNumber + '@example.com') + expect(data[0].nsfwPolicy).to.equal('display') - expect(users[1].username).to.equal('user_1') - expect(users[1].email).to.equal('user_1@example.com') - expect(users[1].nsfwPolicy).to.equal('display') + expect(data[1].username).to.equal('user_1') + expect(data[1].email).to.equal('user_1@example.com') + expect(data[1].nsfwPolicy).to.equal('display') }) it('Should search user by username', async function () { - const res = await getUsersListPaginationAndSort(server.url, server.accessToken, 0, 2, 'createdAt', 'oot') - const users = res.body.data as User[] - - expect(res.body.total).to.equal(1) - expect(users.length).to.equal(1) - - expect(users[0].username).to.equal('root') + const { data, total } = await server.usersCommand.list({ start: 0, count: 2, sort: 'createdAt', search: 'oot' }) + expect(total).to.equal(1) + expect(data.length).to.equal(1) + expect(data[0].username).to.equal('root') }) it('Should search user by email', async function () { { - const res = await getUsersListPaginationAndSort(server.url, server.accessToken, 0, 2, 'createdAt', 'r_1@exam') - const users = res.body.data as User[] - - expect(res.body.total).to.equal(1) - expect(users.length).to.equal(1) - - expect(users[0].username).to.equal('user_1') - expect(users[0].email).to.equal('user_1@example.com') + const { total, data } = await server.usersCommand.list({ start: 0, count: 2, sort: 'createdAt', search: 'r_1@exam' }) + expect(total).to.equal(1) + expect(data.length).to.equal(1) + expect(data[0].username).to.equal('user_1') + expect(data[0].email).to.equal('user_1@example.com') } { - const res = await getUsersListPaginationAndSort(server.url, server.accessToken, 0, 2, 'createdAt', 'example') - const users = res.body.data as User[] - - expect(res.body.total).to.equal(2) - expect(users.length).to.equal(2) - - expect(users[0].username).to.equal('root') - expect(users[1].username).to.equal('user_1') + const { total, data } = await server.usersCommand.list({ start: 0, count: 2, sort: 'createdAt', search: 'example' }) + expect(total).to.equal(2) + expect(data.length).to.equal(2) + expect(data[0].username).to.equal('root') + expect(data[1].username).to.equal('user_1') } }) }) @@ -560,9 +504,8 @@ describe('Test users', function () { describe('Update my account', function () { it('Should update my password', async function () { - await updateMyUser({ - url: server.url, - accessToken: accessTokenUser, + await server.usersCommand.updateMe({ + token: accessTokenUser, currentPassword: 'super password', password: 'new password' }) @@ -572,15 +515,12 @@ describe('Test users', function () { }) it('Should be able to change the NSFW display attribute', async function () { - await updateMyUser({ - url: server.url, - accessToken: accessTokenUser, + await server.usersCommand.updateMe({ + token: accessTokenUser, nsfwPolicy: 'do_not_list' }) - const res = await getMyUserInformation(server.url, accessTokenUser) - const user = res.body - + const user = await server.usersCommand.getMyInfo({ token: accessTokenUser }) expect(user.username).to.equal('user_1') expect(user.email).to.equal('user_1@example.com') expect(user.nsfwPolicy).to.equal('do_not_list') @@ -591,42 +531,33 @@ describe('Test users', function () { }) it('Should be able to change the autoPlayVideo attribute', async function () { - await updateMyUser({ - url: server.url, - accessToken: accessTokenUser, + await server.usersCommand.updateMe({ + token: accessTokenUser, autoPlayVideo: false }) - const res = await getMyUserInformation(server.url, accessTokenUser) - const user = res.body - + const user = await server.usersCommand.getMyInfo({ token: accessTokenUser }) expect(user.autoPlayVideo).to.be.false }) it('Should be able to change the autoPlayNextVideo attribute', async function () { - await updateMyUser({ - url: server.url, - accessToken: accessTokenUser, + await server.usersCommand.updateMe({ + token: accessTokenUser, autoPlayNextVideo: true }) - const res = await getMyUserInformation(server.url, accessTokenUser) - const user = res.body - + const user = await server.usersCommand.getMyInfo({ token: accessTokenUser }) expect(user.autoPlayNextVideo).to.be.true }) it('Should be able to change the email attribute', async function () { - await updateMyUser({ - url: server.url, - accessToken: accessTokenUser, + await server.usersCommand.updateMe({ + token: accessTokenUser, currentPassword: 'new password', email: 'updated@example.com' }) - const res = await getMyUserInformation(server.url, accessTokenUser) - const user = res.body - + const user = await server.usersCommand.getMyInfo({ token: accessTokenUser }) expect(user.username).to.equal('user_1') expect(user.email).to.equal('updated@example.com') expect(user.nsfwPolicy).to.equal('do_not_list') @@ -639,15 +570,9 @@ describe('Test users', function () { it('Should be able to update my avatar with a gif', async function () { const fixture = 'avatar.gif' - await updateMyAvatar({ - url: server.url, - accessToken: accessTokenUser, - fixture - }) - - const res = await getMyUserInformation(server.url, accessTokenUser) - const user = res.body + await server.usersCommand.updateMyAvatar({ token: accessTokenUser, fixture }) + const user = await server.usersCommand.getMyInfo({ token: accessTokenUser }) await testImage(server.url, 'avatar-resized', user.account.avatar.path, '.gif') }) @@ -655,29 +580,17 @@ describe('Test users', function () { for (const extension of [ '.png', '.gif' ]) { const fixture = 'avatar' + extension - await updateMyAvatar({ - url: server.url, - accessToken: accessTokenUser, - fixture - }) - - const res = await getMyUserInformation(server.url, accessTokenUser) - const user = res.body + await server.usersCommand.updateMyAvatar({ token: accessTokenUser, fixture }) + const user = await server.usersCommand.getMyInfo({ token: accessTokenUser }) await testImage(server.url, 'avatar-resized', user.account.avatar.path, extension) } }) it('Should be able to update my display name', async function () { - await updateMyUser({ - url: server.url, - accessToken: accessTokenUser, - displayName: 'new display name' - }) - - const res = await getMyUserInformation(server.url, accessTokenUser) - const user = res.body + await server.usersCommand.updateMe({ token: accessTokenUser, displayName: 'new display name' }) + const user = await server.usersCommand.getMyInfo({ token: accessTokenUser }) expect(user.username).to.equal('user_1') expect(user.email).to.equal('updated@example.com') expect(user.nsfwPolicy).to.equal('do_not_list') @@ -688,15 +601,9 @@ describe('Test users', function () { }) it('Should be able to update my description', async function () { - await updateMyUser({ - url: server.url, - accessToken: accessTokenUser, - description: 'my super description updated' - }) - - const res = await getMyUserInformation(server.url, accessTokenUser) - const user: User = res.body + await server.usersCommand.updateMe({ token: accessTokenUser, description: 'my super description updated' }) + const user = await server.usersCommand.getMyInfo({ token: accessTokenUser }) expect(user.username).to.equal('user_1') expect(user.email).to.equal('updated@example.com') expect(user.nsfwPolicy).to.equal('do_not_list') @@ -710,30 +617,21 @@ describe('Test users', function () { it('Should be able to update my theme', async function () { for (const theme of [ 'background-red', 'default', 'instance-default' ]) { - await updateMyUser({ - url: server.url, - accessToken: accessTokenUser, - theme - }) + await server.usersCommand.updateMe({ token: accessTokenUser, theme }) - const res = await getMyUserInformation(server.url, accessTokenUser) - const body: User = res.body - - expect(body.theme).to.equal(theme) + const user = await server.usersCommand.getMyInfo({ token: accessTokenUser }) + expect(user.theme).to.equal(theme) } }) it('Should be able to update my modal preferences', async function () { - await updateMyUser({ - url: server.url, - accessToken: accessTokenUser, + await server.usersCommand.updateMe({ + token: accessTokenUser, noInstanceConfigWarningModal: true, noWelcomeModal: true }) - const res = await getMyUserInformation(server.url, accessTokenUser) - const user: User = res.body - + const user = await server.usersCommand.getMyInfo({ token: accessTokenUser }) expect(user.noWelcomeModal).to.be.true expect(user.noInstanceConfigWarningModal).to.be.true }) @@ -741,10 +639,9 @@ describe('Test users', function () { describe('Updating another user', function () { it('Should be able to update another user', async function () { - await updateUser({ - url: server.url, + await server.usersCommand.update({ userId, - accessToken, + token: accessToken, email: 'updated2@example.com', emailVerified: true, videoQuota: 42, @@ -753,8 +650,7 @@ describe('Test users', function () { pluginAuth: 'toto' }) - const res = await getUserInformation(server.url, accessToken, userId) - const user = res.body as User + const user = await server.usersCommand.get({ token: accessToken, userId }) expect(user.username).to.equal('user_1') expect(user.email).to.equal('updated2@example.com') @@ -768,28 +664,22 @@ describe('Test users', function () { }) it('Should reset the auth plugin', async function () { - await updateUser({ url: server.url, userId, accessToken, pluginAuth: null }) + await server.usersCommand.update({ userId, token: accessToken, pluginAuth: null }) - const res = await getUserInformation(server.url, accessToken, userId) - const user = res.body as User + const user = await server.usersCommand.get({ token: accessToken, userId }) expect(user.pluginAuth).to.be.null }) it('Should have removed the user token', async function () { - await getMyUserVideoQuotaUsed(server.url, accessTokenUser, HttpStatusCode.UNAUTHORIZED_401) + await server.usersCommand.getMyQuotaUsed({ token: accessTokenUser, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) accessTokenUser = await server.loginCommand.getAccessToken(user) }) it('Should be able to update another user password', async function () { - await updateUser({ - url: server.url, - userId, - accessToken, - password: 'password updated' - }) + await server.usersCommand.update({ userId, token: accessToken, password: 'password updated' }) - await getMyUserVideoQuotaUsed(server.url, accessTokenUser, HttpStatusCode.UNAUTHORIZED_401) + await server.usersCommand.getMyQuotaUsed({ token: accessTokenUser, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) await server.loginCommand.login({ user, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) @@ -806,7 +696,7 @@ describe('Test users', function () { describe('Remove a user', function () { it('Should be able to remove this user', async function () { - await removeUser(server.url, userId, accessToken) + await server.usersCommand.remove({ userId, token: accessToken }) }) it('Should not be able to login with this user', async function () { @@ -830,7 +720,7 @@ describe('Test users', function () { const user = { displayName: 'super user 15', username: 'user_15', password: 'my super password' } const channel = { name: 'my_user_15_channel', displayName: 'my channel rocks' } - await registerUserWithChannel({ url: server.url, user, channel }) + await server.usersCommand.register({ ...user, channel }) }) it('Should be able to login with this registered user', async function () { @@ -843,16 +733,12 @@ describe('Test users', function () { }) it('Should have the correct display name', async function () { - const res = await getMyUserInformation(server.url, user15AccessToken) - const user: User = res.body - + const user = await server.usersCommand.getMyInfo({ token: user15AccessToken }) expect(user.account.displayName).to.equal('super user 15') }) it('Should have the correct video quota', async function () { - const res = await getMyUserInformation(server.url, user15AccessToken) - const user = res.body - + const user = await server.usersCommand.getMyInfo({ token: user15AccessToken }) expect(user.videoQuota).to.equal(5 * 1024 * 1024) }) @@ -864,15 +750,15 @@ describe('Test users', function () { it('Should remove me', async function () { { - const res = await getUsersList(server.url, server.accessToken) - expect(res.body.data.find(u => u.username === 'user_15')).to.not.be.undefined + const { data } = await server.usersCommand.list() + expect(data.find(u => u.username === 'user_15')).to.not.be.undefined } - await deleteMe(server.url, user15AccessToken) + await server.usersCommand.deleteMe({ token: user15AccessToken }) { - const res = await getUsersList(server.url, server.accessToken) - expect(res.body.data.find(u => u.username === 'user_15')).to.be.undefined + const { data } = await server.usersCommand.list() + expect(data.find(u => u.username === 'user_15')).to.be.undefined } }) }) @@ -886,49 +772,40 @@ describe('Test users', function () { } it('Should block a user', async function () { - const resUser = await createUser({ - url: server.url, - accessToken: server.accessToken, - username: user16.username, - password: user16.password - }) - user16Id = resUser.body.user.id + const user = await server.usersCommand.create({ ...user16 }) + user16Id = user.id user16AccessToken = await server.loginCommand.getAccessToken(user16) - await getMyUserInformation(server.url, user16AccessToken, HttpStatusCode.OK_200) - await blockUser(server.url, user16Id, server.accessToken) + await server.usersCommand.getMyInfo({ token: user16AccessToken, expectedStatus: HttpStatusCode.OK_200 }) + await server.usersCommand.banUser({ userId: user16Id }) - await getMyUserInformation(server.url, user16AccessToken, HttpStatusCode.UNAUTHORIZED_401) + await server.usersCommand.getMyInfo({ token: user16AccessToken, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) await server.loginCommand.login({ user: user16, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) it('Should search user by banned status', async function () { { - const res = await getUsersListPaginationAndSort(server.url, server.accessToken, 0, 2, 'createdAt', undefined, true) - const users = res.body.data as User[] + const { data, total } = await server.usersCommand.list({ start: 0, count: 2, sort: 'createdAt', blocked: true }) + expect(total).to.equal(1) + expect(data.length).to.equal(1) - expect(res.body.total).to.equal(1) - expect(users.length).to.equal(1) - - expect(users[0].username).to.equal(user16.username) + expect(data[0].username).to.equal(user16.username) } { - const res = await getUsersListPaginationAndSort(server.url, server.accessToken, 0, 2, 'createdAt', undefined, false) - const users = res.body.data as User[] - - expect(res.body.total).to.equal(1) - expect(users.length).to.equal(1) + const { data, total } = await server.usersCommand.list({ start: 0, count: 2, sort: 'createdAt', blocked: false }) + expect(total).to.equal(1) + expect(data.length).to.equal(1) - expect(users[0].username).to.not.equal(user16.username) + expect(data[0].username).to.not.equal(user16.username) } }) it('Should unblock a user', async function () { - await unblockUser(server.url, user16Id, server.accessToken) + await server.usersCommand.unbanUser({ userId: user16Id }) user16AccessToken = await server.loginCommand.getAccessToken(user16) - await getMyUserInformation(server.url, user16AccessToken, HttpStatusCode.OK_200) + await server.usersCommand.getMyInfo({ token: user16AccessToken, expectedStatus: HttpStatusCode.OK_200 }) }) }) @@ -941,19 +818,12 @@ describe('Test users', function () { username: 'user_17', password: 'my super password' } - const resUser = await createUser({ - url: server.url, - accessToken: server.accessToken, - username: user17.username, - password: user17.password - }) + const created = await server.usersCommand.create({ ...user17 }) - user17Id = resUser.body.user.id + user17Id = created.id user17AccessToken = await server.loginCommand.getAccessToken(user17) - const res = await getUserInformation(server.url, server.accessToken, user17Id, true) - const user: User = res.body - + const user = await server.usersCommand.get({ userId: user17Id, withStats: true }) expect(user.videosCount).to.equal(0) expect(user.videoCommentsCount).to.equal(0) expect(user.abusesCount).to.equal(0) @@ -969,9 +839,7 @@ describe('Test users', function () { const res1 = await getVideosList(server.url) videoId = res1.body.data.find(video => video.name === videoAttributes.name).id - const res2 = await getUserInformation(server.url, server.accessToken, user17Id, true) - const user: User = res2.body - + const user = await server.usersCommand.get({ userId: user17Id, withStats: true }) expect(user.videosCount).to.equal(1) }) @@ -979,9 +847,7 @@ describe('Test users', function () { const text = 'super comment' await server.commentsCommand.createThread({ token: user17AccessToken, videoId, text }) - const res = await getUserInformation(server.url, server.accessToken, user17Id, true) - const user: User = res.body - + const user = await server.usersCommand.get({ userId: user17Id, withStats: true }) expect(user.videoCommentsCount).to.equal(1) }) @@ -992,17 +858,13 @@ describe('Test users', function () { const body1 = await server.abusesCommand.getAdminList() const abuseId = body1.data[0].id - const res2 = await getUserInformation(server.url, server.accessToken, user17Id, true) - const user2: User = res2.body - + const user2 = await server.usersCommand.get({ userId: user17Id, withStats: true }) expect(user2.abusesCount).to.equal(1) // number of incriminations expect(user2.abusesCreatedCount).to.equal(1) // number of reports created await server.abusesCommand.update({ abuseId, body: { state: AbuseState.ACCEPTED } }) - const res3 = await getUserInformation(server.url, server.accessToken, user17Id, true) - const user3: User = res3.body - + const user3 = await server.usersCommand.get({ userId: user17Id, withStats: true }) expect(user3.abusesAcceptedCount).to.equal(1) // number of reports created accepted }) }) diff --git a/server/tests/api/videos/multiple-servers.ts b/server/tests/api/videos/multiple-servers.ts index 740314bfd..169bb2e23 100644 --- a/server/tests/api/videos/multiple-servers.ts +++ b/server/tests/api/videos/multiple-servers.ts @@ -10,7 +10,6 @@ import { checkVideoFilesWereRemoved, cleanupTests, completeVideoCheck, - createUser, dateIsValid, doubleFollow, flushAndRunMultipleServers, @@ -153,7 +152,7 @@ describe('Test multiple servers', function () { username: 'user1', password: 'super_password' } - await createUser({ url: servers[1].url, accessToken: servers[1].accessToken, username: user.username, password: user.password }) + await servers[1].usersCommand.create({ username: user.username, password: user.password }) const userAccessToken = await servers[1].loginCommand.getAccessToken(user) const videoAttributes = { diff --git a/server/tests/api/videos/resumable-upload.ts b/server/tests/api/videos/resumable-upload.ts index 5845efc86..642c115d0 100644 --- a/server/tests/api/videos/resumable-upload.ts +++ b/server/tests/api/videos/resumable-upload.ts @@ -9,15 +9,13 @@ import { buildAbsoluteFixturePath, cleanupTests, flushAndRunServer, - getMyUserInformation, prepareResumableUpload, sendResumableChunks, ServerInfo, setAccessTokensToServers, - setDefaultVideoChannel, - updateUser + setDefaultVideoChannel } from '@shared/extra-utils' -import { MyUser, VideoPrivacy } from '@shared/models' +import { VideoPrivacy } from '@shared/models' const expect = chai.expect @@ -109,15 +107,10 @@ describe('Test resumable upload', function () { await setAccessTokensToServers([ server ]) await setDefaultVideoChannel([ server ]) - const res = await getMyUserInformation(server.url, server.accessToken) - rootId = (res.body as MyUser).id + const body = await server.usersCommand.getMyInfo() + rootId = body.id - await updateUser({ - url: server.url, - userId: rootId, - accessToken: server.accessToken, - videoQuota: 10_000_000 - }) + await server.usersCommand.update({ userId: rootId, videoQuota: 10_000_000 }) }) describe('Directory cleaning', function () { diff --git a/server/tests/api/videos/video-change-ownership.ts b/server/tests/api/videos/video-change-ownership.ts index 17c738e6f..b0bbd5a0d 100644 --- a/server/tests/api/videos/video-change-ownership.ts +++ b/server/tests/api/videos/video-change-ownership.ts @@ -6,11 +6,9 @@ import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-c import { ChangeOwnershipCommand, cleanupTests, - createUser, doubleFollow, flushAndRunMultipleServers, flushAndRunServer, - getMyUserInformation, getVideo, getVideosList, ServerInfo, @@ -19,21 +17,15 @@ import { uploadVideo } from '../../../../shared/extra-utils' import { waitJobs } from '../../../../shared/extra-utils/server/jobs' -import { User } from '../../../../shared/models/users' import { VideoDetails, VideoPrivacy } from '../../../../shared/models/videos' const expect = chai.expect describe('Test video change ownership - nominal', function () { let servers: ServerInfo[] = [] - const firstUser = { - username: 'first', - password: 'My great password' - } - const secondUser = { - username: 'second', - password: 'My other password' - } + + const firstUser = 'first' + const secondUser = 'second' let firstUserToken = '' let firstUserChannelId: number @@ -65,35 +57,17 @@ describe('Test video change ownership - nominal', function () { } }) - const videoQuota = 42000000 - await createUser({ - url: servers[0].url, - accessToken: servers[0].accessToken, - username: firstUser.username, - password: firstUser.password, - videoQuota: videoQuota - }) - await createUser({ - url: servers[0].url, - accessToken: servers[0].accessToken, - username: secondUser.username, - password: secondUser.password, - videoQuota: videoQuota - }) - - firstUserToken = await servers[0].loginCommand.getAccessToken(firstUser) - secondUserToken = await servers[0].loginCommand.getAccessToken(secondUser) + firstUserToken = await servers[0].usersCommand.generateUserAndToken(firstUser) + secondUserToken = await servers[0].usersCommand.generateUserAndToken(secondUser) { - const res = await getMyUserInformation(servers[0].url, firstUserToken) - const firstUserInformation: User = res.body - firstUserChannelId = firstUserInformation.videoChannels[0].id + const { videoChannels } = await servers[0].usersCommand.getMyInfo({ token: firstUserToken }) + firstUserChannelId = videoChannels[0].id } { - const res = await getMyUserInformation(servers[0].url, secondUserToken) - const secondUserInformation: User = res.body - secondUserChannelId = secondUserInformation.videoChannels[0].id + const { videoChannels } = await servers[0].usersCommand.getMyInfo({ token: secondUserToken }) + secondUserChannelId = videoChannels[0].id } { @@ -140,7 +114,7 @@ describe('Test video change ownership - nominal', function () { it('Should send a request to change ownership of a video', async function () { this.timeout(15000) - await command.create({ token: firstUserToken, videoId: servers[0].video.id, username: secondUser.username }) + await command.create({ token: firstUserToken, videoId: servers[0].video.id, username: secondUser }) }) it('Should only return a request to change ownership for the second user', async function () { @@ -166,7 +140,7 @@ describe('Test video change ownership - nominal', function () { it('Should accept the same change ownership request without crashing', async function () { this.timeout(10000) - await command.create({ token: firstUserToken, videoId: servers[0].video.id, username: secondUser.username }) + await command.create({ token: firstUserToken, videoId: servers[0].video.id, username: secondUser }) }) it('Should not create multiple change ownership requests while one is waiting', async function () { @@ -194,7 +168,7 @@ describe('Test video change ownership - nominal', function () { it('Should send a new request to change ownership of a video', async function () { this.timeout(15000) - await command.create({ token: firstUserToken, videoId: servers[0].video.id, username: secondUser.username }) + await command.create({ token: firstUserToken, videoId: servers[0].video.id, username: secondUser }) }) it('Should return two requests to change ownership for the second user', async function () { @@ -251,7 +225,7 @@ describe('Test video change ownership - nominal', function () { it('Should send a request to change ownership of a live', async function () { this.timeout(15000) - await command.create({ token: firstUserToken, videoId: liveId, username: secondUser.username }) + await command.create({ token: firstUserToken, videoId: liveId, username: secondUser }) const body = await command.list({ token: secondUserToken }) @@ -286,14 +260,9 @@ describe('Test video change ownership - nominal', function () { describe('Test video change ownership - quota too small', function () { let server: ServerInfo - const firstUser = { - username: 'first', - password: 'My great password' - } - const secondUser = { - username: 'second', - password: 'My other password' - } + const firstUser = 'first' + const secondUser = 'second' + let firstUserToken = '' let secondUserToken = '' let lastRequestId: number @@ -305,24 +274,9 @@ describe('Test video change ownership - quota too small', function () { server = await flushAndRunServer(1) await setAccessTokensToServers([ server ]) - const videoQuota = 42000000 - const limitedVideoQuota = 10 - await createUser({ - url: server.url, - accessToken: server.accessToken, - username: firstUser.username, - password: firstUser.password, - videoQuota: videoQuota - }) - await createUser({ - url: server.url, - accessToken: server.accessToken, - username: secondUser.username, - password: secondUser.password, - videoQuota: limitedVideoQuota - }) + await server.usersCommand.create({ username: secondUser, videoQuota: 10 }) - firstUserToken = await server.loginCommand.getAccessToken(firstUser) + firstUserToken = await server.usersCommand.generateUserAndToken(firstUser) secondUserToken = await server.loginCommand.getAccessToken(secondUser) // Upload some videos on the server @@ -345,7 +299,7 @@ describe('Test video change ownership - quota too small', function () { it('Should send a request to change ownership of a video', async function () { this.timeout(15000) - await server.changeOwnershipCommand.create({ token: firstUserToken, videoId: server.video.id, username: secondUser.username }) + await server.changeOwnershipCommand.create({ token: firstUserToken, videoId: server.video.id, username: secondUser }) }) it('Should only return a request to change ownership for the second user', async function () { @@ -371,9 +325,8 @@ describe('Test video change ownership - quota too small', function () { it('Should not be possible to accept the change of ownership from second user because of exceeded quota', async function () { this.timeout(10000) - const secondUserInformationResponse = await getMyUserInformation(server.url, secondUserToken) - const secondUserInformation: User = secondUserInformationResponse.body - const channelId = secondUserInformation.videoChannels[0].id + const { videoChannels } = await server.usersCommand.getMyInfo({ token: secondUserToken }) + const channelId = videoChannels[0].id await server.changeOwnershipCommand.accept({ token: secondUserToken, diff --git a/server/tests/api/videos/video-channels.ts b/server/tests/api/videos/video-channels.ts index 83645640c..2e57cbbff 100644 --- a/server/tests/api/videos/video-channels.ts +++ b/server/tests/api/videos/video-channels.ts @@ -6,21 +6,22 @@ import { basename } from 'path' import { ACTOR_IMAGES_SIZE } from '@server/initializers/constants' import { cleanupTests, - createUser, doubleFollow, flushAndRunMultipleServers, getVideo, getVideoChannelVideos, + ServerInfo, + setAccessTokensToServers, setDefaultVideoChannel, testFileExistsOrNot, testImage, updateVideo, uploadVideo, - wait -} from '../../../../shared/extra-utils' -import { getMyUserInformation, ServerInfo, setAccessTokensToServers, viewVideo } from '../../../../shared/extra-utils/index' -import { waitJobs } from '../../../../shared/extra-utils/server/jobs' -import { User, Video, VideoChannel, VideoDetails } from '../../../../shared/index' + viewVideo, + wait, + waitJobs +} from '@shared/extra-utils' +import { User, Video, VideoChannel, VideoDetails } from '@shared/models' const expect = chai.expect @@ -85,8 +86,7 @@ describe('Test video channels', function () { }) it('Should have two video channels when getting my information', async () => { - const res = await getMyUserInformation(servers[0].url, servers[0].accessToken) - userInfo = res.body + userInfo = await servers[0].usersCommand.getMyInfo() expect(userInfo.videoChannels).to.be.an('array') expect(userInfo.videoChannels).to.have.lengthOf(2) @@ -389,11 +389,11 @@ describe('Test video channels', function () { } { - await createUser({ url: servers[0].url, accessToken: servers[0].accessToken, username: 'toto', password: 'password' }) + await servers[0].usersCommand.create({ username: 'toto', password: 'password' }) const accessToken = await servers[0].loginCommand.getAccessToken({ username: 'toto', password: 'password' }) - const res = await getMyUserInformation(servers[0].url, accessToken) - const videoChannel = res.body.videoChannels[0] + const { videoChannels } = await servers[0].usersCommand.getMyInfo({ token: accessToken }) + const videoChannel = videoChannels[0] expect(videoChannel.name).to.match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/) } }) diff --git a/server/tests/api/videos/video-comments.ts b/server/tests/api/videos/video-comments.ts index f9bd23646..266824d58 100644 --- a/server/tests/api/videos/video-comments.ts +++ b/server/tests/api/videos/video-comments.ts @@ -5,13 +5,11 @@ import * as chai from 'chai' import { cleanupTests, CommentsCommand, - createUser, dateIsValid, flushAndRunServer, ServerInfo, setAccessTokensToServers, testImage, - updateMyAvatar, uploadVideo } from '@shared/extra-utils' @@ -39,19 +37,9 @@ describe('Test video comments', function () { videoUUID = res.body.video.uuid videoId = res.body.video.id - await updateMyAvatar({ - url: server.url, - accessToken: server.accessToken, - fixture: 'avatar.png' - }) + await server.usersCommand.updateMyAvatar({ fixture: 'avatar.png' }) - await createUser({ - url: server.url, - accessToken: server.accessToken, - username: 'user1', - password: 'password' - }) - userAccessTokenServer1 = await server.loginCommand.getAccessToken('user1', 'password') + userAccessTokenServer1 = await server.usersCommand.generateUserAndToken('user1') command = server.commentsCommand }) diff --git a/server/tests/api/videos/video-imports.ts b/server/tests/api/videos/video-imports.ts index f6ae8cab1..052c052b4 100644 --- a/server/tests/api/videos/video-imports.ts +++ b/server/tests/api/videos/video-imports.ts @@ -7,7 +7,6 @@ import { cleanupTests, doubleFollow, flushAndRunMultipleServers, - getMyUserInformation, getMyVideos, getVideo, getVideosList, @@ -97,13 +96,13 @@ describe('Test video imports', function () { await setAccessTokensToServers(servers) { - const res = await getMyUserInformation(servers[0].url, servers[0].accessToken) - channelIdServer1 = res.body.videoChannels[0].id + const { videoChannels } = await servers[0].usersCommand.getMyInfo() + channelIdServer1 = videoChannels[0].id } { - const res = await getMyUserInformation(servers[1].url, servers[1].accessToken) - channelIdServer2 = res.body.videoChannels[0].id + const { videoChannels } = await servers[1].usersCommand.getMyInfo() + channelIdServer2 = videoChannels[0].id } await doubleFollow(servers[0], servers[1]) diff --git a/server/tests/api/videos/video-nsfw.ts b/server/tests/api/videos/video-nsfw.ts index a30b11ace..9dc26fca6 100644 --- a/server/tests/api/videos/video-nsfw.ts +++ b/server/tests/api/videos/video-nsfw.ts @@ -4,20 +4,17 @@ import 'mocha' import * as chai from 'chai' import { cleanupTests, - createUser, flushAndRunServer, getAccountVideos, - getMyUserInformation, getMyVideos, getVideoChannelVideos, getVideosList, getVideosListWithToken, ServerInfo, setAccessTokensToServers, - updateMyUser, uploadVideo } from '@shared/extra-utils' -import { BooleanBothQuery, CustomConfig, ResultList, User, Video, VideosOverview } from '@shared/models' +import { BooleanBothQuery, CustomConfig, ResultList, Video, VideosOverview } from '@shared/models' const expect = chai.expect @@ -32,8 +29,7 @@ describe('Test video NSFW policy', function () { let customConfig: CustomConfig async function getVideosFunctions (token?: string, query: { nsfw?: BooleanBothQuery } = {}) { - const res = await getMyUserInformation(server.url, server.accessToken) - const user: User = res.body + const user = await server.usersCommand.getMyInfo() const videoChannelName = user.videoChannels[0].name const accountName = user.account.name + '@' + user.account.host const hasQuery = Object.keys(query).length !== 0 @@ -148,13 +144,11 @@ describe('Test video NSFW policy', function () { it('Should create a user having the default nsfw policy', async function () { const username = 'user1' const password = 'my super password' - await createUser({ url: server.url, accessToken: server.accessToken, username: username, password: password }) + await server.usersCommand.create({ username: username, password: password }) userAccessToken = await server.loginCommand.getAccessToken({ username, password }) - const res = await getMyUserInformation(server.url, userAccessToken) - const user = res.body - + const user = await server.usersCommand.getMyInfo({ token: userAccessToken }) expect(user.nsfwPolicy).to.equal('blur') }) @@ -173,11 +167,7 @@ describe('Test video NSFW policy', function () { }) it('Should display NSFW videos with display user NSFW policy', async function () { - await updateMyUser({ - url: server.url, - accessToken: server.accessToken, - nsfwPolicy: 'display' - }) + await server.usersCommand.updateMe({ nsfwPolicy: 'display' }) for (const body of await getVideosFunctions(server.accessToken)) { expect(body.total).to.equal(2) @@ -190,11 +180,7 @@ describe('Test video NSFW policy', function () { }) it('Should not display NSFW videos with do_not_list user NSFW policy', async function () { - await updateMyUser({ - url: server.url, - accessToken: server.accessToken, - nsfwPolicy: 'do_not_list' - }) + await server.usersCommand.updateMe({ nsfwPolicy: 'do_not_list' }) for (const body of await getVideosFunctions(server.accessToken)) { expect(body.total).to.equal(1) diff --git a/server/tests/api/videos/video-playlists.ts b/server/tests/api/videos/video-playlists.ts index 38133e2ce..e57d86c14 100644 --- a/server/tests/api/videos/video-playlists.ts +++ b/server/tests/api/videos/video-playlists.ts @@ -6,13 +6,9 @@ import { HttpStatusCode } from '@shared/core-utils' import { checkPlaylistFilesWereRemoved, cleanupTests, - createUser, doubleFollow, flushAndRunMultipleServers, - generateUserAccessToken, - getMyUserInformation, PlaylistsCommand, - removeUser, ServerInfo, setAccessTokensToServers, setDefaultVideoChannel, @@ -24,7 +20,6 @@ import { waitJobs } from '@shared/extra-utils' import { - User, VideoPlaylist, VideoPlaylistCreateResult, VideoPlaylistElementType, @@ -113,15 +108,7 @@ describe('Test video playlists', function () { nsfwVideoServer1 = (await uploadVideoAndGetId({ server: servers[0], videoName: 'NSFW video', nsfw: true })).id - { - await createUser({ - url: servers[0].url, - accessToken: servers[0].accessToken, - username: 'user1', - password: 'password' - }) - userTokenServer1 = await servers[0].loginCommand.getAccessToken('user1', 'password') - } + userTokenServer1 = await servers[0].usersCommand.generateUserAndToken('user1') await waitJobs(servers) }) @@ -165,7 +152,7 @@ describe('Test video playlists', function () { }) it('Should get private playlist for a classic user', async function () { - const token = await generateUserAccessToken(servers[0], 'toto') + const token = await servers[0].usersCommand.generateUserAndToken('toto') const body = await commands[0].listByAccount({ token, handle: 'toto' }) @@ -1118,19 +1105,10 @@ describe('Test video playlists', function () { it('Should delete an account and delete its playlists', async function () { this.timeout(30000) - const user = { username: 'user_1', password: 'password' } - const res = await createUser({ - url: servers[0].url, - accessToken: servers[0].accessToken, - username: user.username, - password: user.password - }) - - const userId = res.body.user.id - const userAccessToken = await servers[0].loginCommand.getAccessToken(user) + const { userId, token } = await servers[0].usersCommand.generate('user_1') - const resChannel = await getMyUserInformation(servers[0].url, userAccessToken) - const userChannel = (resChannel.body as User).videoChannels[0] + const { videoChannels } = await servers[0].usersCommand.getMyInfo({ token }) + const userChannel = videoChannels[0] await commands[0].create({ attributes: { @@ -1152,7 +1130,7 @@ describe('Test video playlists', function () { } } - await removeUser(servers[0].url, userId, servers[0].accessToken) + await servers[0].usersCommand.remove({ userId }) await waitJobs(servers) { diff --git a/server/tests/api/videos/video-privacy.ts b/server/tests/api/videos/video-privacy.ts index f831dd8a9..4e349e350 100644 --- a/server/tests/api/videos/video-privacy.ts +++ b/server/tests/api/videos/video-privacy.ts @@ -5,7 +5,6 @@ import * as chai from 'chai' import { HttpStatusCode } from '@shared/core-utils' import { cleanupTests, - createUser, doubleFollow, flushAndRunServer, getMyVideos, @@ -125,7 +124,7 @@ describe('Test video privacy', function () { username: 'hello', password: 'super password' } - await createUser({ url: servers[0].url, accessToken: servers[0].accessToken, username: user.username, password: user.password }) + await servers[0].usersCommand.create({ username: user.username, password: user.password }) anotherUserToken = await servers[0].loginCommand.getAccessToken(user) await getVideoWithToken(servers[0].url, anotherUserToken, privateVideoUUID, HttpStatusCode.FORBIDDEN_403) diff --git a/server/tests/api/videos/videos-filter.ts b/server/tests/api/videos/videos-filter.ts index 519dad646..4aa00cfc4 100644 --- a/server/tests/api/videos/videos-filter.ts +++ b/server/tests/api/videos/videos-filter.ts @@ -5,7 +5,6 @@ import * as chai from 'chai' import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' import { cleanupTests, - createUser, doubleFollow, flushAndRunMultipleServers, makeGetRequest, @@ -60,17 +59,7 @@ describe('Test videos filter', function () { for (const server of servers) { const moderator = { username: 'moderator', password: 'my super password' } - await createUser( - { - url: server.url, - accessToken: server.accessToken, - username: moderator.username, - password: moderator.password, - videoQuota: undefined, - videoQuotaDaily: undefined, - role: UserRole.MODERATOR - } - ) + await server.usersCommand.create({ username: moderator.username, password: moderator.password, role: UserRole.MODERATOR }) server['moderatorAccessToken'] = await server.loginCommand.getAccessToken(moderator) await uploadVideo(server.url, server.accessToken, { name: 'public ' + server.serverNumber }) diff --git a/server/tests/api/videos/videos-history.ts b/server/tests/api/videos/videos-history.ts index 256271bd0..aa0623f7d 100644 --- a/server/tests/api/videos/videos-history.ts +++ b/server/tests/api/videos/videos-history.ts @@ -5,7 +5,6 @@ import * as chai from 'chai' import { HttpStatusCode } from '@shared/core-utils' import { cleanupTests, - createUser, flushAndRunServer, getVideosListWithToken, getVideoWithToken, @@ -14,7 +13,6 @@ import { reRunServer, ServerInfo, setAccessTokensToServers, - updateMyUser, uploadVideo, wait } from '@shared/extra-utils' @@ -59,7 +57,7 @@ describe('Test videos history', function () { username: 'user_1', password: 'super password' } - await createUser({ url: server.url, accessToken: server.accessToken, username: user.username, password: user.password }) + await server.usersCommand.create({ username: user.username, password: user.password }) userAccessToken = await server.loginCommand.getAccessToken(user) }) @@ -174,9 +172,7 @@ describe('Test videos history', function () { }) it('Should disable videos history', async function () { - await updateMyUser({ - url: server.url, - accessToken: server.accessToken, + await server.usersCommand.updateMe({ videosHistoryEnabled: false }) @@ -184,9 +180,7 @@ describe('Test videos history', function () { }) it('Should re-enable videos history', async function () { - await updateMyUser({ - url: server.url, - accessToken: server.accessToken, + await server.usersCommand.updateMe({ videosHistoryEnabled: true }) diff --git a/server/tests/api/videos/videos-overview.ts b/server/tests/api/videos/videos-overview.ts index ccbc6f4a4..a2da2eaef 100644 --- a/server/tests/api/videos/videos-overview.ts +++ b/server/tests/api/videos/videos-overview.ts @@ -2,15 +2,7 @@ import 'mocha' import * as chai from 'chai' -import { - cleanupTests, - flushAndRunServer, - generateUserAccessToken, - ServerInfo, - setAccessTokensToServers, - uploadVideo, - wait -} from '@shared/extra-utils' +import { cleanupTests, flushAndRunServer, ServerInfo, setAccessTokensToServers, uploadVideo, wait } from '@shared/extra-utils' import { VideosOverview } from '@shared/models' const expect = chai.expect @@ -112,7 +104,7 @@ describe('Test a videos overview', function () { }) it('Should hide muted accounts', async function () { - const token = await generateUserAccessToken(server, 'choco') + const token = await server.usersCommand.generateUserAndToken('choco') await server.blocklistCommand.addToMyBlocklist({ token, account: 'root@' + server.host }) diff --git a/server/tests/cli/peertube.ts b/server/tests/cli/peertube.ts index e055b4684..a0c149ac0 100644 --- a/server/tests/cli/peertube.ts +++ b/server/tests/cli/peertube.ts @@ -8,11 +8,9 @@ import { buildAbsoluteFixturePath, cleanupTests, CLICommand, - createUser, doubleFollow, flushAndRunServer, getLocalIdByUUID, - getMyUserInformation, getVideo, getVideosList, ImportsCommand, @@ -38,7 +36,7 @@ describe('Test CLI wrapper', function () { server = await flushAndRunServer(1) await setAccessTokensToServers([ server ]) - await createUser({ url: server.url, accessToken: server.accessToken, username: 'user_1', password: 'super_password' }) + await server.usersCommand.create({ username: 'user_1', password: 'super_password' }) userAccessToken = await server.loginCommand.getAccessToken({ username: 'user_1', password: 'super_password' }) @@ -56,8 +54,8 @@ describe('Test CLI wrapper', function () { const stdout = await cliCommand.execWithEnv(`${cmd} token --url ${server.url} --username user_1 --password super_password`) const token = stdout.trim() - const res = await getMyUserInformation(server.url, token) - expect(res.body.username).to.equal('user_1') + const body = await server.usersCommand.getMyInfo({ token }) + expect(body.username).to.equal('user_1') }) it('Should display no selected instance', async function () { diff --git a/server/tests/cli/prune-storage.ts b/server/tests/cli/prune-storage.ts index 68a59a41d..b45049964 100644 --- a/server/tests/cli/prune-storage.ts +++ b/server/tests/cli/prune-storage.ts @@ -16,7 +16,6 @@ import { ServerInfo, setAccessTokensToServers, setDefaultVideoChannel, - updateMyAvatar, uploadVideo, wait, waitJobs @@ -73,7 +72,7 @@ describe('Test prune storage scripts', function () { await uploadVideo(server.url, server.accessToken, { name: 'video 1' }) await uploadVideo(server.url, server.accessToken, { name: 'video 2' }) - await updateMyAvatar({ url: server.url, accessToken: server.accessToken, fixture: 'avatar.png' }) + await server.usersCommand.updateMyAvatar({ fixture: 'avatar.png' }) await server.playlistsCommand.create({ attributes: { diff --git a/server/tests/cli/reset-password.ts b/server/tests/cli/reset-password.ts index a5f958bf7..5e1e1c2af 100644 --- a/server/tests/cli/reset-password.ts +++ b/server/tests/cli/reset-password.ts @@ -1,5 +1,5 @@ import 'mocha' -import { cleanupTests, CLICommand, createUser, flushAndRunServer, ServerInfo, setAccessTokensToServers } from '../../../shared/extra-utils' +import { cleanupTests, CLICommand, flushAndRunServer, ServerInfo, setAccessTokensToServers } from '../../../shared/extra-utils' describe('Test reset password scripts', function () { let server: ServerInfo @@ -9,7 +9,7 @@ describe('Test reset password scripts', function () { server = await flushAndRunServer(1) await setAccessTokensToServers([ server ]) - await createUser({ url: server.url, accessToken: server.accessToken, username: 'user_1', password: 'super password' }) + await server.usersCommand.create({ username: 'user_1', password: 'super password' }) }) it('Should change the user password from CLI', async function () { diff --git a/server/tests/cli/update-host.ts b/server/tests/cli/update-host.ts index e986a04f2..b857fcf28 100644 --- a/server/tests/cli/update-host.ts +++ b/server/tests/cli/update-host.ts @@ -4,7 +4,6 @@ import 'mocha' import { expect } from 'chai' import { cleanupTests, - createUser, flushAndRunServer, getVideo, getVideosList, @@ -41,7 +40,7 @@ describe('Test update host scripts', function () { await uploadVideo(server.url, server.accessToken, videoAttributes) // Create a user - await createUser({ url: server.url, accessToken: server.accessToken, username: 'toto', password: 'coucou' }) + await server.usersCommand.create({ username: 'toto', password: 'coucou' }) // Create channel const videoChannel = { diff --git a/server/tests/client.ts b/server/tests/client.ts index 1bdb2eb64..96403da37 100644 --- a/server/tests/client.ts +++ b/server/tests/client.ts @@ -15,7 +15,6 @@ import { ServerInfo, setAccessTokensToServers, setDefaultVideoChannel, - updateMyUser, uploadVideo, waitJobs } from '../../shared/extra-utils' @@ -96,7 +95,7 @@ describe('Test a client controllers', function () { // Account - await updateMyUser({ url: servers[0].url, accessToken: servers[0].accessToken, description: 'my account description' }) + await servers[0].usersCommand.updateMe({ description: 'my account description' }) account = await servers[0].accountsCommand.get({ accountName: `${servers[0].user.username}@${servers[0].host}` }) diff --git a/server/tests/external-plugins/auth-ldap.ts b/server/tests/external-plugins/auth-ldap.ts index 8153e2b81..d99b3badc 100644 --- a/server/tests/external-plugins/auth-ldap.ts +++ b/server/tests/external-plugins/auth-ldap.ts @@ -3,9 +3,7 @@ import 'mocha' import { expect } from 'chai' import { HttpStatusCode } from '@shared/core-utils' -import { User } from '@shared/models/users/user.model' -import { blockUser, getMyUserInformation, setAccessTokensToServers, unblockUser, uploadVideo } from '../../../shared/extra-utils' -import { cleanupTests, flushAndRunServer, ServerInfo } from '../../../shared/extra-utils/server/servers' +import { cleanupTests, flushAndRunServer, ServerInfo, setAccessTokensToServers, uploadVideo } from '@shared/extra-utils' describe('Official plugin auth-ldap', function () { let server: ServerInfo @@ -71,9 +69,7 @@ describe('Official plugin auth-ldap', function () { }) it('Should login get my profile', async function () { - const res = await getMyUserInformation(server.url, accessToken) - const body: User = res.body - + const body = await server.usersCommand.getMyInfo({ token: accessToken }) expect(body.username).to.equal('fry') expect(body.email).to.equal('fry@planetexpress.com') @@ -85,7 +81,7 @@ describe('Official plugin auth-ldap', function () { }) it('Should not be able to login if the user is banned', async function () { - await blockUser(server.url, userId, server.accessToken) + await server.usersCommand.banUser({ userId }) await server.loginCommand.login({ user: { username: 'fry@planetexpress.com', password: 'fry' }, @@ -94,7 +90,7 @@ describe('Official plugin auth-ldap', function () { }) it('Should be able to login if the user is unbanned', async function () { - await unblockUser(server.url, userId, server.accessToken) + await server.usersCommand.unbanUser({ userId }) await server.loginCommand.login({ user: { username: 'fry@planetexpress.com', password: 'fry' } }) }) diff --git a/server/tests/feeds/feeds.ts b/server/tests/feeds/feeds.ts index 9c78ae0e8..18ce8f7c5 100644 --- a/server/tests/feeds/feeds.ts +++ b/server/tests/feeds/feeds.ts @@ -6,21 +6,16 @@ import * as xmlParser from 'fast-xml-parser' import { HttpStatusCode } from '@shared/core-utils' import { cleanupTests, - createUser, doubleFollow, flushAndRunMultipleServers, flushAndRunServer, - getMyUserInformation, - getUserScopedTokens, - renewUserScopedTokens, ServerInfo, setAccessTokensToServers, uploadVideo, uploadVideoAndGetId, waitJobs } from '@shared/extra-utils' -import { User, VideoPrivacy } from '@shared/models' -import { ScopedToken } from '@shared/models/users/user-scoped-token' +import { VideoPrivacy } from '@shared/models' chai.use(require('chai-xml')) chai.use(require('chai-json-schema')) @@ -54,24 +49,21 @@ describe('Test syndication feeds', () => { await doubleFollow(servers[0], servers[1]) { - const res = await getMyUserInformation(servers[0].url, servers[0].accessToken) - const user: User = res.body + const user = await servers[0].usersCommand.getMyInfo() rootAccountId = user.account.id rootChannelId = user.videoChannels[0].id } { const attr = { username: 'john', password: 'password' } - await createUser({ url: servers[0].url, accessToken: servers[0].accessToken, username: attr.username, password: attr.password }) + await servers[0].usersCommand.create({ username: attr.username, password: attr.password }) userAccessToken = await servers[0].loginCommand.getAccessToken(attr) - const res = await getMyUserInformation(servers[0].url, userAccessToken) - const user: User = res.body + const user = await servers[0].usersCommand.getMyInfo({ token: userAccessToken }) userAccountId = user.account.id userChannelId = user.videoChannels[0].id - const res2 = await getUserScopedTokens(servers[0].url, userAccessToken) - const token: ScopedToken = res2.body + const token = await servers[0].usersCommand.getMyScopedTokens({ token: userAccessToken }) userFeedToken = token.feedToken } @@ -299,18 +291,16 @@ describe('Test syndication feeds', () => { it('Should list no videos for a user with no videos and no subscriptions', async function () { const attr = { username: 'feeduser', password: 'password' } - await createUser({ url: servers[0].url, accessToken: servers[0].accessToken, username: attr.username, password: attr.password }) + await servers[0].usersCommand.create({ username: attr.username, password: attr.password }) const feeduserAccessToken = await servers[0].loginCommand.getAccessToken(attr) { - const res = await getMyUserInformation(servers[0].url, feeduserAccessToken) - const user: User = res.body + const user = await servers[0].usersCommand.getMyInfo({ token: feeduserAccessToken }) feeduserAccountId = user.account.id } { - const res = await getUserScopedTokens(servers[0].url, feeduserAccessToken) - const token: ScopedToken = res.body + const token = await servers[0].usersCommand.getMyScopedTokens({ token: feeduserAccessToken }) feeduserFeedToken = token.feedToken } @@ -381,15 +371,14 @@ describe('Test syndication feeds', () => { }) it('Should renew the token, and so have an invalid old token', async function () { - await renewUserScopedTokens(servers[0].url, userAccessToken) + await servers[0].usersCommand.renewMyScopedTokens({ token: userAccessToken }) const query = { accountId: userAccountId, token: userFeedToken, version: 3 } await servers[0].feedCommand.getJSON({ feed: 'subscriptions', query, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) it('Should succeed with the new token', async function () { - const res2 = await getUserScopedTokens(servers[0].url, userAccessToken) - const token: ScopedToken = res2.body + const token = await servers[0].usersCommand.getMyScopedTokens({ token: userAccessToken }) userFeedToken = token.feedToken const query = { accountId: userAccountId, token: userFeedToken, version: 4 } diff --git a/server/tests/misc-endpoints.ts b/server/tests/misc-endpoints.ts index 4b7b2163d..84bdcaabf 100644 --- a/server/tests/misc-endpoints.ts +++ b/server/tests/misc-endpoints.ts @@ -5,7 +5,6 @@ import * as chai from 'chai' import { HttpStatusCode } from '@shared/core-utils' import { cleanupTests, - createUser, flushAndRunServer, makeGetRequest, ServerInfo, @@ -173,8 +172,8 @@ describe('Test misc endpoints', function () { await server.channelsCommand.create({ attributes: { name: 'channel1', displayName: 'channel 1' } }) await server.channelsCommand.create({ attributes: { name: 'channel2', displayName: 'channel 2' } }) - await createUser({ url: server.url, accessToken: server.accessToken, username: 'user1', password: 'password' }) - await createUser({ url: server.url, accessToken: server.accessToken, username: 'user2', password: 'password' }) + await server.usersCommand.create({ username: 'user1', password: 'password' }) + await server.usersCommand.create({ username: 'user2', password: 'password' }) const res = await makeGetRequest({ url: server.url, diff --git a/server/tests/plugins/action-hooks.ts b/server/tests/plugins/action-hooks.ts index 84f4e8501..b156f6b60 100644 --- a/server/tests/plugins/action-hooks.ts +++ b/server/tests/plugins/action-hooks.ts @@ -1,28 +1,20 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ import 'mocha' -import { ServerHookName, VideoPlaylistPrivacy, VideoPrivacy } from '@shared/models' import { - blockUser, - createUser, + cleanupTests, + flushAndRunMultipleServers, + killallServers, PluginsCommand, - registerUser, - removeUser, + reRunServer, + ServerInfo, setAccessTokensToServers, setDefaultVideoChannel, - unblockUser, - updateUser, updateVideo, uploadVideo, viewVideo -} from '../../../shared/extra-utils' -import { - cleanupTests, - flushAndRunMultipleServers, - killallServers, - reRunServer, - ServerInfo -} from '../../../shared/extra-utils/server/servers' +} from '@shared/extra-utils' +import { ServerHookName, VideoPlaylistPrivacy, VideoPrivacy } from '@shared/models' describe('Test plugin action hooks', function () { let servers: ServerInfo[] @@ -119,19 +111,14 @@ describe('Test plugin action hooks', function () { let userId: number it('Should run action:api.user.registered', async function () { - await registerUser(servers[0].url, 'registered_user', 'super_password') + await servers[0].usersCommand.register({ username: 'registered_user' }) await checkHook('action:api.user.registered') }) it('Should run action:api.user.created', async function () { - const res = await createUser({ - url: servers[0].url, - accessToken: servers[0].accessToken, - username: 'created_user', - password: 'super_password' - }) - userId = res.body.user.id + const user = await servers[0].usersCommand.create({ username: 'created_user' }) + userId = user.id await checkHook('action:api.user.created') }) @@ -143,25 +130,25 @@ describe('Test plugin action hooks', function () { }) it('Should run action:api.user.blocked', async function () { - await blockUser(servers[0].url, userId, servers[0].accessToken) + await servers[0].usersCommand.banUser({ userId }) await checkHook('action:api.user.blocked') }) it('Should run action:api.user.unblocked', async function () { - await unblockUser(servers[0].url, userId, servers[0].accessToken) + await servers[0].usersCommand.unbanUser({ userId }) await checkHook('action:api.user.unblocked') }) it('Should run action:api.user.updated', async function () { - await updateUser({ url: servers[0].url, accessToken: servers[0].accessToken, userId, videoQuota: 50 }) + await servers[0].usersCommand.update({ userId, videoQuota: 50 }) await checkHook('action:api.user.updated') }) it('Should run action:api.user.deleted', async function () { - await removeUser(servers[0].url, userId, servers[0].accessToken) + await servers[0].usersCommand.remove({ userId }) await checkHook('action:api.user.deleted') }) diff --git a/server/tests/plugins/external-auth.ts b/server/tests/plugins/external-auth.ts index e421fd224..3e8305611 100644 --- a/server/tests/plugins/external-auth.ts +++ b/server/tests/plugins/external-auth.ts @@ -5,17 +5,14 @@ import { expect } from 'chai' import { HttpStatusCode } from '@shared/core-utils' import { cleanupTests, - createUser, decodeQueryString, flushAndRunServer, - getMyUserInformation, PluginsCommand, ServerInfo, setAccessTokensToServers, - updateMyUser, wait } from '@shared/extra-utils' -import { User, UserRole } from '@shared/models' +import { UserRole } from '@shared/models' async function loginExternal (options: { server: ServerInfo @@ -149,9 +146,7 @@ describe('Test external auth plugins', function () { } { - const res = await getMyUserInformation(server.url, cyanAccessToken) - - const body: User = res.body + const body = await server.usersCommand.getMyInfo({ token: cyanAccessToken }) expect(body.username).to.equal('cyan') expect(body.account.displayName).to.equal('cyan') expect(body.email).to.equal('cyan@example.com') @@ -173,9 +168,7 @@ describe('Test external auth plugins', function () { } { - const res = await getMyUserInformation(server.url, kefkaAccessToken) - - const body: User = res.body + const body = await server.usersCommand.getMyInfo({ token: kefkaAccessToken }) expect(body.username).to.equal('kefka') expect(body.account.displayName).to.equal('Kefka Palazzo') expect(body.email).to.equal('kefka@example.com') @@ -189,9 +182,8 @@ describe('Test external auth plugins', function () { cyanAccessToken = resRefresh.body.access_token cyanRefreshToken = resRefresh.body.refresh_token - const res = await getMyUserInformation(server.url, cyanAccessToken) - const user: User = res.body - expect(user.username).to.equal('cyan') + const body = await server.usersCommand.getMyInfo({ token: cyanAccessToken }) + expect(body.username).to.equal('cyan') } { @@ -200,16 +192,13 @@ describe('Test external auth plugins', function () { }) it('Should update Cyan profile', async function () { - await updateMyUser({ - url: server.url, - accessToken: cyanAccessToken, + await server.usersCommand.updateMe({ + token: cyanAccessToken, displayName: 'Cyan Garamonde', description: 'Retainer to the king of Doma' }) - const res = await getMyUserInformation(server.url, cyanAccessToken) - - const body: User = res.body + const body = await server.usersCommand.getMyInfo({ token: cyanAccessToken }) expect(body.account.displayName).to.equal('Cyan Garamonde') expect(body.account.description).to.equal('Retainer to the king of Doma') }) @@ -221,7 +210,7 @@ describe('Test external auth plugins', function () { it('Should have logged out Cyan', async function () { await server.serversCommand.waitUntilLog('On logout cyan') - await getMyUserInformation(server.url, cyanAccessToken, HttpStatusCode.UNAUTHORIZED_401) + await server.usersCommand.getMyInfo({ token: cyanAccessToken, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should login Cyan and keep the old existing profile', async function () { @@ -239,9 +228,7 @@ describe('Test external auth plugins', function () { cyanAccessToken = res.access_token } - const res = await getMyUserInformation(server.url, cyanAccessToken) - - const body: User = res.body + const body = await server.usersCommand.getMyInfo({ token: cyanAccessToken }) expect(body.username).to.equal('cyan') expect(body.account.displayName).to.equal('Cyan Garamonde') expect(body.account.description).to.equal('Retainer to the king of Doma') @@ -249,12 +236,11 @@ describe('Test external auth plugins', function () { }) it('Should not update an external auth email', async function () { - await updateMyUser({ - url: server.url, - accessToken: cyanAccessToken, + await server.usersCommand.updateMe({ + token: cyanAccessToken, email: 'toto@example.com', currentPassword: 'toto', - statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 + expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) @@ -263,7 +249,7 @@ describe('Test external auth plugins', function () { await wait(5000) - await getMyUserInformation(server.url, kefkaAccessToken, HttpStatusCode.UNAUTHORIZED_401) + await server.usersCommand.getMyInfo({ token: kefkaAccessToken, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should unregister external-auth-2 and do not login existing Kefka', async function () { @@ -334,12 +320,7 @@ describe('Test external auth plugins', function () { }) it('Should not login an existing user', async function () { - await createUser({ - url: server.url, - accessToken: server.accessToken, - username: 'existing_user', - password: 'super_password' - }) + await server.usersCommand.create({ username: 'existing_user', password: 'super_password' }) await loginExternal({ server, diff --git a/server/tests/plugins/filter-hooks.ts b/server/tests/plugins/filter-hooks.ts index b5e29d298..c82025f6a 100644 --- a/server/tests/plugins/filter-hooks.ts +++ b/server/tests/plugins/filter-hooks.ts @@ -17,7 +17,6 @@ import { ImportsCommand, makeRawRequest, PluginsCommand, - registerUser, ServerInfo, setAccessTokensToServers, setDefaultVideoChannel, @@ -335,11 +334,15 @@ describe('Test plugin filter hooks', function () { }) it('Should allow a signup', async function () { - await registerUser(servers[0].url, 'john', 'password') + await servers[0].usersCommand.register({ username: 'john', password: 'password' }) }) it('Should not allow a signup', async function () { - const res = await registerUser(servers[0].url, 'jma', 'password', HttpStatusCode.FORBIDDEN_403) + const res = await servers[0].usersCommand.register({ + username: 'jma', + password: 'password', + expectedStatus: HttpStatusCode.FORBIDDEN_403 + }) expect(res.body.error).to.equal('No jma') }) diff --git a/server/tests/plugins/id-and-pass-auth.ts b/server/tests/plugins/id-and-pass-auth.ts index e3da64110..787080e7c 100644 --- a/server/tests/plugins/id-and-pass-auth.ts +++ b/server/tests/plugins/id-and-pass-auth.ts @@ -3,18 +3,8 @@ import 'mocha' import { expect } from 'chai' import { HttpStatusCode } from '@shared/core-utils' -import { - cleanupTests, - flushAndRunServer, - getMyUserInformation, - getUsersList, - PluginsCommand, - ServerInfo, - setAccessTokensToServers, - updateMyUser, - wait -} from '@shared/extra-utils' -import { User, UserRole } from '@shared/models' +import { cleanupTests, flushAndRunServer, PluginsCommand, ServerInfo, setAccessTokensToServers, wait } from '@shared/extra-utils' +import { UserRole } from '@shared/models' describe('Test id and pass auth plugins', function () { let server: ServerInfo @@ -55,9 +45,8 @@ describe('Test id and pass auth plugins', function () { it('Should login Spyro, create the user and use the token', async function () { const accessToken = await server.loginCommand.getAccessToken({ username: 'spyro', password: 'spyro password' }) - const res = await getMyUserInformation(server.url, accessToken) + const body = await server.usersCommand.getMyInfo({ token: accessToken }) - const body: User = res.body expect(body.username).to.equal('spyro') expect(body.account.displayName).to.equal('Spyro the Dragon') expect(body.role).to.equal(UserRole.USER) @@ -71,9 +60,8 @@ describe('Test id and pass auth plugins', function () { } { - const res = await getMyUserInformation(server.url, crashAccessToken) + const body = await server.usersCommand.getMyInfo({ token: crashAccessToken }) - const body: User = res.body expect(body.username).to.equal('crash') expect(body.account.displayName).to.equal('Crash Bandicoot') expect(body.role).to.equal(UserRole.MODERATOR) @@ -88,9 +76,8 @@ describe('Test id and pass auth plugins', function () { } { - const res = await getMyUserInformation(server.url, lagunaAccessToken) + const body = await server.usersCommand.getMyInfo({ token: lagunaAccessToken }) - const body: User = res.body expect(body.username).to.equal('laguna') expect(body.account.displayName).to.equal('laguna') expect(body.role).to.equal(UserRole.USER) @@ -103,9 +90,8 @@ describe('Test id and pass auth plugins', function () { crashAccessToken = resRefresh.body.access_token crashRefreshToken = resRefresh.body.refresh_token - const res = await getMyUserInformation(server.url, crashAccessToken) - const user: User = res.body - expect(user.username).to.equal('crash') + const body = await server.usersCommand.getMyInfo({ token: crashAccessToken }) + expect(body.username).to.equal('crash') } { @@ -114,16 +100,14 @@ describe('Test id and pass auth plugins', function () { }) it('Should update Crash profile', async function () { - await updateMyUser({ - url: server.url, - accessToken: crashAccessToken, + await server.usersCommand.updateMe({ + token: crashAccessToken, displayName: 'Beautiful Crash', description: 'Mutant eastern barred bandicoot' }) - const res = await getMyUserInformation(server.url, crashAccessToken) + const body = await server.usersCommand.getMyInfo({ token: crashAccessToken }) - const body: User = res.body expect(body.account.displayName).to.equal('Beautiful Crash') expect(body.account.description).to.equal('Mutant eastern barred bandicoot') }) @@ -135,15 +119,14 @@ describe('Test id and pass auth plugins', function () { it('Should have logged out Crash', async function () { await server.serversCommand.waitUntilLog('On logout for auth 1 - 2') - await getMyUserInformation(server.url, crashAccessToken, 401) + await server.usersCommand.getMyInfo({ token: crashAccessToken, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should login Crash and keep the old existing profile', async function () { crashAccessToken = await server.loginCommand.getAccessToken({ username: 'crash', password: 'crash password' }) - const res = await getMyUserInformation(server.url, crashAccessToken) + const body = await server.usersCommand.getMyInfo({ token: crashAccessToken }) - const body: User = res.body expect(body.username).to.equal('crash') expect(body.account.displayName).to.equal('Beautiful Crash') expect(body.account.description).to.equal('Mutant eastern barred bandicoot') @@ -155,7 +138,7 @@ describe('Test id and pass auth plugins', function () { await wait(5000) - await getMyUserInformation(server.url, lagunaAccessToken, 401) + await server.usersCommand.getMyInfo({ token: lagunaAccessToken, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should reject an invalid username, email, role or display name', async function () { @@ -215,13 +198,11 @@ describe('Test id and pass auth plugins', function () { }) it('Should display plugin auth information in users list', async function () { - const res = await getUsersList(server.url, server.accessToken) - - const users: User[] = res.body.data + const { data } = await server.usersCommand.list() - const root = users.find(u => u.username === 'root') - const crash = users.find(u => u.username === 'crash') - const laguna = users.find(u => u.username === 'laguna') + const root = data.find(u => u.username === 'root') + const crash = data.find(u => u.username === 'crash') + const laguna = data.find(u => u.username === 'laguna') expect(root.pluginAuth).to.be.null expect(crash.pluginAuth).to.equal('peertube-plugin-test-id-pass-auth-one') diff --git a/server/tools/cli.ts b/server/tools/cli.ts index 3e0e03b97..17c2e8c74 100644 --- a/server/tools/cli.ts +++ b/server/tools/cli.ts @@ -3,8 +3,7 @@ import { Netrc } from 'netrc-parser' import { join } from 'path' import { createLogger, format, transports } from 'winston' import { assignCommands, ServerInfo } from '@shared/extra-utils' -import { getMyUserInformation } from '@shared/extra-utils/users/users' -import { User, UserRole } from '@shared/models' +import { UserRole } from '@shared/models' import { VideoPrivacy } from '../../shared/models/videos' import { getAppNumber, isTestInstance, root } from '../helpers/core-utils' @@ -16,16 +15,15 @@ const config = require('application-config')(configName) const version = require('../../../package.json').version async function getAdminTokenOrDie (server: ServerInfo, username: string, password: string) { - const accessToken = await server.loginCommand.getAccessToken(username, password) - const resMe = await getMyUserInformation(server.url, accessToken) - const me: User = resMe.body + const token = await server.loginCommand.getAccessToken(username, password) + const me = await server.usersCommand.getMyUserInformation({ token }) if (me.role !== UserRole.ADMINISTRATOR) { console.error('You must be an administrator.') process.exit(-1) } - return accessToken + return token } interface Settings { diff --git a/shared/extra-utils/server/servers.ts b/shared/extra-utils/server/servers.ts index 4d9599680..b6d597c5d 100644 --- a/shared/extra-utils/server/servers.ts +++ b/shared/extra-utils/server/servers.ts @@ -16,7 +16,7 @@ import { AbusesCommand } from '../moderation' import { OverviewsCommand } from '../overviews' import { SearchCommand } from '../search' import { SocketIOCommand } from '../socket' -import { AccountsCommand, BlocklistCommand, LoginCommand, NotificationsCommand, SubscriptionsCommand } from '../users' +import { AccountsCommand, BlocklistCommand, LoginCommand, NotificationsCommand, SubscriptionsCommand, UsersCommand } from '../users' import { BlacklistCommand, CaptionsCommand, @@ -127,6 +127,7 @@ interface ServerInfo { notificationsCommand?: NotificationsCommand serversCommand?: ServersCommand loginCommand?: LoginCommand + usersCommand?: UsersCommand } function flushAndRunMultipleServers (totalServers: number, configOverride?: Object) { @@ -359,6 +360,7 @@ function assignCommands (server: ServerInfo) { server.notificationsCommand = new NotificationsCommand(server) server.serversCommand = new ServersCommand(server) server.loginCommand = new LoginCommand(server) + server.usersCommand = new UsersCommand(server) } async function reRunServer (server: ServerInfo, configOverride?: any) { diff --git a/shared/extra-utils/users/index.ts b/shared/extra-utils/users/index.ts index b200ae705..e6107afa5 100644 --- a/shared/extra-utils/users/index.ts +++ b/shared/extra-utils/users/index.ts @@ -6,4 +6,5 @@ export * from './login-command' export * from './notifications' export * from './notifications-command' export * from './subscriptions-command' +export * from './users-command' export * from './users' diff --git a/shared/extra-utils/users/login-command.ts b/shared/extra-utils/users/login-command.ts index 8af3531f9..b4e3bb602 100644 --- a/shared/extra-utils/users/login-command.ts +++ b/shared/extra-utils/users/login-command.ts @@ -7,7 +7,7 @@ export class LoginCommand extends AbstractCommand { login (options: OverrideCommandOptions & { client?: { id?: string, secret?: string } - user?: { username: string, password: string } + user?: { username: string, password?: string } } = {}) { const { client = this.server.client, user = this.server.user } = options const path = '/api/v1/users/token' @@ -16,7 +16,7 @@ export class LoginCommand extends AbstractCommand { client_id: client.id, client_secret: client.secret, username: user.username, - password: user.password, + password: user.password ?? 'password', response_type: 'code', grant_type: 'password', scope: 'upload' @@ -33,10 +33,10 @@ export class LoginCommand extends AbstractCommand { })) } - getAccessToken (arg1?: { username: string, password: string }): Promise - getAccessToken (arg1: string, password: string): Promise - async getAccessToken (arg1?: { username: string, password: string } | string, password?: string) { - let user: { username: string, password: string } + getAccessToken (arg1?: { username: string, password?: string }): Promise + getAccessToken (arg1: string, password?: string): Promise + async getAccessToken (arg1?: { username: string, password?: string } | string, password?: string) { + let user: { username: string, password?: string } if (!arg1) user = this.server.user else if (typeof arg1 === 'object') user = arg1 diff --git a/shared/extra-utils/users/notifications.ts b/shared/extra-utils/users/notifications.ts index 79cb6f617..0af7d8a18 100644 --- a/shared/extra-utils/users/notifications.ts +++ b/shared/extra-utils/users/notifications.ts @@ -8,7 +8,6 @@ import { MockSmtpServer } from '../mock-servers/mock-email' import { doubleFollow } from '../server/follows' import { flushAndRunMultipleServers, ServerInfo } from '../server/servers' import { setAccessTokensToServers } from './login' -import { createUser, getMyUserInformation } from './users' function getAllNotificationsSettings (): UserNotificationSetting { return { @@ -651,17 +650,8 @@ async function prepareNotificationsTest (serversCount = 3, overrideConfigArg: an await doubleFollow(servers[0], servers[1]) } - const user = { - username: 'user_1', - password: 'super password' - } - await createUser({ - url: servers[0].url, - accessToken: servers[0].accessToken, - username: user.username, - password: user.password, - videoQuota: 10 * 1000 * 1000 - }) + const user = { username: 'user_1', password: 'super password' } + await servers[0].usersCommand.create({ ...user, videoQuota: 10 * 1000 * 1000 }) const userAccessToken = await servers[0].loginCommand.getAccessToken(user) await servers[0].notificationsCommand.updateMySettings({ token: userAccessToken, settings: getAllNotificationsSettings() }) @@ -685,8 +675,8 @@ async function prepareNotificationsTest (serversCount = 3, overrideConfigArg: an socket.on('new-notification', n => adminNotificationsServer2.push(n)) } - const resChannel = await getMyUserInformation(servers[0].url, servers[0].accessToken) - const channelId = resChannel.body.videoChannels[0].id + const { videoChannels } = await servers[0].usersCommand.getMyInfo() + const channelId = videoChannels[0].id return { userNotifications, diff --git a/shared/extra-utils/users/users-command.ts b/shared/extra-utils/users/users-command.ts new file mode 100644 index 000000000..202528b8d --- /dev/null +++ b/shared/extra-utils/users/users-command.ts @@ -0,0 +1,414 @@ +import { omit, pick } from 'lodash' +import { HttpStatusCode } from '@shared/core-utils' +import { + MyUser, + ResultList, + User, + UserAdminFlag, + UserCreateResult, + UserRole, + UserUpdate, + UserUpdateMe, + UserVideoQuota, + UserVideoRate +} from '@shared/models' +import { ScopedToken } from '@shared/models/users/user-scoped-token' +import { unwrapBody } from '../requests' +import { AbstractCommand, OverrideCommandOptions } from '../shared' + +export class UsersCommand extends AbstractCommand { + + askResetPassword (options: OverrideCommandOptions & { + email: string + }) { + const { email } = options + const path = '/api/v1/users/ask-reset-password' + + return this.postBodyRequest({ + ...options, + + path, + fields: { email }, + implicitToken: false, + defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 + }) + } + + resetPassword (options: OverrideCommandOptions & { + userId: number + verificationString: string + password: string + }) { + const { userId, verificationString, password } = options + const path = '/api/v1/users/' + userId + '/reset-password' + + return this.postBodyRequest({ + ...options, + + path, + fields: { password, verificationString }, + implicitToken: false, + defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 + }) + } + + // --------------------------------------------------------------------------- + + askSendVerifyEmail (options: OverrideCommandOptions & { + email: string + }) { + const { email } = options + const path = '/api/v1/users/ask-send-verify-email' + + return this.postBodyRequest({ + ...options, + + path, + fields: { email }, + implicitToken: false, + defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 + }) + } + + verifyEmail (options: OverrideCommandOptions & { + userId: number + verificationString: string + isPendingEmail?: boolean // default false + }) { + const { userId, verificationString, isPendingEmail = false } = options + const path = '/api/v1/users/' + userId + '/verify-email' + + return this.postBodyRequest({ + ...options, + + path, + fields: { + verificationString, + isPendingEmail + }, + implicitToken: false, + defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 + }) + } + + // --------------------------------------------------------------------------- + + banUser (options: OverrideCommandOptions & { + userId: number + reason?: string + }) { + const { userId, reason } = options + const path = '/api/v1/users' + '/' + userId + '/block' + + return this.postBodyRequest({ + ...options, + + path, + fields: { reason }, + implicitToken: true, + defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 + }) + } + + unbanUser (options: OverrideCommandOptions & { + userId: number + }) { + const { userId } = options + const path = '/api/v1/users' + '/' + userId + '/unblock' + + return this.postBodyRequest({ + ...options, + + path, + implicitToken: true, + defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 + }) + } + + // --------------------------------------------------------------------------- + + getMyScopedTokens (options: OverrideCommandOptions = {}) { + const path = '/api/v1/users/scoped-tokens' + + return this.getRequestBody({ + ...options, + + path, + implicitToken: true, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } + + renewMyScopedTokens (options: OverrideCommandOptions = {}) { + const path = '/api/v1/users/scoped-tokens' + + return this.postBodyRequest({ + ...options, + + path, + implicitToken: true, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } + + // --------------------------------------------------------------------------- + + create (options: OverrideCommandOptions & { + username: string + password?: string + videoQuota?: number + videoQuotaDaily?: number + role?: UserRole + adminFlags?: UserAdminFlag + }) { + const { + username, + adminFlags, + password = 'password', + videoQuota = 42000000, + videoQuotaDaily = -1, + role = UserRole.USER + } = options + + const path = '/api/v1/users' + + return unwrapBody<{ user: UserCreateResult }>(this.postBodyRequest({ + ...options, + + path, + fields: { + username, + password, + role, + adminFlags, + email: username + '@example.com', + videoQuota, + videoQuotaDaily + }, + implicitToken: true, + defaultExpectedStatus: HttpStatusCode.OK_200 + })).then(res => res.user) + } + + async generate (username: string) { + const password = 'password' + const user = await this.create({ username, password }) + + const token = await this.server.loginCommand.getAccessToken({ username, password }) + + const me = await this.getMyInfo({ token }) + + return { + token, + userId: user.id, + userChannelId: me.videoChannels[0].id + } + } + + async generateUserAndToken (username: string) { + const password = 'password' + await this.create({ username, password }) + + return this.server.loginCommand.getAccessToken({ username, password }) + } + + register (options: OverrideCommandOptions & { + username: string + password?: string + displayName?: string + channel?: { + name: string + displayName: string + } + }) { + const { username, password = 'password', displayName, channel } = options + const path = '/api/v1/users/register' + + return this.postBodyRequest({ + ...options, + + path, + fields: { + username, + password, + email: username + '@example.com', + displayName, + channel + }, + implicitToken: false, + defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 + }) + } + + // --------------------------------------------------------------------------- + + getMyInfo (options: OverrideCommandOptions = {}) { + const path = '/api/v1/users/me' + + return this.getRequestBody({ + ...options, + + path, + implicitToken: true, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } + + getMyQuotaUsed (options: OverrideCommandOptions = {}) { + const path = '/api/v1/users/me/video-quota-used' + + return this.getRequestBody({ + ...options, + + path, + implicitToken: true, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } + + getMyRating (options: OverrideCommandOptions & { + videoId: number | string + }) { + const { videoId } = options + const path = '/api/v1/users/me/videos/' + videoId + '/rating' + + return this.getRequestBody({ + ...options, + + path, + implicitToken: true, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } + + deleteMe (options: OverrideCommandOptions = {}) { + const path = '/api/v1/users/me' + + return this.deleteRequest({ + ...options, + + path, + implicitToken: true, + defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 + }) + } + + updateMe (options: OverrideCommandOptions & UserUpdateMe) { + const path = '/api/v1/users/me' + + const toSend: UserUpdateMe = omit(options, 'url', 'accessToken') + + return this.putBodyRequest({ + ...options, + + path, + fields: toSend, + implicitToken: true, + defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 + }) + } + + updateMyAvatar (options: OverrideCommandOptions & { + fixture: string + }) { + const { fixture } = options + const path = '/api/v1/users/me/avatar/pick' + + return this.updateImageRequest({ + ...options, + + path, + fixture, + fieldname: 'avatarfile', + + implicitToken: true, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } + + // --------------------------------------------------------------------------- + + get (options: OverrideCommandOptions & { + userId: number + withStats?: boolean // default false + }) { + const { userId, withStats } = options + const path = '/api/v1/users/' + userId + + return this.getRequestBody({ + ...options, + + path, + query: { withStats }, + implicitToken: true, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } + + list (options: OverrideCommandOptions & { + start?: number + count?: number + sort?: string + search?: string + blocked?: boolean + } = {}) { + const path = '/api/v1/users' + + return this.getRequestBody>({ + ...options, + + path, + query: pick(options, [ 'start', 'count', 'sort', 'search', 'blocked' ]), + implicitToken: true, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } + + remove (options: OverrideCommandOptions & { + userId: number + }) { + const { userId } = options + const path = '/api/v1/users/' + userId + + return this.deleteRequest({ + ...options, + + path, + implicitToken: true, + defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 + }) + } + + update (options: OverrideCommandOptions & { + userId: number + email?: string + emailVerified?: boolean + videoQuota?: number + videoQuotaDaily?: number + password?: string + adminFlags?: UserAdminFlag + pluginAuth?: string + role?: UserRole + }) { + const path = '/api/v1/users/' + options.userId + + const toSend: UserUpdate = {} + if (options.password !== undefined && options.password !== null) toSend.password = options.password + if (options.email !== undefined && options.email !== null) toSend.email = options.email + if (options.emailVerified !== undefined && options.emailVerified !== null) toSend.emailVerified = options.emailVerified + if (options.videoQuota !== undefined && options.videoQuota !== null) toSend.videoQuota = options.videoQuota + if (options.videoQuotaDaily !== undefined && options.videoQuotaDaily !== null) toSend.videoQuotaDaily = options.videoQuotaDaily + if (options.role !== undefined && options.role !== null) toSend.role = options.role + if (options.adminFlags !== undefined && options.adminFlags !== null) toSend.adminFlags = options.adminFlags + if (options.pluginAuth !== undefined) toSend.pluginAuth = options.pluginAuth + + return this.putBodyRequest({ + ...options, + + path, + fields: toSend, + implicitToken: true, + defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 + }) + } +} diff --git a/shared/extra-utils/users/users.ts b/shared/extra-utils/users/users.ts index 835ad08ba..6cf61d60e 100644 --- a/shared/extra-utils/users/users.ts +++ b/shared/extra-utils/users/users.ts @@ -1,118 +1,8 @@ -import { omit } from 'lodash' import * as request from 'supertest' import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' -import { UserUpdateMe } from '../../models/users' -import { UserAdminFlag } from '../../models/users/user-flag.model' -import { UserRegister } from '../../models/users/user-register.model' -import { UserRole } from '../../models/users/user-role' -import { makeGetRequest, makePostBodyRequest, makePutBodyRequest, updateImageRequest } from '../requests/requests' -import { ServerInfo } from '../server/servers' -function createUser (parameters: { - url: string - accessToken: string - username: string - password: string - videoQuota?: number - videoQuotaDaily?: number - role?: UserRole - adminFlags?: UserAdminFlag - specialStatus?: number -}) { - const { - url, - accessToken, - username, - adminFlags, - password = 'password', - videoQuota = 1000000, - videoQuotaDaily = -1, - role = UserRole.USER, - specialStatus = HttpStatusCode.OK_200 - } = parameters - - const path = '/api/v1/users' - const body = { - username, - password, - role, - adminFlags, - email: username + '@example.com', - videoQuota, - videoQuotaDaily - } - - return request(url) - .post(path) - .set('Accept', 'application/json') - .set('Authorization', 'Bearer ' + accessToken) - .send(body) - .expect(specialStatus) -} - -async function generateUser (server: ServerInfo, username: string) { - const password = 'my super password' - const resCreate = await createUser({ url: server.url, accessToken: server.accessToken, username: username, password: password }) - - const token = await server.loginCommand.getAccessToken({ username, password }) - - const resMe = await getMyUserInformation(server.url, token) - - return { - token, - userId: resCreate.body.user.id, - userChannelId: resMe.body.videoChannels[0].id - } -} - -async function generateUserAccessToken (server: ServerInfo, username: string) { - const password = 'my super password' - await createUser({ url: server.url, accessToken: server.accessToken, username: username, password: password }) - - return server.loginCommand.getAccessToken({ username, password }) -} - -function registerUser (url: string, username: string, password: string, specialStatus = HttpStatusCode.NO_CONTENT_204) { - const path = '/api/v1/users/register' - const body = { - username, - password, - email: username + '@example.com' - } - - return request(url) - .post(path) - .set('Accept', 'application/json') - .send(body) - .expect(specialStatus) -} - -function registerUserWithChannel (options: { - url: string - user: { username: string, password: string, displayName?: string } - channel: { name: string, displayName: string } -}) { - const path = '/api/v1/users/register' - const body: UserRegister = { - username: options.user.username, - password: options.user.password, - email: options.user.username + '@example.com', - channel: options.channel - } - - if (options.user.displayName) { - Object.assign(body, { displayName: options.user.displayName }) - } - - return makePostBodyRequest({ - url: options.url, - path, - fields: body, - statusCodeExpected: HttpStatusCode.NO_CONTENT_204 - }) -} - -function getMyUserInformation (url: string, accessToken: string, specialStatus = HttpStatusCode.OK_200) { +// FIXME: delete once videos does not use it anymore +function xxxgetMyUserInformation (url: string, accessToken: string, specialStatus = HttpStatusCode.OK_200) { const path = '/api/v1/users/me' return request(url) @@ -123,292 +13,8 @@ function getMyUserInformation (url: string, accessToken: string, specialStatus = .expect('Content-Type', /json/) } -function getUserScopedTokens (url: string, token: string, statusCodeExpected = HttpStatusCode.OK_200) { - const path = '/api/v1/users/scoped-tokens' - - return makeGetRequest({ - url, - path, - token, - statusCodeExpected - }) -} - -function renewUserScopedTokens (url: string, token: string, statusCodeExpected = HttpStatusCode.OK_200) { - const path = '/api/v1/users/scoped-tokens' - - return makePostBodyRequest({ - url, - path, - token, - statusCodeExpected - }) -} - -function deleteMe (url: string, accessToken: string, specialStatus = HttpStatusCode.NO_CONTENT_204) { - const path = '/api/v1/users/me' - - return request(url) - .delete(path) - .set('Accept', 'application/json') - .set('Authorization', 'Bearer ' + accessToken) - .expect(specialStatus) -} - -function getMyUserVideoQuotaUsed (url: string, accessToken: string, specialStatus = HttpStatusCode.OK_200) { - const path = '/api/v1/users/me/video-quota-used' - - return request(url) - .get(path) - .set('Accept', 'application/json') - .set('Authorization', 'Bearer ' + accessToken) - .expect(specialStatus) - .expect('Content-Type', /json/) -} - -function getUserInformation (url: string, accessToken: string, userId: number, withStats = false) { - const path = '/api/v1/users/' + userId - - return request(url) - .get(path) - .query({ withStats }) - .set('Accept', 'application/json') - .set('Authorization', 'Bearer ' + accessToken) - .expect(HttpStatusCode.OK_200) - .expect('Content-Type', /json/) -} - -function getMyUserVideoRating (url: string, accessToken: string, videoId: number | string, specialStatus = HttpStatusCode.OK_200) { - const path = '/api/v1/users/me/videos/' + videoId + '/rating' - - return request(url) - .get(path) - .set('Accept', 'application/json') - .set('Authorization', 'Bearer ' + accessToken) - .expect(specialStatus) - .expect('Content-Type', /json/) -} - -function getUsersList (url: string, accessToken: string) { - const path = '/api/v1/users' - - return request(url) - .get(path) - .set('Accept', 'application/json') - .set('Authorization', 'Bearer ' + accessToken) - .expect(HttpStatusCode.OK_200) - .expect('Content-Type', /json/) -} - -function getUsersListPaginationAndSort ( - url: string, - accessToken: string, - start: number, - count: number, - sort: string, - search?: string, - blocked?: boolean -) { - const path = '/api/v1/users' - - const query = { - start, - count, - sort, - search, - blocked - } - - return request(url) - .get(path) - .query(query) - .set('Accept', 'application/json') - .set('Authorization', 'Bearer ' + accessToken) - .expect(HttpStatusCode.OK_200) - .expect('Content-Type', /json/) -} - -function removeUser (url: string, userId: number | string, accessToken: string, expectedStatus = HttpStatusCode.NO_CONTENT_204) { - const path = '/api/v1/users' - - return request(url) - .delete(path + '/' + userId) - .set('Accept', 'application/json') - .set('Authorization', 'Bearer ' + accessToken) - .expect(expectedStatus) -} - -function blockUser ( - url: string, - userId: number | string, - accessToken: string, - expectedStatus = HttpStatusCode.NO_CONTENT_204, - reason?: string -) { - const path = '/api/v1/users' - let body: any - if (reason) body = { reason } - - return request(url) - .post(path + '/' + userId + '/block') - .send(body) - .set('Accept', 'application/json') - .set('Authorization', 'Bearer ' + accessToken) - .expect(expectedStatus) -} - -function unblockUser (url: string, userId: number | string, accessToken: string, expectedStatus = HttpStatusCode.NO_CONTENT_204) { - const path = '/api/v1/users' - - return request(url) - .post(path + '/' + userId + '/unblock') - .set('Accept', 'application/json') - .set('Authorization', 'Bearer ' + accessToken) - .expect(expectedStatus) -} - -function updateMyUser (options: { url: string, accessToken: string, statusCodeExpected?: HttpStatusCode } & UserUpdateMe) { - const path = '/api/v1/users/me' - - const toSend: UserUpdateMe = omit(options, 'url', 'accessToken') - - return makePutBodyRequest({ - url: options.url, - path, - token: options.accessToken, - fields: toSend, - statusCodeExpected: options.statusCodeExpected || HttpStatusCode.NO_CONTENT_204 - }) -} - -function updateMyAvatar (options: { - url: string - accessToken: string - fixture: string -}) { - const path = '/api/v1/users/me/avatar/pick' - - return updateImageRequest({ ...options, path, fieldname: 'avatarfile' }) -} - -function updateUser (options: { - url: string - userId: number - accessToken: string - email?: string - emailVerified?: boolean - videoQuota?: number - videoQuotaDaily?: number - password?: string - adminFlags?: UserAdminFlag - pluginAuth?: string - role?: UserRole -}) { - const path = '/api/v1/users/' + options.userId - - const toSend = {} - if (options.password !== undefined && options.password !== null) toSend['password'] = options.password - if (options.email !== undefined && options.email !== null) toSend['email'] = options.email - if (options.emailVerified !== undefined && options.emailVerified !== null) toSend['emailVerified'] = options.emailVerified - if (options.videoQuota !== undefined && options.videoQuota !== null) toSend['videoQuota'] = options.videoQuota - if (options.videoQuotaDaily !== undefined && options.videoQuotaDaily !== null) toSend['videoQuotaDaily'] = options.videoQuotaDaily - if (options.role !== undefined && options.role !== null) toSend['role'] = options.role - if (options.adminFlags !== undefined && options.adminFlags !== null) toSend['adminFlags'] = options.adminFlags - if (options.pluginAuth !== undefined) toSend['pluginAuth'] = options.pluginAuth - - return makePutBodyRequest({ - url: options.url, - path, - token: options.accessToken, - fields: toSend, - statusCodeExpected: HttpStatusCode.NO_CONTENT_204 - }) -} - -function askResetPassword (url: string, email: string) { - const path = '/api/v1/users/ask-reset-password' - - return makePostBodyRequest({ - url, - path, - fields: { email }, - statusCodeExpected: HttpStatusCode.NO_CONTENT_204 - }) -} - -function resetPassword ( - url: string, - userId: number, - verificationString: string, - password: string, - statusCodeExpected = HttpStatusCode.NO_CONTENT_204 -) { - const path = '/api/v1/users/' + userId + '/reset-password' - - return makePostBodyRequest({ - url, - path, - fields: { password, verificationString }, - statusCodeExpected - }) -} - -function askSendVerifyEmail (url: string, email: string) { - const path = '/api/v1/users/ask-send-verify-email' - - return makePostBodyRequest({ - url, - path, - fields: { email }, - statusCodeExpected: HttpStatusCode.NO_CONTENT_204 - }) -} - -function verifyEmail ( - url: string, - userId: number, - verificationString: string, - isPendingEmail = false, - statusCodeExpected = HttpStatusCode.NO_CONTENT_204 -) { - const path = '/api/v1/users/' + userId + '/verify-email' - - return makePostBodyRequest({ - url, - path, - fields: { - verificationString, - isPendingEmail - }, - statusCodeExpected - }) -} - // --------------------------------------------------------------------------- export { - createUser, - registerUser, - getMyUserInformation, - getMyUserVideoRating, - deleteMe, - registerUserWithChannel, - getMyUserVideoQuotaUsed, - getUsersList, - getUsersListPaginationAndSort, - removeUser, - updateUser, - updateMyUser, - getUserInformation, - blockUser, - unblockUser, - askResetPassword, - resetPassword, - renewUserScopedTokens, - updateMyAvatar, - generateUser, - askSendVerifyEmail, - generateUserAccessToken, - verifyEmail, - getUserScopedTokens + xxxgetMyUserInformation } diff --git a/shared/extra-utils/videos/channels.ts b/shared/extra-utils/videos/channels.ts index a77543c92..9e7ec565d 100644 --- a/shared/extra-utils/videos/channels.ts +++ b/shared/extra-utils/videos/channels.ts @@ -1,13 +1,11 @@ -import { User } from '../../models/users/user.model' import { ServerInfo } from '../server/servers' -import { getMyUserInformation } from '../users/users' function setDefaultVideoChannel (servers: ServerInfo[]) { const tasks: Promise[] = [] for (const server of servers) { - const p = getMyUserInformation(server.url, server.accessToken) - .then(res => { server.videoChannel = (res.body as User).videoChannels[0] }) + const p = server.usersCommand.getMyInfo() + .then(user => { server.videoChannel = user.videoChannels[0] }) tasks.push(p) } diff --git a/shared/extra-utils/videos/videos.ts b/shared/extra-utils/videos/videos.ts index 5dd71ce8b..5e20f8010 100644 --- a/shared/extra-utils/videos/videos.ts +++ b/shared/extra-utils/videos/videos.ts @@ -17,7 +17,7 @@ import { buildAbsoluteFixturePath, dateIsValid, testImage, wait, webtorrentAdd } import { makeGetRequest, makePutBodyRequest, makeRawRequest, makeUploadRequest } from '../requests/requests' import { waitJobs } from '../server/jobs' import { ServerInfo } from '../server/servers' -import { getMyUserInformation } from '../users/users' +import { xxxgetMyUserInformation } from '../users' loadLanguages() @@ -339,7 +339,7 @@ async function uploadVideo ( let defaultChannelId = '1' try { - const res = await getMyUserInformation(url, accessToken) + const res = await xxxgetMyUserInformation(url, accessToken) defaultChannelId = res.body.videoChannels[0].id } catch (e) { /* empty */ } diff --git a/shared/models/users/index.ts b/shared/models/users/index.ts index a9d578054..b61a8cd40 100644 --- a/shared/models/users/index.ts +++ b/shared/models/users/index.ts @@ -1,3 +1,4 @@ +export * from './user-create-result.model' export * from './user-create.model' export * from './user-flag.model' export * from './user-login.model' diff --git a/shared/models/users/user-create-result.model.ts b/shared/models/users/user-create-result.model.ts new file mode 100644 index 000000000..835b241ed --- /dev/null +++ b/shared/models/users/user-create-result.model.ts @@ -0,0 +1,7 @@ +export interface UserCreateResult { + id: number + + account: { + id: number + } +} -- cgit v1.2.3 From d23dd9fbfc4d26026352c10f81d2795ceaf2908a Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Thu, 15 Jul 2021 10:02:54 +0200 Subject: Introduce videos command --- scripts/benchmark.ts | 11 +- server/tests/api/activitypub/cleaner.ts | 50 +- server/tests/api/activitypub/client.ts | 11 +- server/tests/api/activitypub/fetch.ts | 33 +- server/tests/api/activitypub/refresher.ts | 29 +- server/tests/api/check-params/abuses.ts | 13 +- server/tests/api/check-params/live.ts | 5 +- server/tests/api/check-params/redundancy.ts | 9 +- server/tests/api/check-params/services.ts | 14 +- server/tests/api/check-params/upload-quota.ts | 37 +- server/tests/api/check-params/users.ts | 21 +- server/tests/api/check-params/video-blacklist.ts | 34 +- server/tests/api/check-params/video-captions.ts | 8 +- server/tests/api/check-params/video-comments.ts | 13 +- server/tests/api/check-params/video-playlists.ts | 29 +- server/tests/api/check-params/videos-history.ts | 13 +- server/tests/api/check-params/videos.ts | 109 ++-- server/tests/api/live/live-constraints.ts | 7 +- server/tests/api/live/live-permanent.ts | 11 +- server/tests/api/live/live-save-replay.ts | 48 +- server/tests/api/live/live-socket-messages.ts | 16 +- server/tests/api/live/live-views.ts | 18 +- server/tests/api/live/live.ts | 88 ++- server/tests/api/moderation/abuses.ts | 57 +- .../tests/api/moderation/blocklist-notification.ts | 16 +- server/tests/api/moderation/blocklist.ts | 100 ++- server/tests/api/moderation/video-blacklist.ts | 92 ++- .../api/notifications/comments-notifications.ts | 46 +- .../api/notifications/moderation-notifications.ts | 51 +- .../tests/api/notifications/notifications-api.ts | 11 +- .../tests/api/notifications/user-notifications.ts | 19 +- server/tests/api/redundancy/manage-redundancy.ts | 15 +- .../tests/api/redundancy/redundancy-constraints.ts | 8 +- server/tests/api/redundancy/redundancy.ts | 57 +- .../search/search-activitypub-video-channels.ts | 37 +- .../search/search-activitypub-video-playlists.ts | 9 +- .../tests/api/search/search-activitypub-videos.ts | 32 +- server/tests/api/search/search-index.ts | 4 +- server/tests/api/search/search-playlists.ts | 9 +- server/tests/api/search/search-videos.ts | 42 +- server/tests/api/server/bulk.ts | 33 +- server/tests/api/server/config.ts | 11 +- server/tests/api/server/email.ts | 24 +- server/tests/api/server/follow-constraints.ts | 146 ++--- server/tests/api/server/follows.ts | 65 +- server/tests/api/server/handle-down.ts | 73 +-- server/tests/api/server/jobs.ts | 5 +- server/tests/api/server/logs.ts | 23 +- server/tests/api/server/reverse-proxy.ts | 53 +- server/tests/api/server/services.ts | 19 +- server/tests/api/server/stats.ts | 15 +- server/tests/api/server/tracker.ts | 21 +- server/tests/api/users/user-subscriptions.ts | 56 +- server/tests/api/users/users-multiple-servers.ts | 34 +- server/tests/api/users/users.ts | 166 +++-- server/tests/api/videos/audio-only.ts | 20 +- server/tests/api/videos/multiple-servers.ts | 334 +++++----- server/tests/api/videos/resumable-upload.ts | 10 +- server/tests/api/videos/single-server.ts | 276 ++++---- server/tests/api/videos/video-captions.ts | 8 +- server/tests/api/videos/video-change-ownership.ts | 38 +- server/tests/api/videos/video-channels.ts | 69 +- server/tests/api/videos/video-comments.ts | 9 +- server/tests/api/videos/video-description.ts | 41 +- server/tests/api/videos/video-hls.ts | 32 +- server/tests/api/videos/video-imports.ts | 54 +- server/tests/api/videos/video-nsfw.ts | 40 +- .../tests/api/videos/video-playlist-thumbnails.ts | 5 +- server/tests/api/videos/video-playlists.ts | 19 +- server/tests/api/videos/video-privacy.ts | 146 ++--- server/tests/api/videos/video-schedule-update.ts | 69 +- server/tests/api/videos/video-transcoder.ts | 208 +++--- server/tests/api/videos/videos-filter.ts | 20 +- server/tests/api/videos/videos-history.ts | 38 +- server/tests/api/videos/videos-overview.ts | 22 +- server/tests/api/videos/videos-views-cleaner.ts | 14 +- server/tests/cli/create-import-video-file-job.ts | 52 +- server/tests/cli/create-transcoding-job.ts | 76 +-- server/tests/cli/optimize-old-videos.ts | 47 +- server/tests/cli/peertube.ts | 41 +- server/tests/cli/prune-storage.ts | 5 +- server/tests/cli/regenerate-thumbnails.ts | 33 +- server/tests/cli/update-host.ts | 29 +- server/tests/client.ts | 45 +- server/tests/external-plugins/auth-ldap.ts | 4 +- server/tests/external-plugins/auto-block-videos.ts | 38 +- server/tests/external-plugins/auto-mute.ts | 38 +- server/tests/feeds/feeds.ts | 24 +- server/tests/misc-endpoints.ts | 17 +- server/tests/plugins/action-hooks.ts | 17 +- server/tests/plugins/filter-hooks.ts | 94 ++- server/tests/plugins/plugin-helpers.ts | 57 +- server/tests/plugins/plugin-transcoding.ts | 23 +- server/tests/plugins/video-constants.ts | 52 +- server/tools/cli.ts | 2 +- server/tools/peertube-import-videos.ts | 29 +- server/tools/peertube-upload.ts | 11 +- shared/extra-utils/miscs/webtorrent.ts | 16 +- shared/extra-utils/requests/requests.ts | 25 +- shared/extra-utils/server/servers.ts | 5 +- shared/extra-utils/shared/abstract-command.ts | 41 +- shared/extra-utils/videos/index.ts | 1 + shared/extra-utils/videos/live-command.ts | 7 +- shared/extra-utils/videos/playlists-command.ts | 17 +- shared/extra-utils/videos/videos-command.ts | 583 +++++++++++++++++ shared/extra-utils/videos/videos.ts | 714 +-------------------- shared/models/search/videos-common-query.model.ts | 2 + shared/models/videos/video-update.model.ts | 1 + 108 files changed, 2489 insertions(+), 3105 deletions(-) create mode 100644 shared/extra-utils/videos/videos-command.ts diff --git a/scripts/benchmark.ts b/scripts/benchmark.ts index 272f9e8b1..d9e4a08ab 100644 --- a/scripts/benchmark.ts +++ b/scripts/benchmark.ts @@ -1,6 +1,6 @@ import * as autocannon from 'autocannon' import { writeJson } from 'fs-extra' -import { flushAndRunServer, getVideosList, killallServers, ServerInfo, setAccessTokensToServers, uploadVideo } from '@shared/extra-utils' +import { flushAndRunServer, killallServers, ServerInfo, setAccessTokensToServers } from '@shared/extra-utils' import { Video, VideoPrivacy } from '@shared/models' import { registerTSPaths } from '../server/helpers/register-ts-paths' @@ -197,7 +197,7 @@ async function prepare () { }) await setAccessTokensToServers([ server ]) - const videoAttributes = { + const attributes = { name: 'my super video', category: 2, nsfw: true, @@ -210,12 +210,11 @@ async function prepare () { } for (let i = 0; i < 10; i++) { - Object.assign(videoAttributes, { name: 'my super video ' + i }) - await uploadVideo(server.url, server.accessToken, videoAttributes) + await server.videosCommand.upload({ attributes: { ...attributes, name: 'my super video ' + i } }) } - const resVideos = await getVideosList(server.url) - video = resVideos.body.data.find(v => v.name === 'my super video 1') + const { data } = await server.videosCommand.list() + video = data.find(v => v.name === 'my super video 1') for (let i = 0; i < 10; i++) { const text = 'my super first comment' diff --git a/server/tests/api/activitypub/cleaner.ts b/server/tests/api/activitypub/cleaner.ts index 5b08880bf..dcf758711 100644 --- a/server/tests/api/activitypub/cleaner.ts +++ b/server/tests/api/activitypub/cleaner.ts @@ -6,11 +6,8 @@ import { cleanupTests, doubleFollow, flushAndRunMultipleServers, - getVideo, - rateVideo, ServerInfo, setAccessTokensToServers, - uploadVideoAndGetId, wait, waitJobs } from '@shared/extra-utils' @@ -49,9 +46,9 @@ describe('Test AP cleaner', function () { // Create 1 comment per video // Update 1 remote URL and 1 local URL on - videoUUID1 = (await uploadVideoAndGetId({ server: servers[0], videoName: 'server 1' })).uuid - videoUUID2 = (await uploadVideoAndGetId({ server: servers[1], videoName: 'server 2' })).uuid - videoUUID3 = (await uploadVideoAndGetId({ server: servers[2], videoName: 'server 3' })).uuid + videoUUID1 = (await servers[0].videosCommand.quickUpload({ name: 'server 1' })).uuid + videoUUID2 = (await servers[1].videosCommand.quickUpload({ name: 'server 2' })).uuid + videoUUID3 = (await servers[2].videosCommand.quickUpload({ name: 'server 3' })).uuid videoUUIDs = [ videoUUID1, videoUUID2, videoUUID3 ] @@ -59,7 +56,7 @@ describe('Test AP cleaner', function () { for (const server of servers) { for (const uuid of videoUUIDs) { - await rateVideo(server.url, server.accessToken, uuid, 'like') + await server.videosCommand.rate({ id: uuid, rating: 'like' }) await server.commentsCommand.createThread({ videoId: uuid, text: 'comment' }) } } @@ -70,9 +67,10 @@ describe('Test AP cleaner', function () { it('Should have the correct likes', async function () { for (const server of servers) { for (const uuid of videoUUIDs) { - const res = await getVideo(server.url, uuid) - expect(res.body.likes).to.equal(3) - expect(res.body.dislikes).to.equal(0) + const video = await server.videosCommand.get({ id: uuid }) + + expect(video.likes).to.equal(3) + expect(video.dislikes).to.equal(0) } } }) @@ -90,16 +88,16 @@ describe('Test AP cleaner', function () { // Updated rates of my video { - const res = await getVideo(servers[0].url, videoUUID1) - expect(res.body.likes).to.equal(2) - expect(res.body.dislikes).to.equal(0) + const video = await servers[0].videosCommand.get({ id: videoUUID1 }) + expect(video.likes).to.equal(2) + expect(video.dislikes).to.equal(0) } // Did not update rates of a remote video { - const res = await getVideo(servers[0].url, videoUUID2) - expect(res.body.likes).to.equal(3) - expect(res.body.dislikes).to.equal(0) + const video = await servers[0].videosCommand.get({ id: videoUUID2 }) + expect(video.likes).to.equal(3) + expect(video.dislikes).to.equal(0) } }) @@ -108,7 +106,7 @@ describe('Test AP cleaner', function () { for (const server of servers) { for (const uuid of videoUUIDs) { - await rateVideo(server.url, server.accessToken, uuid, 'dislike') + await server.videosCommand.rate({ id: uuid, rating: 'dislike' }) } } @@ -116,9 +114,9 @@ describe('Test AP cleaner', function () { for (const server of servers) { for (const uuid of videoUUIDs) { - const res = await getVideo(server.url, uuid) - expect(res.body.likes).to.equal(0) - expect(res.body.dislikes).to.equal(3) + const video = await server.videosCommand.get({ id: uuid }) + expect(video.likes).to.equal(0) + expect(video.dislikes).to.equal(3) } } }) @@ -137,16 +135,16 @@ describe('Test AP cleaner', function () { // Updated rates of my video { - const res = await getVideo(servers[0].url, videoUUID1) - expect(res.body.likes).to.equal(0) - expect(res.body.dislikes).to.equal(2) + const video = await servers[0].videosCommand.get({ id: videoUUID1 }) + expect(video.likes).to.equal(0) + expect(video.dislikes).to.equal(2) } // Did not update rates of a remote video { - const res = await getVideo(servers[0].url, videoUUID2) - expect(res.body.likes).to.equal(0) - expect(res.body.dislikes).to.equal(3) + const video = await servers[0].videosCommand.get({ id: videoUUID2 }) + expect(video.likes).to.equal(0) + expect(video.dislikes).to.equal(3) } }) diff --git a/server/tests/api/activitypub/client.ts b/server/tests/api/activitypub/client.ts index e8536a214..0190df04c 100644 --- a/server/tests/api/activitypub/client.ts +++ b/server/tests/api/activitypub/client.ts @@ -2,8 +2,7 @@ import 'mocha' import * as chai from 'chai' -import { VideoPlaylistPrivacy } from '@shared/models' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '@shared/core-utils' import { cleanupTests, doubleFollow, @@ -11,9 +10,9 @@ import { makeActivityPubGetRequest, ServerInfo, setAccessTokensToServers, - setDefaultVideoChannel, - uploadVideoAndGetId -} from '../../../../shared/extra-utils' + setDefaultVideoChannel +} from '@shared/extra-utils' +import { VideoPlaylistPrivacy } from '@shared/models' const expect = chai.expect @@ -69,7 +68,7 @@ describe('Test activitypub', function () { await setDefaultVideoChannel(servers) { - video = await uploadVideoAndGetId({ server: servers[0], videoName: 'video' }) + video = await await servers[0].videosCommand.quickUpload({ name: 'video' }) } { diff --git a/server/tests/api/activitypub/fetch.ts b/server/tests/api/activitypub/fetch.ts index 162f3ec83..5ab4a85d7 100644 --- a/server/tests/api/activitypub/fetch.ts +++ b/server/tests/api/activitypub/fetch.ts @@ -2,17 +2,7 @@ import 'mocha' import * as chai from 'chai' -import { - cleanupTests, - doubleFollow, - flushAndRunMultipleServers, - getVideosListSort, - ServerInfo, - setAccessTokensToServers, - uploadVideo, - waitJobs -} from '../../../../shared/extra-utils' -import { Video } from '../../../../shared/models/videos' +import { cleanupTests, doubleFollow, flushAndRunMultipleServers, ServerInfo, setAccessTokensToServers, waitJobs } from '@shared/extra-utils' const expect = chai.expect @@ -36,10 +26,9 @@ describe('Test ActivityPub fetcher', function () { const userAccessToken = await servers[0].loginCommand.getAccessToken(user) - await uploadVideo(servers[0].url, servers[0].accessToken, { name: 'video root' }) - const res = await uploadVideo(servers[0].url, servers[0].accessToken, { name: 'bad video root' }) - const badVideoUUID = res.body.video.uuid - await uploadVideo(servers[0].url, userAccessToken, { name: 'video user' }) + await servers[0].videosCommand.upload({ attributes: { name: 'video root' } }) + const { uuid } = await servers[0].videosCommand.upload({ attributes: { name: 'bad video root' } }) + await servers[0].videosCommand.upload({ token: userAccessToken, attributes: { name: 'video user' } }) { const to = 'http://localhost:' + servers[0].port + '/accounts/user1' @@ -48,8 +37,8 @@ describe('Test ActivityPub fetcher', function () { } { - const value = 'http://localhost:' + servers[2].port + '/videos/watch/' + badVideoUUID - await servers[0].sqlCommand.setVideoField(badVideoUUID, 'url', value) + const value = 'http://localhost:' + servers[2].port + '/videos/watch/' + uuid + await servers[0].sqlCommand.setVideoField(uuid, 'url', value) } }) @@ -60,20 +49,18 @@ describe('Test ActivityPub fetcher', function () { await waitJobs(servers) { - const res = await getVideosListSort(servers[0].url, 'createdAt') - expect(res.body.total).to.equal(3) + const { total, data } = await servers[0].videosCommand.list({ sort: 'createdAt' }) - const data: Video[] = res.body.data + expect(total).to.equal(3) expect(data[0].name).to.equal('video root') expect(data[1].name).to.equal('bad video root') expect(data[2].name).to.equal('video user') } { - const res = await getVideosListSort(servers[1].url, 'createdAt') - expect(res.body.total).to.equal(1) + const { total, data } = await servers[1].videosCommand.list({ sort: 'createdAt' }) - const data: Video[] = res.body.data + expect(total).to.equal(1) expect(data[0].name).to.equal('video root') } }) diff --git a/server/tests/api/activitypub/refresher.ts b/server/tests/api/activitypub/refresher.ts index 5a37dbc40..5af4b1edb 100644 --- a/server/tests/api/activitypub/refresher.ts +++ b/server/tests/api/activitypub/refresher.ts @@ -6,14 +6,11 @@ import { cleanupTests, doubleFollow, flushAndRunMultipleServers, - getVideo, killallServers, reRunServer, ServerInfo, setAccessTokensToServers, setDefaultVideoChannel, - uploadVideo, - uploadVideoAndGetId, wait, waitJobs } from '@shared/extra-utils' @@ -37,17 +34,17 @@ describe('Test AP refresher', function () { await setDefaultVideoChannel(servers) { - videoUUID1 = (await uploadVideoAndGetId({ server: servers[1], videoName: 'video1' })).uuid - videoUUID2 = (await uploadVideoAndGetId({ server: servers[1], videoName: 'video2' })).uuid - videoUUID3 = (await uploadVideoAndGetId({ server: servers[1], videoName: 'video3' })).uuid + videoUUID1 = (await servers[1].videosCommand.quickUpload({ name: 'video1' })).uuid + videoUUID2 = (await servers[1].videosCommand.quickUpload({ name: 'video2' })).uuid + videoUUID3 = (await servers[1].videosCommand.quickUpload({ name: 'video3' })).uuid } { - const a1 = await servers[1].usersCommand.generateUserAndToken('user1') - await uploadVideo(servers[1].url, a1, { name: 'video4' }) + const token1 = await servers[1].usersCommand.generateUserAndToken('user1') + await servers[1].videosCommand.upload({ token: token1, attributes: { name: 'video4' } }) - const a2 = await servers[1].usersCommand.generateUserAndToken('user2') - await uploadVideo(servers[1].url, a2, { name: 'video5' }) + const token2 = await servers[1].usersCommand.generateUserAndToken('user2') + await servers[1].videosCommand.upload({ token: token2, attributes: { name: 'video5' } }) } { @@ -75,13 +72,13 @@ describe('Test AP refresher', function () { // Change UUID so the remote server returns a 404 await servers[1].sqlCommand.setVideoField(videoUUID1, 'uuid', '304afe4f-39f9-4d49-8ed7-ac57b86b174f') - await getVideo(servers[0].url, videoUUID1) - await getVideo(servers[0].url, videoUUID2) + await servers[0].videosCommand.get({ id: videoUUID1 }) + await servers[0].videosCommand.get({ id: videoUUID2 }) await waitJobs(servers) - await getVideo(servers[0].url, videoUUID1, HttpStatusCode.NOT_FOUND_404) - await getVideo(servers[0].url, videoUUID2, HttpStatusCode.OK_200) + await servers[0].videosCommand.get({ id: videoUUID1, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) + await servers[0].videosCommand.get({ id: videoUUID2 }) }) it('Should not update a remote video if the remote instance is down', async function () { @@ -94,13 +91,13 @@ describe('Test AP refresher', function () { // Video will need a refresh await wait(10000) - await getVideo(servers[0].url, videoUUID3) + await servers[0].videosCommand.get({ id: videoUUID3 }) // The refresh should fail await waitJobs([ servers[0] ]) await reRunServer(servers[1]) - await getVideo(servers[0].url, videoUUID3, HttpStatusCode.OK_200) + await servers[0].videosCommand.get({ id: videoUUID3 }) }) }) diff --git a/server/tests/api/check-params/abuses.ts b/server/tests/api/check-params/abuses.ts index 4cd10a6fd..199cc5599 100644 --- a/server/tests/api/check-params/abuses.ts +++ b/server/tests/api/check-params/abuses.ts @@ -10,12 +10,10 @@ import { cleanupTests, doubleFollow, flushAndRunServer, - getVideoIdFromUUID, makeGetRequest, makePostBodyRequest, ServerInfo, setAccessTokensToServers, - uploadVideo, waitJobs } from '@shared/extra-utils' import { AbuseCreate, AbuseState } from '@shared/models' @@ -41,15 +39,10 @@ describe('Test abuses API validators', function () { await setAccessTokensToServers([ server ]) - const username = 'user1' - const password = 'my super password' - await server.usersCommand.create({ username: username, password: password }) - userToken = await server.loginCommand.getAccessToken({ username, password }) - + userToken = await server.usersCommand.generateUserAndToken('user_1') userToken2 = await server.usersCommand.generateUserAndToken('user_2') - const res = await uploadVideo(server.url, server.accessToken, {}) - server.video = res.body.video + server.video = await server.videosCommand.upload() command = server.abusesCommand }) @@ -421,7 +414,7 @@ describe('Test abuses API validators', function () { await doubleFollow(anotherServer, server) - const server2VideoId = await getVideoIdFromUUID(anotherServer.url, server.video.uuid) + const server2VideoId = await anotherServer.videosCommand.getId({ uuid: server.video.uuid }) await anotherServer.abusesCommand.report({ reason: 'remote server', videoId: server2VideoId }) await waitJobs([ server, anotherServer ]) diff --git a/server/tests/api/check-params/live.ts b/server/tests/api/check-params/live.ts index 78863fd50..4b54fc31c 100644 --- a/server/tests/api/check-params/live.ts +++ b/server/tests/api/check-params/live.ts @@ -13,8 +13,7 @@ import { sendRTMPStream, ServerInfo, setAccessTokensToServers, - stopFfmpeg, - uploadVideoAndGetId + stopFfmpeg } from '@shared/extra-utils' import { VideoCreateResult, VideoPrivacy } from '@shared/models' @@ -58,7 +57,7 @@ describe('Test video lives API validator', function () { } { - videoIdNotLive = (await uploadVideoAndGetId({ server, videoName: 'not live' })).id + videoIdNotLive = (await server.videosCommand.quickUpload({ name: 'not live' })).id } command = server.liveCommand diff --git a/server/tests/api/check-params/redundancy.ts b/server/tests/api/check-params/redundancy.ts index d93022c32..b1692b986 100644 --- a/server/tests/api/check-params/redundancy.ts +++ b/server/tests/api/check-params/redundancy.ts @@ -10,14 +10,12 @@ import { cleanupTests, doubleFollow, flushAndRunMultipleServers, - getVideo, makeDeleteRequest, makeGetRequest, makePostBodyRequest, makePutBodyRequest, ServerInfo, setAccessTokensToServers, - uploadVideoAndGetId, waitJobs } from '../../../../shared/extra-utils' @@ -45,14 +43,13 @@ describe('Test server redundancy API validators', function () { await servers[0].usersCommand.create({ username: user.username, password: user.password }) userAccessToken = await servers[0].loginCommand.getAccessToken(user) - videoIdLocal = (await uploadVideoAndGetId({ server: servers[0], videoName: 'video' })).id + videoIdLocal = (await servers[0].videosCommand.quickUpload({ name: 'video' })).id - const remoteUUID = (await uploadVideoAndGetId({ server: servers[1], videoName: 'video' })).uuid + const remoteUUID = (await servers[1].videosCommand.quickUpload({ name: 'video' })).uuid await waitJobs(servers) - const resVideo = await getVideo(servers[0].url, remoteUUID) - videoRemote = resVideo.body + videoRemote = await servers[0].videosCommand.get({ id: remoteUUID }) }) describe('When listing redundancies', function () { diff --git a/server/tests/api/check-params/services.ts b/server/tests/api/check-params/services.ts index 595fab70d..f86712b4e 100644 --- a/server/tests/api/check-params/services.ts +++ b/server/tests/api/check-params/services.ts @@ -1,17 +1,16 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ import 'mocha' -import { VideoPlaylistPrivacy } from '@shared/models' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '@shared/core-utils' import { cleanupTests, flushAndRunServer, makeGetRequest, ServerInfo, setAccessTokensToServers, - setDefaultVideoChannel, - uploadVideo -} from '../../../../shared/extra-utils' + setDefaultVideoChannel +} from '@shared/extra-utils' +import { VideoPlaylistPrivacy } from '@shared/models' describe('Test services API validators', function () { let server: ServerInfo @@ -26,10 +25,7 @@ describe('Test services API validators', function () { await setAccessTokensToServers([ server ]) await setDefaultVideoChannel([ server ]) - { - const res = await uploadVideo(server.url, server.accessToken, { name: 'my super name' }) - server.video = res.body.video - } + server.video = await server.videosCommand.upload({ attributes: { name: 'my super name' } }) { const created = await server.playlistsCommand.create({ diff --git a/server/tests/api/check-params/upload-quota.ts b/server/tests/api/check-params/upload-quota.ts index d94dec624..164c581e3 100644 --- a/server/tests/api/check-params/upload-quota.ts +++ b/server/tests/api/check-params/upload-quota.ts @@ -3,7 +3,6 @@ import 'mocha' import { expect } from 'chai' import { HttpStatusCode, randomInt } from '@shared/core-utils' -import { VideoImportState, VideoPrivacy } from '@shared/models' import { cleanupTests, flushAndRunServer, @@ -11,13 +10,15 @@ import { ServerInfo, setAccessTokensToServers, setDefaultVideoChannel, - uploadVideo, + VideosCommand, waitJobs -} from '../../../../shared/extra-utils' +} from '@shared/extra-utils' +import { VideoImportState, VideoPrivacy } from '@shared/models' describe('Test upload quota', function () { let server: ServerInfo let rootId: number + let command: VideosCommand // --------------------------------------------------------------- @@ -32,6 +33,8 @@ describe('Test upload quota', function () { rootId = user.id await server.usersCommand.update({ userId: rootId, videoQuota: 42 }) + + command = server.videosCommand }) describe('When having a video quota', function () { @@ -41,14 +44,14 @@ describe('Test upload quota', function () { const user = { username: 'registered' + randomInt(1, 1500), password: 'password' } await server.usersCommand.register(user) - const userAccessToken = await server.loginCommand.getAccessToken(user) + const userToken = await server.loginCommand.getAccessToken(user) - const videoAttributes = { fixture: 'video_short2.webm' } + const attributes = { fixture: 'video_short2.webm' } for (let i = 0; i < 5; i++) { - await uploadVideo(server.url, userAccessToken, videoAttributes) + await command.upload({ token: userToken, attributes }) } - await uploadVideo(server.url, userAccessToken, videoAttributes, HttpStatusCode.PAYLOAD_TOO_LARGE_413, 'legacy') + await command.upload({ token: userToken, attributes, expectedStatus: HttpStatusCode.PAYLOAD_TOO_LARGE_413, mode: 'legacy' }) }) it('Should fail with a registered user having too many videos with resumable upload', async function () { @@ -56,14 +59,14 @@ describe('Test upload quota', function () { const user = { username: 'registered' + randomInt(1, 1500), password: 'password' } await server.usersCommand.register(user) - const userAccessToken = await server.loginCommand.getAccessToken(user) + const userToken = await server.loginCommand.getAccessToken(user) - const videoAttributes = { fixture: 'video_short2.webm' } + const attributes = { fixture: 'video_short2.webm' } for (let i = 0; i < 5; i++) { - await uploadVideo(server.url, userAccessToken, videoAttributes) + await command.upload({ token: userToken, attributes }) } - await uploadVideo(server.url, userAccessToken, videoAttributes, HttpStatusCode.PAYLOAD_TOO_LARGE_413, 'resumable') + await command.upload({ token: userToken, attributes, expectedStatus: HttpStatusCode.PAYLOAD_TOO_LARGE_413, mode: 'resumable' }) }) it('Should fail to import with HTTP/Torrent/magnet', async function () { @@ -97,8 +100,8 @@ describe('Test upload quota', function () { it('Should fail with a user having too many videos daily', async function () { await server.usersCommand.update({ userId: rootId, videoQuotaDaily: 42 }) - await uploadVideo(server.url, server.accessToken, {}, HttpStatusCode.PAYLOAD_TOO_LARGE_413, 'legacy') - await uploadVideo(server.url, server.accessToken, {}, HttpStatusCode.PAYLOAD_TOO_LARGE_413, 'resumable') + await command.upload({ expectedStatus: HttpStatusCode.PAYLOAD_TOO_LARGE_413, mode: 'legacy' }) + await command.upload({ expectedStatus: HttpStatusCode.PAYLOAD_TOO_LARGE_413, mode: 'resumable' }) }) }) @@ -110,8 +113,8 @@ describe('Test upload quota', function () { videoQuotaDaily: 1024 * 1024 * 1024 }) - await uploadVideo(server.url, server.accessToken, {}, HttpStatusCode.PAYLOAD_TOO_LARGE_413, 'legacy') - await uploadVideo(server.url, server.accessToken, {}, HttpStatusCode.PAYLOAD_TOO_LARGE_413, 'resumable') + await command.upload({ expectedStatus: HttpStatusCode.PAYLOAD_TOO_LARGE_413, mode: 'legacy' }) + await command.upload({ expectedStatus: HttpStatusCode.PAYLOAD_TOO_LARGE_413, mode: 'resumable' }) }) it('Should fail if exceeding daily quota', async function () { @@ -121,8 +124,8 @@ describe('Test upload quota', function () { videoQuotaDaily: 42 }) - await uploadVideo(server.url, server.accessToken, {}, HttpStatusCode.PAYLOAD_TOO_LARGE_413, 'legacy') - await uploadVideo(server.url, server.accessToken, {}, HttpStatusCode.PAYLOAD_TOO_LARGE_413, 'resumable') + await command.upload({ expectedStatus: HttpStatusCode.PAYLOAD_TOO_LARGE_413, mode: 'legacy' }) + await command.upload({ expectedStatus: HttpStatusCode.PAYLOAD_TOO_LARGE_413, mode: 'resumable' }) }) }) diff --git a/server/tests/api/check-params/users.ts b/server/tests/api/check-params/users.ts index 801131918..33c48a009 100644 --- a/server/tests/api/check-params/users.ts +++ b/server/tests/api/check-params/users.ts @@ -2,10 +2,12 @@ import 'mocha' import { omit } from 'lodash' -import { UserRole, VideoCreateResult } from '../../../../shared' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '@shared/core-utils' import { buildAbsoluteFixturePath, + checkBadCountPagination, + checkBadSortPagination, + checkBadStartPagination, cleanupTests, flushAndRunServer, killallServers, @@ -13,19 +15,13 @@ import { makePostBodyRequest, makePutBodyRequest, makeUploadRequest, + MockSmtpServer, reRunServer, ServerInfo, setAccessTokensToServers, - uploadVideo, UsersCommand -} from '../../../../shared/extra-utils' -import { MockSmtpServer } from '../../../../shared/extra-utils/mock-servers/mock-email' -import { - checkBadCountPagination, - checkBadSortPagination, - checkBadStartPagination -} from '../../../../shared/extra-utils/requests/check-api-params' -import { UserAdminFlag } from '../../../../shared/models/users/user-flag.model' +} from '@shared/extra-utils' +import { UserAdminFlag, UserRole, VideoCreateResult } from '@shared/models' describe('Test users API validators', function () { const path = '/api/v1/users/' @@ -80,8 +76,7 @@ describe('Test users API validators', function () { } { - const res = await uploadVideo(server.url, server.accessToken, {}) - video = res.body.video + video = await server.videosCommand.upload() } { diff --git a/server/tests/api/check-params/video-blacklist.ts b/server/tests/api/check-params/video-blacklist.ts index 5097f8069..0fda31b29 100644 --- a/server/tests/api/check-params/video-blacklist.ts +++ b/server/tests/api/check-params/video-blacklist.ts @@ -11,20 +11,17 @@ import { cleanupTests, doubleFollow, flushAndRunMultipleServers, - getVideo, - getVideoWithToken, makePostBodyRequest, makePutBodyRequest, ServerInfo, setAccessTokensToServers, - uploadVideo, waitJobs } from '@shared/extra-utils' -import { VideoBlacklistType, VideoDetails } from '@shared/models' +import { VideoBlacklistType } from '@shared/models' describe('Test video blacklist API validators', function () { let servers: ServerInfo[] - let notBlacklistedVideoId: number + let notBlacklistedVideoId: string let remoteVideoUUID: string let userAccessToken1 = '' let userAccessToken2 = '' @@ -55,18 +52,17 @@ describe('Test video blacklist API validators', function () { } { - const res = await uploadVideo(servers[0].url, userAccessToken1, {}) - servers[0].video = res.body.video + servers[0].video = await servers[0].videosCommand.upload({ token: userAccessToken1 }) } { - const res = await uploadVideo(servers[0].url, servers[0].accessToken, {}) - notBlacklistedVideoId = res.body.video.uuid + const { uuid } = await servers[0].videosCommand.upload() + notBlacklistedVideoId = uuid } { - const res = await uploadVideo(servers[1].url, servers[1].accessToken, {}) - remoteVideoUUID = res.body.video.uuid + const { uuid } = await servers[1].videosCommand.upload() + remoteVideoUUID = uuid } await waitJobs(servers) @@ -204,17 +200,19 @@ describe('Test video blacklist API validators', function () { describe('When getting blacklisted video', function () { it('Should fail with a non authenticated user', async function () { - await getVideo(servers[0].url, servers[0].video.uuid, HttpStatusCode.UNAUTHORIZED_401) + await servers[0].videosCommand.get({ id: servers[0].video.uuid, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should fail with another user', async function () { - await getVideoWithToken(servers[0].url, userAccessToken2, servers[0].video.uuid, HttpStatusCode.FORBIDDEN_403) + await servers[0].videosCommand.getWithToken({ + token: userAccessToken2, + id: servers[0].video.uuid, + expectedStatus: HttpStatusCode.FORBIDDEN_403 + }) }) it('Should succeed with the owner authenticated user', async function () { - const res = await getVideoWithToken(servers[0].url, userAccessToken1, servers[0].video.uuid, HttpStatusCode.OK_200) - const video: VideoDetails = res.body - + const video = await servers[0].videosCommand.getWithToken({ token: userAccessToken1, id: servers[0].video.uuid }) expect(video.blacklisted).to.be.true }) @@ -222,9 +220,7 @@ describe('Test video blacklist API validators', function () { const video = servers[0].video for (const id of [ video.id, video.uuid, video.shortUUID ]) { - const res = await getVideoWithToken(servers[0].url, servers[0].accessToken, id, HttpStatusCode.OK_200) - const video: VideoDetails = res.body - + const video = await servers[0].videosCommand.getWithToken({ id, expectedStatus: HttpStatusCode.OK_200 }) expect(video.blacklisted).to.be.true } }) diff --git a/server/tests/api/check-params/video-captions.ts b/server/tests/api/check-params/video-captions.ts index 631ef4dac..f3941b3fa 100644 --- a/server/tests/api/check-params/video-captions.ts +++ b/server/tests/api/check-params/video-captions.ts @@ -10,8 +10,7 @@ import { makeGetRequest, makeUploadRequest, ServerInfo, - setAccessTokensToServers, - uploadVideo + setAccessTokensToServers } from '@shared/extra-utils' import { VideoCreateResult } from '@shared/models' @@ -31,10 +30,7 @@ describe('Test video captions API validator', function () { await setAccessTokensToServers([ server ]) - { - const res = await uploadVideo(server.url, server.accessToken, {}) - video = res.body.video - } + video = await server.videosCommand.upload() { const user = { diff --git a/server/tests/api/check-params/video-comments.ts b/server/tests/api/check-params/video-comments.ts index b7656a176..bdf7f91ee 100644 --- a/server/tests/api/check-params/video-comments.ts +++ b/server/tests/api/check-params/video-comments.ts @@ -13,8 +13,7 @@ import { makeGetRequest, makePostBodyRequest, ServerInfo, - setAccessTokensToServers, - uploadVideo + setAccessTokensToServers } from '@shared/extra-utils' import { VideoCreateResult } from '@shared/models' @@ -39,8 +38,7 @@ describe('Test video comments API validator', function () { await setAccessTokensToServers([ server ]) { - const res = await uploadVideo(server.url, server.accessToken, {}) - video = res.body.video + const video = await server.videosCommand.upload({ attributes: {} }) pathThread = '/api/v1/videos/' + video.uuid + '/comment-threads' } @@ -291,8 +289,8 @@ describe('Test video comments API validator', function () { let anotherVideoUUID: string { - const res = await uploadVideo(server.url, userAccessToken, { name: 'video' }) - anotherVideoUUID = res.body.video.uuid + const { uuid } = await server.videosCommand.upload({ token: userAccessToken, attributes: { name: 'video' } }) + anotherVideoUUID = uuid } { @@ -318,8 +316,7 @@ describe('Test video comments API validator', function () { describe('When a video has comments disabled', function () { before(async function () { - const res = await uploadVideo(server.url, server.accessToken, { commentsEnabled: false }) - video = res.body.video + video = await server.videosCommand.upload({ attributes: { commentsEnabled: false } }) pathThread = '/api/v1/videos/' + video.uuid + '/comment-threads' }) diff --git a/server/tests/api/check-params/video-playlists.ts b/server/tests/api/check-params/video-playlists.ts index 46c09bb11..ebd7e2413 100644 --- a/server/tests/api/check-params/video-playlists.ts +++ b/server/tests/api/check-params/video-playlists.ts @@ -2,15 +2,6 @@ import 'mocha' import { HttpStatusCode } from '@shared/core-utils' -import { - VideoPlaylistCreate, - VideoPlaylistCreateResult, - VideoPlaylistElementCreate, - VideoPlaylistElementUpdate, - VideoPlaylistPrivacy, - VideoPlaylistReorder, - VideoPlaylistType -} from '@shared/models' import { checkBadCountPagination, checkBadSortPagination, @@ -21,9 +12,17 @@ import { PlaylistsCommand, ServerInfo, setAccessTokensToServers, - setDefaultVideoChannel, - uploadVideoAndGetId -} from '../../../../shared/extra-utils' + setDefaultVideoChannel +} from '@shared/extra-utils' +import { + VideoPlaylistCreate, + VideoPlaylistCreateResult, + VideoPlaylistElementCreate, + VideoPlaylistElementUpdate, + VideoPlaylistPrivacy, + VideoPlaylistReorder, + VideoPlaylistType +} from '@shared/models' describe('Test video playlists API validator', function () { let server: ServerInfo @@ -49,7 +48,7 @@ describe('Test video playlists API validator', function () { await setDefaultVideoChannel([ server ]) userAccessToken = await server.usersCommand.generateUserAndToken('user1') - videoId = (await uploadVideoAndGetId({ server, videoName: 'video 1' })).id + videoId = (await server.videosCommand.quickUpload({ name: 'video 1' })).id command = server.playlistsCommand @@ -486,8 +485,8 @@ describe('Test video playlists API validator', function () { } before(async function () { - videoId3 = (await uploadVideoAndGetId({ server, videoName: 'video 3' })).id - videoId4 = (await uploadVideoAndGetId({ server, videoName: 'video 4' })).id + videoId3 = (await server.videosCommand.quickUpload({ name: 'video 3' })).id + videoId4 = (await server.videosCommand.quickUpload({ name: 'video 4' })).id for (const id of [ videoId3, videoId4 ]) { await command.addElement({ playlistId: playlist.shortUUID, attributes: { videoId: id } }) diff --git a/server/tests/api/check-params/videos-history.ts b/server/tests/api/check-params/videos-history.ts index 0e91fe0a8..1da922a17 100644 --- a/server/tests/api/check-params/videos-history.ts +++ b/server/tests/api/check-params/videos-history.ts @@ -1,6 +1,7 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ import 'mocha' +import { HttpStatusCode } from '@shared/core-utils' import { checkBadCountPagination, checkBadStartPagination, @@ -10,10 +11,8 @@ import { makePostBodyRequest, makePutBodyRequest, ServerInfo, - setAccessTokensToServers, - uploadVideo -} from '../../../../shared/extra-utils' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' + setAccessTokensToServers +} from '@shared/extra-utils' describe('Test videos history API validator', function () { const myHistoryPath = '/api/v1/users/me/history/videos' @@ -30,10 +29,8 @@ describe('Test videos history API validator', function () { await setAccessTokensToServers([ server ]) - const res = await uploadVideo(server.url, server.accessToken, {}) - const videoUUID = res.body.video.uuid - - watchingPath = '/api/v1/videos/' + videoUUID + '/watching' + const { uuid } = await server.videosCommand.upload() + watchingPath = '/api/v1/videos/' + uuid + '/watching' }) describe('When notifying a user is watching a video', function () { diff --git a/server/tests/api/check-params/videos.ts b/server/tests/api/check-params/videos.ts index 855b09f39..8f9f33b8c 100644 --- a/server/tests/api/check-params/videos.ts +++ b/server/tests/api/check-params/videos.ts @@ -4,30 +4,23 @@ import 'mocha' import * as chai from 'chai' import { omit } from 'lodash' import { join } from 'path' -import { randomInt } from '@shared/core-utils' -import { PeerTubeProblemDocument, VideoCreateResult } from '@shared/models' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode, randomInt } from '@shared/core-utils' import { + checkBadCountPagination, + checkBadSortPagination, + checkBadStartPagination, checkUploadVideoParam, cleanupTests, flushAndRunServer, - getVideo, - getVideosList, makeDeleteRequest, makeGetRequest, makePutBodyRequest, makeUploadRequest, - removeVideo, root, ServerInfo, setAccessTokensToServers -} from '../../../../shared/extra-utils' -import { - checkBadCountPagination, - checkBadSortPagination, - checkBadStartPagination -} from '../../../../shared/extra-utils/requests/check-api-params' -import { VideoPrivacy } from '../../../../shared/models/videos/video-privacy.enum' +} from '@shared/extra-utils' +import { PeerTubeProblemDocument, VideoCreateResult, VideoPrivacy } from '@shared/models' const expect = chai.expect @@ -210,70 +203,70 @@ describe('Test videos API validator', function () { it('Should fail with nothing', async function () { const fields = {} const attaches = {} - await checkUploadVideoParam(server.url, server.accessToken, { ...fields, ...attaches }, HttpStatusCode.BAD_REQUEST_400, mode) + await checkUploadVideoParam(server, server.accessToken, { ...fields, ...attaches }, HttpStatusCode.BAD_REQUEST_400, mode) }) it('Should fail without name', async function () { const fields = omit(baseCorrectParams, 'name') const attaches = baseCorrectAttaches - await checkUploadVideoParam(server.url, server.accessToken, { ...fields, ...attaches }, HttpStatusCode.BAD_REQUEST_400, mode) + await checkUploadVideoParam(server, server.accessToken, { ...fields, ...attaches }, HttpStatusCode.BAD_REQUEST_400, mode) }) it('Should fail with a long name', async function () { const fields = { ...baseCorrectParams, name: 'super'.repeat(65) } const attaches = baseCorrectAttaches - await checkUploadVideoParam(server.url, server.accessToken, { ...fields, ...attaches }, HttpStatusCode.BAD_REQUEST_400, mode) + await checkUploadVideoParam(server, server.accessToken, { ...fields, ...attaches }, HttpStatusCode.BAD_REQUEST_400, mode) }) it('Should fail with a bad category', async function () { const fields = { ...baseCorrectParams, category: 125 } const attaches = baseCorrectAttaches - await checkUploadVideoParam(server.url, server.accessToken, { ...fields, ...attaches }, HttpStatusCode.BAD_REQUEST_400, mode) + await checkUploadVideoParam(server, server.accessToken, { ...fields, ...attaches }, HttpStatusCode.BAD_REQUEST_400, mode) }) it('Should fail with a bad licence', async function () { const fields = { ...baseCorrectParams, licence: 125 } const attaches = baseCorrectAttaches - await checkUploadVideoParam(server.url, server.accessToken, { ...fields, ...attaches }, HttpStatusCode.BAD_REQUEST_400, mode) + await checkUploadVideoParam(server, server.accessToken, { ...fields, ...attaches }, HttpStatusCode.BAD_REQUEST_400, mode) }) it('Should fail with a bad language', async function () { const fields = { ...baseCorrectParams, language: 'a'.repeat(15) } const attaches = baseCorrectAttaches - await checkUploadVideoParam(server.url, server.accessToken, { ...fields, ...attaches }, HttpStatusCode.BAD_REQUEST_400, mode) + await checkUploadVideoParam(server, server.accessToken, { ...fields, ...attaches }, HttpStatusCode.BAD_REQUEST_400, mode) }) it('Should fail with a long description', async function () { const fields = { ...baseCorrectParams, description: 'super'.repeat(2500) } const attaches = baseCorrectAttaches - await checkUploadVideoParam(server.url, server.accessToken, { ...fields, ...attaches }, HttpStatusCode.BAD_REQUEST_400, mode) + await checkUploadVideoParam(server, server.accessToken, { ...fields, ...attaches }, HttpStatusCode.BAD_REQUEST_400, mode) }) it('Should fail with a long support text', async function () { const fields = { ...baseCorrectParams, support: 'super'.repeat(201) } const attaches = baseCorrectAttaches - await checkUploadVideoParam(server.url, server.accessToken, { ...fields, ...attaches }, HttpStatusCode.BAD_REQUEST_400, mode) + await checkUploadVideoParam(server, server.accessToken, { ...fields, ...attaches }, HttpStatusCode.BAD_REQUEST_400, mode) }) it('Should fail without a channel', async function () { const fields = omit(baseCorrectParams, 'channelId') const attaches = baseCorrectAttaches - await checkUploadVideoParam(server.url, server.accessToken, { ...fields, ...attaches }, HttpStatusCode.BAD_REQUEST_400, mode) + await checkUploadVideoParam(server, server.accessToken, { ...fields, ...attaches }, HttpStatusCode.BAD_REQUEST_400, mode) }) it('Should fail with a bad channel', async function () { const fields = { ...baseCorrectParams, channelId: 545454 } const attaches = baseCorrectAttaches - await checkUploadVideoParam(server.url, server.accessToken, { ...fields, ...attaches }, HttpStatusCode.BAD_REQUEST_400, mode) + await checkUploadVideoParam(server, server.accessToken, { ...fields, ...attaches }, HttpStatusCode.BAD_REQUEST_400, mode) }) it('Should fail with another user channel', async function () { @@ -290,35 +283,35 @@ describe('Test videos API validator', function () { const fields = { ...baseCorrectParams, channelId: customChannelId } const attaches = baseCorrectAttaches - await checkUploadVideoParam(server.url, userAccessToken, { ...fields, ...attaches }, HttpStatusCode.BAD_REQUEST_400, mode) + await checkUploadVideoParam(server, userAccessToken, { ...fields, ...attaches }, HttpStatusCode.BAD_REQUEST_400, mode) }) it('Should fail with too many tags', async function () { const fields = { ...baseCorrectParams, tags: [ 'tag1', 'tag2', 'tag3', 'tag4', 'tag5', 'tag6' ] } const attaches = baseCorrectAttaches - await checkUploadVideoParam(server.url, server.accessToken, { ...fields, ...attaches }, HttpStatusCode.BAD_REQUEST_400, mode) + await checkUploadVideoParam(server, server.accessToken, { ...fields, ...attaches }, HttpStatusCode.BAD_REQUEST_400, mode) }) it('Should fail with a tag length too low', async function () { const fields = { ...baseCorrectParams, tags: [ 'tag1', 't' ] } const attaches = baseCorrectAttaches - await checkUploadVideoParam(server.url, server.accessToken, { ...fields, ...attaches }, HttpStatusCode.BAD_REQUEST_400, mode) + await checkUploadVideoParam(server, server.accessToken, { ...fields, ...attaches }, HttpStatusCode.BAD_REQUEST_400, mode) }) it('Should fail with a tag length too big', async function () { const fields = { ...baseCorrectParams, tags: [ 'tag1', 'my_super_tag_too_long_long_long_long_long_long' ] } const attaches = baseCorrectAttaches - await checkUploadVideoParam(server.url, server.accessToken, { ...fields, ...attaches }, HttpStatusCode.BAD_REQUEST_400, mode) + await checkUploadVideoParam(server, server.accessToken, { ...fields, ...attaches }, HttpStatusCode.BAD_REQUEST_400, mode) }) it('Should fail with a bad schedule update (miss updateAt)', async function () { const fields = { ...baseCorrectParams, scheduleUpdate: { privacy: VideoPrivacy.PUBLIC } } const attaches = baseCorrectAttaches - await checkUploadVideoParam(server.url, server.accessToken, { ...fields, ...attaches }, HttpStatusCode.BAD_REQUEST_400, mode) + await checkUploadVideoParam(server, server.accessToken, { ...fields, ...attaches }, HttpStatusCode.BAD_REQUEST_400, mode) }) it('Should fail with a bad schedule update (wrong updateAt)', async function () { @@ -332,20 +325,20 @@ describe('Test videos API validator', function () { } const attaches = baseCorrectAttaches - await checkUploadVideoParam(server.url, server.accessToken, { ...fields, ...attaches }, HttpStatusCode.BAD_REQUEST_400, mode) + await checkUploadVideoParam(server, server.accessToken, { ...fields, ...attaches }, HttpStatusCode.BAD_REQUEST_400, mode) }) it('Should fail with a bad originally published at attribute', async function () { const fields = { ...baseCorrectParams, originallyPublishedAt: 'toto' } const attaches = baseCorrectAttaches - await checkUploadVideoParam(server.url, server.accessToken, { ...fields, ...attaches }, HttpStatusCode.BAD_REQUEST_400, mode) + await checkUploadVideoParam(server, server.accessToken, { ...fields, ...attaches }, HttpStatusCode.BAD_REQUEST_400, mode) }) it('Should fail without an input file', async function () { const fields = baseCorrectParams const attaches = {} - await checkUploadVideoParam(server.url, server.accessToken, { ...fields, ...attaches }, HttpStatusCode.BAD_REQUEST_400, mode) + await checkUploadVideoParam(server, server.accessToken, { ...fields, ...attaches }, HttpStatusCode.BAD_REQUEST_400, mode) }) it('Should fail with an incorrect input file', async function () { @@ -353,7 +346,7 @@ describe('Test videos API validator', function () { let attaches = { fixture: join(root(), 'server', 'tests', 'fixtures', 'video_short_fake.webm') } await checkUploadVideoParam( - server.url, + server, server.accessToken, { ...fields, ...attaches }, HttpStatusCode.UNPROCESSABLE_ENTITY_422, @@ -362,7 +355,7 @@ describe('Test videos API validator', function () { attaches = { fixture: join(root(), 'server', 'tests', 'fixtures', 'video_short.mkv') } await checkUploadVideoParam( - server.url, + server, server.accessToken, { ...fields, ...attaches }, HttpStatusCode.UNSUPPORTED_MEDIA_TYPE_415, @@ -377,7 +370,7 @@ describe('Test videos API validator', function () { fixture: join(root(), 'server', 'tests', 'fixtures', 'video_short.mp4') } - await checkUploadVideoParam(server.url, server.accessToken, { ...fields, ...attaches }, HttpStatusCode.BAD_REQUEST_400, mode) + await checkUploadVideoParam(server, server.accessToken, { ...fields, ...attaches }, HttpStatusCode.BAD_REQUEST_400, mode) }) it('Should fail with a big thumbnail file', async function () { @@ -387,7 +380,7 @@ describe('Test videos API validator', function () { fixture: join(root(), 'server', 'tests', 'fixtures', 'video_short.mp4') } - await checkUploadVideoParam(server.url, server.accessToken, { ...fields, ...attaches }, HttpStatusCode.BAD_REQUEST_400, mode) + await checkUploadVideoParam(server, server.accessToken, { ...fields, ...attaches }, HttpStatusCode.BAD_REQUEST_400, mode) }) it('Should fail with an incorrect preview file', async function () { @@ -397,7 +390,7 @@ describe('Test videos API validator', function () { fixture: join(root(), 'server', 'tests', 'fixtures', 'video_short.mp4') } - await checkUploadVideoParam(server.url, server.accessToken, { ...fields, ...attaches }, HttpStatusCode.BAD_REQUEST_400, mode) + await checkUploadVideoParam(server, server.accessToken, { ...fields, ...attaches }, HttpStatusCode.BAD_REQUEST_400, mode) }) it('Should fail with a big preview file', async function () { @@ -407,7 +400,7 @@ describe('Test videos API validator', function () { fixture: join(root(), 'server', 'tests', 'fixtures', 'video_short.mp4') } - await checkUploadVideoParam(server.url, server.accessToken, { ...fields, ...attaches }, HttpStatusCode.BAD_REQUEST_400, mode) + await checkUploadVideoParam(server, server.accessToken, { ...fields, ...attaches }, HttpStatusCode.BAD_REQUEST_400, mode) }) it('Should report the appropriate error', async function () { @@ -415,9 +408,9 @@ describe('Test videos API validator', function () { const attaches = baseCorrectAttaches const attributes = { ...fields, ...attaches } - const res = await checkUploadVideoParam(server.url, server.accessToken, attributes, HttpStatusCode.BAD_REQUEST_400, mode) + const body = await checkUploadVideoParam(server, server.accessToken, attributes, HttpStatusCode.BAD_REQUEST_400, mode) - const error = res.body as PeerTubeProblemDocument + const error = body as unknown as PeerTubeProblemDocument if (mode === 'legacy') { expect(error.docs).to.equal('https://docs.joinpeertube.org/api-rest-reference.html#operation/uploadLegacy') @@ -442,7 +435,7 @@ describe('Test videos API validator', function () { { const attaches = baseCorrectAttaches - await checkUploadVideoParam(server.url, server.accessToken, { ...fields, ...attaches }, HttpStatusCode.OK_200, mode) + await checkUploadVideoParam(server, server.accessToken, { ...fields, ...attaches }, HttpStatusCode.OK_200, mode) } { @@ -452,7 +445,7 @@ describe('Test videos API validator', function () { videofile: join(root(), 'server', 'tests', 'fixtures', 'video_short.mp4') } - await checkUploadVideoParam(server.url, server.accessToken, { ...fields, ...attaches }, HttpStatusCode.OK_200, mode) + await checkUploadVideoParam(server, server.accessToken, { ...fields, ...attaches }, HttpStatusCode.OK_200, mode) } { @@ -462,7 +455,7 @@ describe('Test videos API validator', function () { videofile: join(root(), 'server', 'tests', 'fixtures', 'video_short.ogv') } - await checkUploadVideoParam(server.url, server.accessToken, { ...fields, ...attaches }, HttpStatusCode.OK_200, mode) + await checkUploadVideoParam(server, server.accessToken, { ...fields, ...attaches }, HttpStatusCode.OK_200, mode) } }) } @@ -491,8 +484,8 @@ describe('Test videos API validator', function () { } before(async function () { - const res = await getVideosList(server.url) - video = res.body.data[0] + const { data } = await server.videosCommand.list() + video = data[0] }) it('Should fail with nothing', async function () { @@ -717,16 +710,16 @@ describe('Test videos API validator', function () { }) it('Should fail without a correct uuid', async function () { - await getVideo(server.url, 'coucou', HttpStatusCode.BAD_REQUEST_400) + await server.videosCommand.get({ id: 'coucou', expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) it('Should return 404 with an incorrect video', async function () { - await getVideo(server.url, '4da6fde3-88f7-4d16-b119-108df5630b06', HttpStatusCode.NOT_FOUND_404) + await server.videosCommand.get({ id: '4da6fde3-88f7-4d16-b119-108df5630b06', expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) it('Shoud report the appropriate error', async function () { - const res = await getVideo(server.url, 'hi', HttpStatusCode.BAD_REQUEST_400) - const error = res.body as PeerTubeProblemDocument + const body = await server.videosCommand.get({ id: 'hi', expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) + const error = body as unknown as PeerTubeProblemDocument expect(error.docs).to.equal('https://docs.joinpeertube.org/api-rest-reference.html#operation/getVideo') @@ -741,16 +734,16 @@ describe('Test videos API validator', function () { }) it('Should succeed with the correct parameters', async function () { - await getVideo(server.url, video.shortUUID) + await server.videosCommand.get({ id: video.shortUUID }) }) }) describe('When rating a video', function () { - let videoId + let videoId: number before(async function () { - const res = await getVideosList(server.url) - videoId = res.body.data[0].id + const { data } = await server.videosCommand.list() + videoId = data[0].id }) it('Should fail without a valid uuid', async function () { @@ -804,22 +797,22 @@ describe('Test videos API validator', function () { }) it('Should fail without a correct uuid', async function () { - await removeVideo(server.url, server.accessToken, 'hello', HttpStatusCode.BAD_REQUEST_400) + await server.videosCommand.remove({ id: 'hello', expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) it('Should fail with a video which does not exist', async function () { - await removeVideo(server.url, server.accessToken, '4da6fde3-88f7-4d16-b119-108df5630b06', HttpStatusCode.NOT_FOUND_404) + await server.videosCommand.remove({ id: '4da6fde3-88f7-4d16-b119-108df5630b06', expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) it('Should fail with a video of another user without the appropriate right', async function () { - await removeVideo(server.url, userAccessToken, video.uuid, HttpStatusCode.FORBIDDEN_403) + await server.videosCommand.remove({ token: userAccessToken, id: video.uuid, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) it('Should fail with a video of another server') it('Shoud report the appropriate error', async function () { - const res = await removeVideo(server.url, server.accessToken, 'hello', HttpStatusCode.BAD_REQUEST_400) - const error = res.body as PeerTubeProblemDocument + const body = await server.videosCommand.remove({ id: 'hello', expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) + const error = body as unknown as PeerTubeProblemDocument expect(error.docs).to.equal('https://docs.joinpeertube.org/api-rest-reference.html#operation/delVideo') @@ -834,7 +827,7 @@ describe('Test videos API validator', function () { }) it('Should succeed with the correct parameters', async function () { - await removeVideo(server.url, server.accessToken, video.uuid) + await server.videosCommand.remove({ id: video.uuid }) }) }) diff --git a/server/tests/api/live/live-constraints.ts b/server/tests/api/live/live-constraints.ts index 290d325d4..7900b1abe 100644 --- a/server/tests/api/live/live-constraints.ts +++ b/server/tests/api/live/live-constraints.ts @@ -2,14 +2,13 @@ import 'mocha' import * as chai from 'chai' -import { VideoDetails, VideoPrivacy } from '@shared/models' +import { VideoPrivacy } from '@shared/models' import { checkLiveCleanup, cleanupTests, ConfigCommand, doubleFollow, flushAndRunMultipleServers, - getVideo, ServerInfo, setAccessTokensToServers, setDefaultVideoChannel, @@ -39,9 +38,7 @@ describe('Test live constraints', function () { async function checkSaveReplay (videoId: string, resolutions = [ 720 ]) { for (const server of servers) { - const res = await getVideo(server.url, videoId) - - const video: VideoDetails = res.body + const video = await server.videosCommand.get({ id: videoId }) expect(video.isLive).to.be.false expect(video.duration).to.be.greaterThan(0) } diff --git a/server/tests/api/live/live-permanent.ts b/server/tests/api/live/live-permanent.ts index 6f4915a6b..707f2edf8 100644 --- a/server/tests/api/live/live-permanent.ts +++ b/server/tests/api/live/live-permanent.ts @@ -2,13 +2,12 @@ import 'mocha' import * as chai from 'chai' -import { LiveVideoCreate, VideoDetails, VideoPrivacy, VideoState } from '@shared/models' +import { LiveVideoCreate, VideoPrivacy, VideoState } from '@shared/models' import { cleanupTests, ConfigCommand, doubleFollow, flushAndRunMultipleServers, - getVideo, ServerInfo, setAccessTokensToServers, setDefaultVideoChannel, @@ -38,8 +37,8 @@ describe('Permanent live', function () { async function checkVideoState (videoId: string, state: VideoState) { for (const server of servers) { - const res = await getVideo(server.url, videoId) - expect((res.body as VideoDetails).state.id).to.equal(state) + const video = await server.videosCommand.get({ id: videoId }) + expect(video.state.id).to.equal(state) } } @@ -123,9 +122,7 @@ describe('Permanent live', function () { await waitJobs(servers) for (const server of servers) { - const res = await getVideo(server.url, videoUUID) - - const videoDetails = res.body as VideoDetails + const videoDetails = await server.videosCommand.get({ id: videoUUID }) expect(videoDetails.streamingPlaylists).to.have.lengthOf(1) } }) diff --git a/server/tests/api/live/live-save-replay.ts b/server/tests/api/live/live-save-replay.ts index 363fb561c..a87a2cd12 100644 --- a/server/tests/api/live/live-save-replay.ts +++ b/server/tests/api/live/live-save-replay.ts @@ -3,26 +3,22 @@ import 'mocha' import * as chai from 'chai' import { FfmpegCommand } from 'fluent-ffmpeg' -import { LiveVideoCreate, VideoDetails, VideoPrivacy, VideoState } from '@shared/models' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '@shared/core-utils' import { checkLiveCleanup, cleanupTests, ConfigCommand, doubleFollow, flushAndRunMultipleServers, - getVideo, - getVideosList, - removeVideo, ServerInfo, setAccessTokensToServers, setDefaultVideoChannel, stopFfmpeg, testFfmpegStreamError, - updateVideo, wait, waitJobs -} from '../../../../shared/extra-utils' +} from '@shared/extra-utils' +import { LiveVideoCreate, VideoPrivacy, VideoState } from '@shared/models' const expect = chai.expect @@ -34,7 +30,7 @@ describe('Save replay setting', function () { async function createLiveWrapper (saveReplay: boolean) { if (liveVideoUUID) { try { - await removeVideo(servers[0].url, servers[0].accessToken, liveVideoUUID) + await servers[0].videosCommand.remove({ id: liveVideoUUID }) await waitJobs(servers) } catch {} } @@ -50,24 +46,24 @@ describe('Save replay setting', function () { return uuid } - async function checkVideosExist (videoId: string, existsInList: boolean, getStatus?: number) { + async function checkVideosExist (videoId: string, existsInList: boolean, expectedStatus?: number) { for (const server of servers) { const length = existsInList ? 1 : 0 - const resVideos = await getVideosList(server.url) - expect(resVideos.body.data).to.have.lengthOf(length) - expect(resVideos.body.total).to.equal(length) + const { data, total } = await server.videosCommand.list() + expect(data).to.have.lengthOf(length) + expect(total).to.equal(length) - if (getStatus) { - await getVideo(server.url, videoId, getStatus) + if (expectedStatus) { + await server.videosCommand.get({ id: videoId, expectedStatus }) } } } async function checkVideoState (videoId: string, state: VideoState) { for (const server of servers) { - const res = await getVideo(server.url, videoId) - expect((res.body as VideoDetails).state.id).to.equal(state) + const video = await server.videosCommand.get({ id: videoId }) + expect(video.state.id).to.equal(state) } } @@ -179,8 +175,8 @@ describe('Save replay setting', function () { await checkVideosExist(liveVideoUUID, false) - await getVideo(servers[0].url, liveVideoUUID, HttpStatusCode.UNAUTHORIZED_401) - await getVideo(servers[1].url, liveVideoUUID, HttpStatusCode.NOT_FOUND_404) + await servers[0].videosCommand.get({ id: liveVideoUUID, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) + await servers[1].videosCommand.get({ id: liveVideoUUID, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) await wait(5000) await waitJobs(servers) @@ -201,7 +197,7 @@ describe('Save replay setting', function () { await Promise.all([ testFfmpegStreamError(ffmpegCommand, true), - removeVideo(servers[0].url, servers[0].accessToken, liveVideoUUID) + servers[0].videosCommand.remove({ id: liveVideoUUID }) ]) await wait(5000) @@ -253,13 +249,13 @@ describe('Save replay setting', function () { it('Should update the saved live and correctly federate the updated attributes', async function () { this.timeout(30000) - await updateVideo(servers[0].url, servers[0].accessToken, liveVideoUUID, { name: 'video updated' }) + await servers[0].videosCommand.update({ id: liveVideoUUID, attributes: { name: 'video updated' } }) await waitJobs(servers) for (const server of servers) { - const res = await getVideo(server.url, liveVideoUUID) - expect(res.body.name).to.equal('video updated') - expect(res.body.isLive).to.be.false + const video = await server.videosCommand.get({ id: liveVideoUUID }) + expect(video.name).to.equal('video updated') + expect(video.isLive).to.be.false } }) @@ -287,8 +283,8 @@ describe('Save replay setting', function () { await checkVideosExist(liveVideoUUID, false) - await getVideo(servers[0].url, liveVideoUUID, HttpStatusCode.UNAUTHORIZED_401) - await getVideo(servers[1].url, liveVideoUUID, HttpStatusCode.NOT_FOUND_404) + await servers[0].videosCommand.get({ id: liveVideoUUID, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) + await servers[1].videosCommand.get({ id: liveVideoUUID, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) await wait(5000) await waitJobs(servers) @@ -307,7 +303,7 @@ describe('Save replay setting', function () { await checkVideosExist(liveVideoUUID, true, HttpStatusCode.OK_200) await Promise.all([ - removeVideo(servers[0].url, servers[0].accessToken, liveVideoUUID), + servers[0].videosCommand.remove({ id: liveVideoUUID }), testFfmpegStreamError(ffmpegCommand, true) ]) diff --git a/server/tests/api/live/live-socket-messages.ts b/server/tests/api/live/live-socket-messages.ts index 4a6677c0a..1f3d455a8 100644 --- a/server/tests/api/live/live-socket-messages.ts +++ b/server/tests/api/live/live-socket-messages.ts @@ -7,12 +7,10 @@ import { cleanupTests, doubleFollow, flushAndRunMultipleServers, - getVideoIdFromUUID, ServerInfo, setAccessTokensToServers, setDefaultVideoChannel, stopFfmpeg, - viewVideo, wait, waitJobs, waitUntilLivePublishedOnAllServers @@ -71,7 +69,7 @@ describe('Test live', function () { await waitJobs(servers) { - const videoId = await getVideoIdFromUUID(servers[0].url, liveVideoUUID) + const videoId = await servers[0].videosCommand.getId({ uuid: liveVideoUUID }) const localSocket = servers[0].socketIOCommand.getLiveNotificationSocket() localSocket.on('state-change', data => localStateChanges.push(data.state)) @@ -79,7 +77,7 @@ describe('Test live', function () { } { - const videoId = await getVideoIdFromUUID(servers[1].url, liveVideoUUID) + const videoId = await servers[1].videosCommand.getId({ uuid: liveVideoUUID }) const remoteSocket = servers[1].socketIOCommand.getLiveNotificationSocket() remoteSocket.on('state-change', data => remoteStateChanges.push(data.state)) @@ -119,7 +117,7 @@ describe('Test live', function () { await waitJobs(servers) { - const videoId = await getVideoIdFromUUID(servers[0].url, liveVideoUUID) + const videoId = await servers[0].videosCommand.getId({ uuid: liveVideoUUID }) const localSocket = servers[0].socketIOCommand.getLiveNotificationSocket() localSocket.on('views-change', data => { localLastVideoViews = data.views }) @@ -127,7 +125,7 @@ describe('Test live', function () { } { - const videoId = await getVideoIdFromUUID(servers[1].url, liveVideoUUID) + const videoId = await servers[1].videosCommand.getId({ uuid: liveVideoUUID }) const remoteSocket = servers[1].socketIOCommand.getLiveNotificationSocket() remoteSocket.on('views-change', data => { remoteLastVideoViews = data.views }) @@ -142,8 +140,8 @@ describe('Test live', function () { expect(localLastVideoViews).to.equal(0) expect(remoteLastVideoViews).to.equal(0) - await viewVideo(servers[0].url, liveVideoUUID) - await viewVideo(servers[1].url, liveVideoUUID) + await servers[0].videosCommand.view({ id: liveVideoUUID }) + await servers[1].videosCommand.view({ id: liveVideoUUID }) await waitJobs(servers) await wait(5000) @@ -163,7 +161,7 @@ describe('Test live', function () { const liveVideoUUID = await createLiveWrapper() await waitJobs(servers) - const videoId = await getVideoIdFromUUID(servers[0].url, liveVideoUUID) + const videoId = await servers[0].videosCommand.getId({ uuid: liveVideoUUID }) const socket = servers[0].socketIOCommand.getLiveNotificationSocket() socket.on('state-change', data => stateChanges.push(data.state)) diff --git a/server/tests/api/live/live-views.ts b/server/tests/api/live/live-views.ts index 75f95b167..1951b11a5 100644 --- a/server/tests/api/live/live-views.ts +++ b/server/tests/api/live/live-views.ts @@ -3,17 +3,15 @@ import 'mocha' import * as chai from 'chai' import { FfmpegCommand } from 'fluent-ffmpeg' -import { VideoDetails, VideoPrivacy } from '@shared/models' +import { VideoPrivacy } from '@shared/models' import { cleanupTests, doubleFollow, flushAndRunMultipleServers, - getVideo, ServerInfo, setAccessTokensToServers, setDefaultVideoChannel, stopFfmpeg, - viewVideo, wait, waitJobs, waitUntilLivePublishedOnAllServers @@ -55,9 +53,7 @@ describe('Test live', function () { async function countViews (expected: number) { for (const server of servers) { - const res = await getVideo(server.url, liveVideoId) - const video: VideoDetails = res.body - + const video = await server.videosCommand.get({ id: liveVideoId }) expect(video.views).to.equal(expected) } } @@ -86,8 +82,8 @@ describe('Test live', function () { it('Should view a live twice and display 1 view', async function () { this.timeout(30000) - await viewVideo(servers[0].url, liveVideoId) - await viewVideo(servers[0].url, liveVideoId) + await servers[0].videosCommand.view({ id: liveVideoId }) + await servers[0].videosCommand.view({ id: liveVideoId }) await wait(7000) @@ -108,9 +104,9 @@ describe('Test live', function () { it('Should view a live on a remote and on local and display 2 views', async function () { this.timeout(30000) - await viewVideo(servers[0].url, liveVideoId) - await viewVideo(servers[1].url, liveVideoId) - await viewVideo(servers[1].url, liveVideoId) + await servers[0].videosCommand.view({ id: liveVideoId }) + await servers[1].videosCommand.view({ id: liveVideoId }) + await servers[1].videosCommand.view({ id: liveVideoId }) await wait(7000) await waitJobs(servers) diff --git a/server/tests/api/live/live.ts b/server/tests/api/live/live.ts index 999a49051..c88143982 100644 --- a/server/tests/api/live/live.ts +++ b/server/tests/api/live/live.ts @@ -4,8 +4,7 @@ import 'mocha' import * as chai from 'chai' import { join } from 'path' import { ffprobePromise, getVideoStreamFromFile } from '@server/helpers/ffprobe-utils' -import { LiveVideo, LiveVideoCreate, Video, VideoDetails, VideoPrivacy, VideoState, VideoStreamingPlaylistType } from '@shared/models' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '@shared/core-utils' import { checkLiveCleanup, checkLiveSegmentHash, @@ -13,14 +12,9 @@ import { cleanupTests, doubleFollow, flushAndRunMultipleServers, - getMyVideosWithFilter, - getVideo, - getVideosList, - getVideosWithFilters, killallServers, LiveCommand, makeRawRequest, - removeVideo, reRunServer, sendRTMPStream, ServerInfo, @@ -29,11 +23,11 @@ import { stopFfmpeg, testFfmpegStreamError, testImage, - uploadVideoAndGetId, wait, waitJobs, waitUntilLivePublishedOnAllServers -} from '../../../../shared/extra-utils' +} from '@shared/extra-utils' +import { LiveVideo, LiveVideoCreate, VideoDetails, VideoPrivacy, VideoState, VideoStreamingPlaylistType } from '@shared/models' const expect = chai.expect @@ -99,8 +93,7 @@ describe('Test live', function () { await waitJobs(servers) for (const server of servers) { - const resVideo = await getVideo(server.url, liveVideoUUID) - const video: VideoDetails = resVideo.body + const video = await server.videosCommand.get({ id: liveVideoUUID }) expect(video.category.id).to.equal(1) expect(video.licence.id).to.equal(2) @@ -154,9 +147,7 @@ describe('Test live', function () { await waitJobs(servers) for (const server of servers) { - const resVideo = await getVideo(server.url, videoId) - const video: VideoDetails = resVideo.body - + const video = await server.videosCommand.get({ id: videoId }) expect(video.privacy.id).to.equal(VideoPrivacy.UNLISTED) expect(video.nsfw).to.be.true @@ -167,10 +158,10 @@ describe('Test live', function () { it('Should not have the live listed since nobody streams into', async function () { for (const server of servers) { - const res = await getVideosList(server.url) + const { total, data } = await server.videosCommand.list() - expect(res.body.total).to.equal(0) - expect(res.body.data).to.have.lengthOf(0) + expect(total).to.equal(0) + expect(data).to.have.lengthOf(0) } }) @@ -204,13 +195,13 @@ describe('Test live', function () { it('Delete the live', async function () { this.timeout(10000) - await removeVideo(servers[0].url, servers[0].accessToken, liveVideoUUID) + await servers[0].videosCommand.remove({ id: liveVideoUUID }) await waitJobs(servers) }) it('Should have the live deleted', async function () { for (const server of servers) { - await getVideo(server.url, liveVideoUUID, HttpStatusCode.NOT_FOUND_404) + await server.videosCommand.get({ id: liveVideoUUID, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) await server.liveCommand.get({ videoId: liveVideoUUID, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) } }) @@ -224,7 +215,7 @@ describe('Test live', function () { before(async function () { this.timeout(120000) - vodVideoId = (await uploadVideoAndGetId({ server: servers[0], videoName: 'vod video' })).uuid + vodVideoId = (await servers[0].videosCommand.quickUpload({ name: 'vod video' })).uuid const liveOptions = { name: 'live', privacy: VideoPrivacy.PUBLIC, channelId: servers[0].videoChannel.id } const live = await commands[0].create({ fields: liveOptions }) @@ -236,19 +227,19 @@ describe('Test live', function () { }) it('Should only display lives', async function () { - const res = await getVideosWithFilters(servers[0].url, { isLive: true }) + const { data, total } = await servers[0].videosCommand.list({ isLive: true }) - expect(res.body.total).to.equal(1) - expect(res.body.data).to.have.lengthOf(1) - expect(res.body.data[0].name).to.equal('live') + expect(total).to.equal(1) + expect(data).to.have.lengthOf(1) + expect(data[0].name).to.equal('live') }) it('Should not display lives', async function () { - const res = await getVideosWithFilters(servers[0].url, { isLive: false }) + const { data, total } = await servers[0].videosCommand.list({ isLive: false }) - expect(res.body.total).to.equal(1) - expect(res.body.data).to.have.lengthOf(1) - expect(res.body.data[0].name).to.equal('vod video') + expect(total).to.equal(1) + expect(data).to.have.lengthOf(1) + expect(data[0].name).to.equal('vod video') }) it('Should display my lives', async function () { @@ -257,24 +248,22 @@ describe('Test live', function () { await stopFfmpeg(ffmpegCommand) await waitJobs(servers) - const res = await getMyVideosWithFilter(servers[0].url, servers[0].accessToken, { isLive: true }) - const videos = res.body.data as Video[] + const { data } = await servers[0].videosCommand.listMyVideos({ isLive: true }) - const result = videos.every(v => v.isLive) + const result = data.every(v => v.isLive) expect(result).to.be.true }) it('Should not display my lives', async function () { - const res = await getMyVideosWithFilter(servers[0].url, servers[0].accessToken, { isLive: false }) - const videos = res.body.data as Video[] + const { data } = await servers[0].videosCommand.listMyVideos({ isLive: false }) - const result = videos.every(v => !v.isLive) + const result = data.every(v => !v.isLive) expect(result).to.be.true }) after(async function () { - await removeVideo(servers[0].url, servers[0].accessToken, vodVideoId) - await removeVideo(servers[0].url, servers[0].accessToken, liveVideoId) + await servers[0].videosCommand.remove({ id: vodVideoId }) + await servers[0].videosCommand.remove({ id: liveVideoId }) }) }) @@ -297,9 +286,9 @@ describe('Test live', function () { const { uuid } = await commands[0].create({ fields: liveAttributes }) const live = await commands[0].get({ videoId: uuid }) - const resVideo = await getVideo(servers[0].url, uuid) + const video = await servers[0].videosCommand.get({ id: uuid }) - return Object.assign(resVideo.body as VideoDetails, live) + return Object.assign(video, live) } it('Should not allow a stream without the appropriate path', async function () { @@ -327,13 +316,12 @@ describe('Test live', function () { it('Should list this live now someone stream into it', async function () { for (const server of servers) { - const res = await getVideosList(server.url) - - expect(res.body.total).to.equal(1) - expect(res.body.data).to.have.lengthOf(1) + const { total, data } = await server.videosCommand.list() - const video: Video = res.body.data[0] + expect(total).to.equal(1) + expect(data).to.have.lengthOf(1) + const video = data[0] expect(video.name).to.equal('user live') expect(video.isLive).to.be.true } @@ -355,7 +343,7 @@ describe('Test live', function () { liveVideo = await createLiveWrapper() - await removeVideo(servers[0].url, servers[0].accessToken, liveVideo.uuid) + await servers[0].videosCommand.remove({ id: liveVideo.uuid }) const command = sendRTMPStream(rtmpUrl + '/live', liveVideo.streamKey) await testFfmpegStreamError(command, true) @@ -379,13 +367,10 @@ describe('Test live', function () { async function testVideoResolutions (liveVideoId: string, resolutions: number[]) { for (const server of servers) { - const resList = await getVideosList(server.url) - const videos: Video[] = resList.body.data - - expect(videos.find(v => v.uuid === liveVideoId)).to.exist + const { data } = await server.videosCommand.list() + expect(data.find(v => v.uuid === liveVideoId)).to.exist - const resVideo = await getVideo(server.url, liveVideoId) - const video: VideoDetails = resVideo.body + const video = await server.videosCommand.get({ id: liveVideoId }) expect(video.streamingPlaylists).to.have.lengthOf(1) @@ -505,8 +490,7 @@ describe('Test live', function () { } for (const server of servers) { - const resVideo = await getVideo(server.url, liveVideoId) - const video: VideoDetails = resVideo.body + const video = await server.videosCommand.get({ id: liveVideoId }) expect(video.state.id).to.equal(VideoState.PUBLISHED) expect(video.duration).to.be.greaterThan(1) diff --git a/server/tests/api/moderation/abuses.ts b/server/tests/api/moderation/abuses.ts index a7119263c..7574b8f4a 100644 --- a/server/tests/api/moderation/abuses.ts +++ b/server/tests/api/moderation/abuses.ts @@ -7,13 +7,8 @@ import { cleanupTests, doubleFollow, flushAndRunMultipleServers, - getVideoIdFromUUID, - getVideosList, - removeVideo, ServerInfo, setAccessTokensToServers, - uploadVideo, - uploadVideoAndGetId, waitJobs } from '@shared/extra-utils' import { AbuseMessage, AbusePredefinedReasonsString, AbuseState, AdminAbuse, UserAbuse } from '@shared/models' @@ -47,28 +42,30 @@ describe('Test abuses', function () { this.timeout(50000) // Upload some videos on each servers - const video1Attributes = { - name: 'my super name for server 1', - description: 'my super description for server 1' + { + const attributes = { + name: 'my super name for server 1', + description: 'my super description for server 1' + } + await servers[0].videosCommand.upload({ attributes }) } - await uploadVideo(servers[0].url, servers[0].accessToken, video1Attributes) - const video2Attributes = { - name: 'my super name for server 2', - description: 'my super description for server 2' + { + const attributes = { + name: 'my super name for server 2', + description: 'my super description for server 2' + } + await servers[1].videosCommand.upload({ attributes }) } - await uploadVideo(servers[1].url, servers[1].accessToken, video2Attributes) // Wait videos propagation, server 2 has transcoding enabled await waitJobs(servers) - const res = await getVideosList(servers[0].url) - const videos = res.body.data - - expect(videos.length).to.equal(2) + const { data } = await servers[0].videosCommand.list() + expect(data.length).to.equal(2) - servers[0].video = videos.find(video => video.name === 'my super name for server 1') - servers[1].video = videos.find(video => video.name === 'my super name for server 2') + servers[0].video = data.find(video => video.name === 'my super name for server 1') + servers[1].video = data.find(video => video.name === 'my super name for server 2') }) it('Should not have abuses', async function () { @@ -130,7 +127,7 @@ describe('Test abuses', function () { this.timeout(10000) const reason = 'my super bad reason 2' - const videoId = await getVideoIdFromUUID(servers[0].url, servers[1].video.uuid) + const videoId = await servers[0].videosCommand.getId({ uuid: servers[1].video.uuid }) await commands[0].report({ videoId, reason }) // We wait requests propagation @@ -203,7 +200,7 @@ describe('Test abuses', function () { this.timeout(10000) { - const videoId = await getVideoIdFromUUID(servers[1].url, servers[0].video.uuid) + const videoId = await servers[1].videosCommand.getId({ uuid: servers[0].video.uuid }) await commands[1].report({ videoId, reason: 'will mute this' }) await waitJobs(servers) @@ -255,7 +252,7 @@ describe('Test abuses', function () { it('Should keep the video abuse when deleting the video', async function () { this.timeout(10000) - await removeVideo(servers[1].url, servers[1].accessToken, abuseServer2.video.uuid) + await servers[1].videosCommand.remove({ id: abuseServer2.video.uuid }) await waitJobs(servers) @@ -279,12 +276,12 @@ describe('Test abuses', function () { const userAccessToken = await servers[0].loginCommand.getAccessToken(user) // upload a third video via this user - const video3Attributes = { + const attributes = { name: 'my second super name for server 1', description: 'my second super description for server 1' } - const resUpload = await uploadVideo(servers[0].url, userAccessToken, video3Attributes) - const video3Id = resUpload.body.video.id + const { id } = await servers[0].videosCommand.upload({ token: userAccessToken, attributes }) + const video3Id = id // resume with the test const reason3 = 'my super bad reason 3' @@ -394,7 +391,7 @@ describe('Test abuses', function () { async function getComment (server: ServerInfo, videoIdArg: number | string) { const videoId = typeof videoIdArg === 'string' - ? await getVideoIdFromUUID(server.url, videoIdArg) + ? await server.videosCommand.getId({ uuid: videoIdArg }) : videoIdArg const { data } = await server.commentsCommand.listThreads({ videoId }) @@ -405,8 +402,8 @@ describe('Test abuses', function () { before(async function () { this.timeout(50000) - servers[0].video = await uploadVideoAndGetId({ server: servers[0], videoName: 'server 1' }) - servers[1].video = await uploadVideoAndGetId({ server: servers[1], videoName: 'server 2' }) + servers[0].video = await await servers[0].videosCommand.quickUpload({ name: 'server 1' }) + servers[1].video = await await servers[1].videosCommand.quickUpload({ name: 'server 2' }) await servers[0].commentsCommand.createThread({ videoId: servers[0].video.id, text: 'comment server 1' }) await servers[1].commentsCommand.createThread({ videoId: servers[1].video.id, text: 'comment server 2' }) @@ -604,7 +601,7 @@ describe('Test abuses', function () { await servers[0].usersCommand.create({ username: 'user_1', password: 'donald' }) const token = await servers[1].usersCommand.generateUserAndToken('user_2') - await uploadVideo(servers[1].url, token, { name: 'super video' }) + await servers[1].videosCommand.upload({ token, attributes: { name: 'super video' } }) await waitJobs(servers) }) @@ -766,7 +763,7 @@ describe('Test abuses', function () { await commands[0].report({ token: userAccessToken, videoId: servers[0].video.id, reason: 'user reason 1' }) - const videoId = await getVideoIdFromUUID(servers[0].url, servers[1].video.uuid) + const videoId = await servers[0].videosCommand.getId({ uuid: servers[1].video.uuid }) await commands[0].report({ token: userAccessToken, videoId, reason: 'user reason 2' }) }) diff --git a/server/tests/api/moderation/blocklist-notification.ts b/server/tests/api/moderation/blocklist-notification.ts index b44bcb012..92a0ec681 100644 --- a/server/tests/api/moderation/blocklist-notification.ts +++ b/server/tests/api/moderation/blocklist-notification.ts @@ -2,15 +2,7 @@ import 'mocha' import * as chai from 'chai' -import { - cleanupTests, - doubleFollow, - flushAndRunMultipleServers, - ServerInfo, - setAccessTokensToServers, - uploadVideo, - waitJobs -} from '@shared/extra-utils' +import { cleanupTests, doubleFollow, flushAndRunMultipleServers, ServerInfo, setAccessTokensToServers, waitJobs } from '@shared/extra-utils' import { UserNotificationType } from '@shared/models' const expect = chai.expect @@ -44,8 +36,8 @@ describe('Test blocklist', function () { await servers[0].notificationsCommand.markAsReadAll({ token: userToken2 }) { - const res = await uploadVideo(servers[0].url, userToken1, { name: 'video' }) - videoUUID = res.body.video.uuid + const { uuid } = await servers[0].videosCommand.upload({ token: userToken1, attributes: { name: 'video' } }) + videoUUID = uuid await waitJobs(servers) } @@ -83,7 +75,7 @@ describe('Test blocklist', function () { }) userToken1 = await servers[0].loginCommand.getAccessToken(user) - await uploadVideo(servers[0].url, userToken1, { name: 'video user 1' }) + await servers[0].videosCommand.upload({ token: userToken1, attributes: { name: 'video user 1' } }) } { diff --git a/server/tests/api/moderation/blocklist.ts b/server/tests/api/moderation/blocklist.ts index c253b5c11..3c3b2d6fd 100644 --- a/server/tests/api/moderation/blocklist.ts +++ b/server/tests/api/moderation/blocklist.ts @@ -8,28 +8,23 @@ import { CommentsCommand, doubleFollow, flushAndRunMultipleServers, - getVideosList, - getVideosListWithToken, ServerInfo, setAccessTokensToServers, - uploadVideo, waitJobs } from '@shared/extra-utils' -import { UserNotificationType, Video } from '@shared/models' +import { UserNotificationType } from '@shared/models' const expect = chai.expect async function checkAllVideos (server: ServerInfo, token: string) { { - const res = await getVideosListWithToken(server.url, token) - - expect(res.body.data).to.have.lengthOf(5) + const { data } = await server.videosCommand.listWithToken({ token }) + expect(data).to.have.lengthOf(5) } { - const res = await getVideosList(server.url) - - expect(res.body.data).to.have.lengthOf(5) + const { data } = await server.videosCommand.list() + expect(data).to.have.lengthOf(5) } } @@ -93,7 +88,7 @@ describe('Test blocklist', function () { await servers[0].usersCommand.create({ username: user.username, password: user.password }) userToken1 = await servers[0].loginCommand.getAccessToken(user) - await uploadVideo(servers[0].url, userToken1, { name: 'video user 1' }) + await servers[0].videosCommand.upload({ token: userToken1, attributes: { name: 'video user 1' } }) } { @@ -108,22 +103,22 @@ describe('Test blocklist', function () { await servers[1].usersCommand.create({ username: user.username, password: user.password }) userToken2 = await servers[1].loginCommand.getAccessToken(user) - await uploadVideo(servers[1].url, userToken2, { name: 'video user 2' }) + await servers[1].videosCommand.upload({ token: userToken2, attributes: { name: 'video user 2' } }) } { - const res = await uploadVideo(servers[0].url, servers[0].accessToken, { name: 'video server 1' }) - videoUUID1 = res.body.video.uuid + const { uuid } = await servers[0].videosCommand.upload({ attributes: { name: 'video server 1' } }) + videoUUID1 = uuid } { - const res = await uploadVideo(servers[1].url, servers[1].accessToken, { name: 'video server 2' }) - videoUUID2 = res.body.video.uuid + const { uuid } = await servers[1].videosCommand.upload({ attributes: { name: 'video server 2' } }) + videoUUID2 = uuid } { - const res = await uploadVideo(servers[0].url, servers[0].accessToken, { name: 'video 2 server 1' }) - videoUUID3 = res.body.video.uuid + const { uuid } = await servers[0].videosCommand.upload({ attributes: { name: 'video 2 server 1' } }) + videoUUID3 = uuid } await doubleFollow(servers[0], servers[1]) @@ -164,12 +159,11 @@ describe('Test blocklist', function () { }) it('Should hide its videos', async function () { - const res = await getVideosListWithToken(servers[0].url, servers[0].accessToken) + const { data } = await servers[0].videosCommand.listWithToken() - const videos: Video[] = res.body.data - expect(videos).to.have.lengthOf(4) + expect(data).to.have.lengthOf(4) - const v = videos.find(v => v.name === 'video user 2') + const v = data.find(v => v.name === 'video user 2') expect(v).to.be.undefined }) @@ -178,12 +172,11 @@ describe('Test blocklist', function () { }) it('Should hide its videos', async function () { - const res = await getVideosListWithToken(servers[0].url, servers[0].accessToken) + const { data } = await servers[0].videosCommand.listWithToken() - const videos: Video[] = res.body.data - expect(videos).to.have.lengthOf(3) + expect(data).to.have.lengthOf(3) - const v = videos.find(v => v.name === 'video user 1') + const v = data.find(v => v.name === 'video user 1') expect(v).to.be.undefined }) @@ -313,12 +306,10 @@ describe('Test blocklist', function () { }) it('Should display its videos', async function () { - const res = await getVideosListWithToken(servers[0].url, servers[0].accessToken) + const { data } = await servers[0].videosCommand.listWithToken() + expect(data).to.have.lengthOf(4) - const videos: Video[] = res.body.data - expect(videos).to.have.lengthOf(4) - - const v = videos.find(v => v.name === 'video user 2') + const v = data.find(v => v.name === 'video user 2') expect(v).not.to.be.undefined }) @@ -387,13 +378,12 @@ describe('Test blocklist', function () { }) it('Should hide its videos', async function () { - const res = await getVideosListWithToken(servers[0].url, servers[0].accessToken) + const { data } = await servers[0].videosCommand.listWithToken() - const videos: Video[] = res.body.data - expect(videos).to.have.lengthOf(3) + expect(data).to.have.lengthOf(3) - const v1 = videos.find(v => v.name === 'video user 2') - const v2 = videos.find(v => v.name === 'video server 2') + const v1 = data.find(v => v.name === 'video user 2') + const v2 = data.find(v => v.name === 'video server 2') expect(v1).to.be.undefined expect(v2).to.be.undefined @@ -498,12 +488,11 @@ describe('Test blocklist', function () { it('Should hide its videos', async function () { for (const token of [ userModeratorToken, servers[0].accessToken ]) { - const res = await getVideosListWithToken(servers[0].url, token) + const { data } = await servers[0].videosCommand.listWithToken({ token }) - const videos: Video[] = res.body.data - expect(videos).to.have.lengthOf(4) + expect(data).to.have.lengthOf(4) - const v = videos.find(v => v.name === 'video user 2') + const v = data.find(v => v.name === 'video user 2') expect(v).to.be.undefined } }) @@ -514,12 +503,11 @@ describe('Test blocklist', function () { it('Should hide its videos', async function () { for (const token of [ userModeratorToken, servers[0].accessToken ]) { - const res = await getVideosListWithToken(servers[0].url, token) + const { data } = await servers[0].videosCommand.listWithToken({ token }) - const videos: Video[] = res.body.data - expect(videos).to.have.lengthOf(3) + expect(data).to.have.lengthOf(3) - const v = videos.find(v => v.name === 'video user 1') + const v = data.find(v => v.name === 'video user 1') expect(v).to.be.undefined } }) @@ -593,12 +581,10 @@ describe('Test blocklist', function () { it('Should display its videos', async function () { for (const token of [ userModeratorToken, servers[0].accessToken ]) { - const res = await getVideosListWithToken(servers[0].url, token) - - const videos: Video[] = res.body.data - expect(videos).to.have.lengthOf(4) + const { data } = await servers[0].videosCommand.listWithToken({ token }) + expect(data).to.have.lengthOf(4) - const v = videos.find(v => v.name === 'video user 2') + const v = data.find(v => v.name === 'video user 2') expect(v).not.to.be.undefined } }) @@ -652,15 +638,17 @@ describe('Test blocklist', function () { it('Should hide its videos', async function () { for (const token of [ userModeratorToken, servers[0].accessToken ]) { - const res1 = await getVideosList(servers[0].url) - const res2 = await getVideosListWithToken(servers[0].url, token) + const requests = [ + servers[0].videosCommand.list(), + servers[0].videosCommand.listWithToken({ token }) + ] - for (const res of [ res1, res2 ]) { - const videos: Video[] = res.body.data - expect(videos).to.have.lengthOf(3) + for (const req of requests) { + const { data } = await req + expect(data).to.have.lengthOf(3) - const v1 = videos.find(v => v.name === 'video user 2') - const v2 = videos.find(v => v.name === 'video server 2') + const v1 = data.find(v => v.name === 'video user 2') + const v2 = data.find(v => v.name === 'video server 2') expect(v1).to.be.undefined expect(v2).to.be.undefined diff --git a/server/tests/api/moderation/video-blacklist.ts b/server/tests/api/moderation/video-blacklist.ts index ef25cfb8e..2f2e678e7 100644 --- a/server/tests/api/moderation/video-blacklist.ts +++ b/server/tests/api/moderation/video-blacklist.ts @@ -8,15 +8,11 @@ import { cleanupTests, doubleFollow, flushAndRunMultipleServers, - getMyVideos, - getVideosList, ImportsCommand, killallServers, reRunServer, ServerInfo, setAccessTokensToServers, - updateVideo, - uploadVideo, waitJobs } from '@shared/extra-utils' import { UserAdminFlag, UserRole, VideoBlacklist, VideoBlacklistType } from '@shared/models' @@ -29,10 +25,9 @@ describe('Test video blacklist', function () { let command: BlacklistCommand async function blacklistVideosOnServer (server: ServerInfo) { - const res = await getVideosList(server.url) + const { data } = await server.videosCommand.list() - const videos = res.body.data - for (const video of videos) { + for (const video of data) { await server.blacklistCommand.add({ videoId: video.id, reason: 'super reason' }) } } @@ -50,8 +45,8 @@ describe('Test video blacklist', function () { await doubleFollow(servers[0], servers[1]) // Upload 2 videos on server 2 - await uploadVideo(servers[1].url, servers[1].accessToken, { name: 'My 1st video', description: 'A video on server 2' }) - await uploadVideo(servers[1].url, servers[1].accessToken, { name: 'My 2nd video', description: 'A video on server 2' }) + await servers[1].videosCommand.upload({ attributes: { name: 'My 1st video', description: 'A video on server 2' } }) + await servers[1].videosCommand.upload({ attributes: { name: 'My 2nd video', description: 'A video on server 2' } }) // Wait videos propagation, server 2 has transcoding enabled await waitJobs(servers) @@ -66,11 +61,11 @@ describe('Test video blacklist', function () { it('Should not have the video blacklisted in videos list/search on server 1', async function () { { - const res = await getVideosList(servers[0].url) + const { total, data } = await servers[0].videosCommand.list() - expect(res.body.total).to.equal(0) - expect(res.body.data).to.be.an('array') - expect(res.body.data.length).to.equal(0) + expect(total).to.equal(0) + expect(data).to.be.an('array') + expect(data.length).to.equal(0) } { @@ -84,11 +79,11 @@ describe('Test video blacklist', function () { it('Should have the blacklisted video in videos list/search on server 2', async function () { { - const res = await getVideosList(servers[1].url) + const { total, data } = await servers[1].videosCommand.list() - expect(res.body.total).to.equal(2) - expect(res.body.data).to.be.an('array') - expect(res.body.data.length).to.equal(2) + expect(total).to.equal(2) + expect(data).to.be.an('array') + expect(data.length).to.equal(2) } { @@ -186,12 +181,12 @@ describe('Test video blacklist', function () { it('Should display blacklisted videos', async function () { await blacklistVideosOnServer(servers[1]) - const res = await getMyVideos(servers[1].url, servers[1].accessToken, 0, 5) + const { total, data } = await servers[1].videosCommand.listMyVideos() - expect(res.body.total).to.equal(2) - expect(res.body.data).to.have.lengthOf(2) + expect(total).to.equal(2) + expect(data).to.have.lengthOf(2) - for (const video of res.body.data) { + for (const video of data) { expect(video.blacklisted).to.be.true expect(video.blacklistedReason).to.equal('super reason') } @@ -203,10 +198,10 @@ describe('Test video blacklist', function () { let blacklist = [] it('Should not have any video in videos list on server 1', async function () { - const res = await getVideosList(servers[0].url) - expect(res.body.total).to.equal(0) - expect(res.body.data).to.be.an('array') - expect(res.body.data.length).to.equal(0) + const { total, data } = await servers[0].videosCommand.list() + expect(total).to.equal(0) + expect(data).to.be.an('array') + expect(data.length).to.equal(0) }) it('Should remove a video from the blacklist on server 1', async function () { @@ -220,15 +215,14 @@ describe('Test video blacklist', function () { }) it('Should have the ex-blacklisted video in videos list on server 1', async function () { - const res = await getVideosList(servers[0].url) - expect(res.body.total).to.equal(1) + const { total, data } = await servers[0].videosCommand.list() + expect(total).to.equal(1) - const videos = res.body.data - expect(videos).to.be.an('array') - expect(videos.length).to.equal(1) + expect(data).to.be.an('array') + expect(data.length).to.equal(1) - expect(videos[0].name).to.equal(videoToRemove.video.name) - expect(videos[0].id).to.equal(videoToRemove.video.id) + expect(data[0].name).to.equal(videoToRemove.video.name) + expect(data[0].id).to.equal(videoToRemove.video.id) }) it('Should not have the ex-blacklisted video in videos blacklist list on server 1', async function () { @@ -250,12 +244,12 @@ describe('Test video blacklist', function () { this.timeout(10000) { - const res = await uploadVideo(servers[0].url, servers[0].accessToken, { name: 'Video 3' }) - video3UUID = res.body.video.uuid + const { uuid } = await servers[0].videosCommand.upload({ attributes: { name: 'Video 3' } }) + video3UUID = uuid } { - const res = await uploadVideo(servers[0].url, servers[0].accessToken, { name: 'Video 4' }) - video4UUID = res.body.video.uuid + const { uuid } = await servers[0].videosCommand.upload({ attributes: { name: 'Video 4' } }) + video4UUID = uuid } await waitJobs(servers) @@ -269,13 +263,13 @@ describe('Test video blacklist', function () { await waitJobs(servers) { - const res = await getVideosList(servers[0].url) - expect(res.body.data.find(v => v.uuid === video3UUID)).to.be.undefined + const { data } = await servers[0].videosCommand.list() + expect(data.find(v => v.uuid === video3UUID)).to.be.undefined } { - const res = await getVideosList(servers[1].url) - expect(res.body.data.find(v => v.uuid === video3UUID)).to.not.be.undefined + const { data } = await servers[1].videosCommand.list() + expect(data.find(v => v.uuid === video3UUID)).to.not.be.undefined } }) @@ -287,21 +281,21 @@ describe('Test video blacklist', function () { await waitJobs(servers) for (const server of servers) { - const res = await getVideosList(server.url) - expect(res.body.data.find(v => v.uuid === video4UUID)).to.be.undefined + const { data } = await server.videosCommand.list() + expect(data.find(v => v.uuid === video4UUID)).to.be.undefined } }) it('Should have the video unfederated even after an Update AP message', async function () { this.timeout(10000) - await updateVideo(servers[0].url, servers[0].accessToken, video4UUID, { description: 'super description' }) + await servers[0].videosCommand.update({ id: video4UUID, attributes: { description: 'super description' } }) await waitJobs(servers) for (const server of servers) { - const res = await getVideosList(server.url) - expect(res.body.data.find(v => v.uuid === video4UUID)).to.be.undefined + const { data } = await server.videosCommand.list() + expect(data.find(v => v.uuid === video4UUID)).to.be.undefined } }) @@ -324,8 +318,8 @@ describe('Test video blacklist', function () { await waitJobs(servers) for (const server of servers) { - const res = await getVideosList(server.url) - expect(res.body.data.find(v => v.uuid === video4UUID)).to.not.be.undefined + const { data } = await server.videosCommand.list() + expect(data.find(v => v.uuid === video4UUID)).to.not.be.undefined } }) @@ -383,7 +377,7 @@ describe('Test video blacklist', function () { }) it('Should auto blacklist a video on upload', async function () { - await uploadVideo(servers[0].url, userWithoutFlag, { name: 'blacklisted' }) + await servers[0].videosCommand.upload({ token: userWithoutFlag, attributes: { name: 'blacklisted' } }) const body = await command.list({ type: VideoBlacklistType.AUTO_BEFORE_PUBLISHED }) expect(body.total).to.equal(1) @@ -419,7 +413,7 @@ describe('Test video blacklist', function () { }) it('Should not auto blacklist a video on upload if the user has the bypass blacklist flag', async function () { - await uploadVideo(servers[0].url, userWithFlag, { name: 'not blacklisted' }) + await servers[0].videosCommand.upload({ token: userWithFlag, attributes: { name: 'not blacklisted' } }) const body = await command.list({ type: VideoBlacklistType.AUTO_BEFORE_PUBLISHED }) expect(body.total).to.equal(3) diff --git a/server/tests/api/notifications/comments-notifications.ts b/server/tests/api/notifications/comments-notifications.ts index 62569f810..a74b38e8a 100644 --- a/server/tests/api/notifications/comments-notifications.ts +++ b/server/tests/api/notifications/comments-notifications.ts @@ -10,7 +10,6 @@ import { MockSmtpServer, prepareNotificationsTest, ServerInfo, - uploadVideo, waitJobs } from '@shared/extra-utils' import { UserNotification } from '@shared/models' @@ -53,8 +52,7 @@ describe('Test comments notifications', function () { it('Should not send a new comment notification after a comment on another video', async function () { this.timeout(20000) - const resVideo = await uploadVideo(servers[0].url, servers[0].accessToken, { name: 'super video' }) - const uuid = resVideo.body.video.uuid + const { uuid } = await servers[0].videosCommand.upload({ attributes: { name: 'super video' } }) const created = await servers[0].commentsCommand.createThread({ videoId: uuid, text: 'comment' }) const commentId = created.id @@ -66,8 +64,7 @@ describe('Test comments notifications', function () { it('Should not send a new comment notification if I comment my own video', async function () { this.timeout(20000) - const resVideo = await uploadVideo(servers[0].url, userToken, { name: 'super video' }) - const uuid = resVideo.body.video.uuid + const { uuid } = await servers[0].videosCommand.upload({ token: userToken, attributes: { name: 'super video' } }) const created = await servers[0].commentsCommand.createThread({ token: userToken, videoId: uuid, text: 'comment' }) const commentId = created.id @@ -81,8 +78,7 @@ describe('Test comments notifications', function () { await servers[0].blocklistCommand.addToMyBlocklist({ token: userToken, account: 'root' }) - const resVideo = await uploadVideo(servers[0].url, userToken, { name: 'super video' }) - const uuid = resVideo.body.video.uuid + const { uuid } = await servers[0].videosCommand.upload({ token: userToken, attributes: { name: 'super video' } }) const created = await servers[0].commentsCommand.createThread({ videoId: uuid, text: 'comment' }) const commentId = created.id @@ -96,8 +92,7 @@ describe('Test comments notifications', function () { it('Should send a new comment notification after a local comment on my video', async function () { this.timeout(20000) - const resVideo = await uploadVideo(servers[0].url, userToken, { name: 'super video' }) - const uuid = resVideo.body.video.uuid + const { uuid } = await servers[0].videosCommand.upload({ token: userToken, attributes: { name: 'super video' } }) const created = await servers[0].commentsCommand.createThread({ videoId: uuid, text: 'comment' }) const commentId = created.id @@ -109,8 +104,7 @@ describe('Test comments notifications', function () { it('Should send a new comment notification after a remote comment on my video', async function () { this.timeout(20000) - const resVideo = await uploadVideo(servers[0].url, userToken, { name: 'super video' }) - const uuid = resVideo.body.video.uuid + const { uuid } = await servers[0].videosCommand.upload({ token: userToken, attributes: { name: 'super video' } }) await waitJobs(servers) @@ -128,8 +122,7 @@ describe('Test comments notifications', function () { it('Should send a new comment notification after a local reply on my video', async function () { this.timeout(20000) - const resVideo = await uploadVideo(servers[0].url, userToken, { name: 'super video' }) - const uuid = resVideo.body.video.uuid + const { uuid } = await servers[0].videosCommand.upload({ token: userToken, attributes: { name: 'super video' } }) const { id: threadId } = await servers[0].commentsCommand.createThread({ videoId: uuid, text: 'comment' }) @@ -142,8 +135,7 @@ describe('Test comments notifications', function () { it('Should send a new comment notification after a remote reply on my video', async function () { this.timeout(20000) - const resVideo = await uploadVideo(servers[0].url, userToken, { name: 'super video' }) - const uuid = resVideo.body.video.uuid + const { uuid } = await servers[0].videosCommand.upload({ token: userToken, attributes: { name: 'super video' } }) await waitJobs(servers) { @@ -169,8 +161,7 @@ describe('Test comments notifications', function () { it('Should convert markdown in comment to html', async function () { this.timeout(20000) - const resVideo = await uploadVideo(servers[0].url, userToken, { name: 'cool video' }) - const uuid = resVideo.body.video.uuid + const { uuid } = await servers[0].videosCommand.upload({ token: userToken, attributes: { name: 'cool video' } }) await servers[0].commentsCommand.createThread({ videoId: uuid, text: commentText }) @@ -199,8 +190,7 @@ describe('Test comments notifications', function () { it('Should not send a new mention comment notification if I mention the video owner', async function () { this.timeout(10000) - const resVideo = await uploadVideo(servers[0].url, userToken, { name: 'super video' }) - const uuid = resVideo.body.video.uuid + const { uuid } = await servers[0].videosCommand.upload({ token: userToken, attributes: { name: 'super video' } }) const { id: commentId } = await servers[0].commentsCommand.createThread({ videoId: uuid, text: '@user_1 hello' }) @@ -211,8 +201,7 @@ describe('Test comments notifications', function () { it('Should not send a new mention comment notification if I mention myself', async function () { this.timeout(10000) - const resVideo = await uploadVideo(servers[0].url, servers[0].accessToken, { name: 'super video' }) - const uuid = resVideo.body.video.uuid + const { uuid } = await servers[0].videosCommand.upload({ attributes: { name: 'super video' } }) const { id: commentId } = await servers[0].commentsCommand.createThread({ token: userToken, videoId: uuid, text: '@user_1 hello' }) @@ -225,8 +214,7 @@ describe('Test comments notifications', function () { await servers[0].blocklistCommand.addToMyBlocklist({ token: userToken, account: 'root' }) - const resVideo = await uploadVideo(servers[0].url, servers[0].accessToken, { name: 'super video' }) - const uuid = resVideo.body.video.uuid + const { uuid } = await servers[0].videosCommand.upload({ attributes: { name: 'super video' } }) const { id: commentId } = await servers[0].commentsCommand.createThread({ videoId: uuid, text: '@user_1 hello' }) @@ -239,8 +227,7 @@ describe('Test comments notifications', function () { it('Should not send a new mention notification if the remote account mention a local account', async function () { this.timeout(20000) - const resVideo = await uploadVideo(servers[0].url, servers[0].accessToken, { name: 'super video' }) - const uuid = resVideo.body.video.uuid + const { uuid } = await servers[0].videosCommand.upload({ attributes: { name: 'super video' } }) await waitJobs(servers) const { id: threadId } = await servers[1].commentsCommand.createThread({ videoId: uuid, text: '@user_1 hello' }) @@ -252,8 +239,7 @@ describe('Test comments notifications', function () { it('Should send a new mention notification after local comments', async function () { this.timeout(10000) - const resVideo = await uploadVideo(servers[0].url, servers[0].accessToken, { name: 'super video' }) - const uuid = resVideo.body.video.uuid + const { uuid } = await servers[0].videosCommand.upload({ attributes: { name: 'super video' } }) const { id: threadId } = await servers[0].commentsCommand.createThread({ videoId: uuid, text: '@user_1 hellotext: 1' }) @@ -269,8 +255,7 @@ describe('Test comments notifications', function () { it('Should send a new mention notification after remote comments', async function () { this.timeout(20000) - const resVideo = await uploadVideo(servers[0].url, servers[0].accessToken, { name: 'super video' }) - const uuid = resVideo.body.video.uuid + const { uuid } = await servers[0].videosCommand.upload({ attributes: { name: 'super video' } }) await waitJobs(servers) @@ -301,8 +286,7 @@ describe('Test comments notifications', function () { it('Should convert markdown in comment to html', async function () { this.timeout(10000) - const resVideo = await uploadVideo(servers[0].url, servers[0].accessToken, { name: 'super video' }) - const uuid = resVideo.body.video.uuid + const { uuid } = await servers[0].videosCommand.upload({ attributes: { name: 'super video' } }) const { id: threadId } = await servers[0].commentsCommand.createThread({ videoId: uuid, text: '@user_1 hello 1' }) diff --git a/server/tests/api/notifications/moderation-notifications.ts b/server/tests/api/notifications/moderation-notifications.ts index 0269124c5..91a2b4fa5 100644 --- a/server/tests/api/notifications/moderation-notifications.ts +++ b/server/tests/api/notifications/moderation-notifications.ts @@ -17,12 +17,10 @@ import { checkVideoAutoBlacklistForModerators, checkVideoIsPublished, cleanupTests, - getVideoIdFromUUID, MockInstancesIndex, MockSmtpServer, prepareNotificationsTest, ServerInfo, - uploadVideo, wait, waitJobs } from '@shared/extra-utils' @@ -64,8 +62,7 @@ describe('Test moderation notifications', function () { this.timeout(20000) const name = 'video for abuse ' + buildUUID() - const resVideo = await uploadVideo(servers[0].url, userAccessToken, { name }) - const video = resVideo.body.video + const video = await servers[0].videosCommand.upload({ token: userAccessToken, attributes: { name } }) await servers[0].abusesCommand.report({ videoId: video.id, reason: 'super reason' }) @@ -77,12 +74,11 @@ describe('Test moderation notifications', function () { this.timeout(20000) const name = 'video for abuse ' + buildUUID() - const resVideo = await uploadVideo(servers[0].url, userAccessToken, { name }) - const video = resVideo.body.video + const video = await servers[0].videosCommand.upload({ token: userAccessToken, attributes: { name } }) await waitJobs(servers) - const videoId = await getVideoIdFromUUID(servers[1].url, video.uuid) + const videoId = await servers[1].videosCommand.getId({ uuid: video.uuid }) await servers[1].abusesCommand.report({ videoId, reason: 'super reason' }) await waitJobs(servers) @@ -93,8 +89,7 @@ describe('Test moderation notifications', function () { this.timeout(20000) const name = 'video for abuse ' + buildUUID() - const resVideo = await uploadVideo(servers[0].url, userAccessToken, { name }) - const video = resVideo.body.video + const video = await servers[0].videosCommand.upload({ token: userAccessToken, attributes: { name } }) const comment = await servers[0].commentsCommand.createThread({ token: userAccessToken, videoId: video.id, @@ -113,8 +108,7 @@ describe('Test moderation notifications', function () { this.timeout(20000) const name = 'video for abuse ' + buildUUID() - const resVideo = await uploadVideo(servers[0].url, userAccessToken, { name }) - const video = resVideo.body.video + const video = await servers[0].videosCommand.upload({ token: userAccessToken, attributes: { name } }) await servers[0].commentsCommand.createThread({ token: userAccessToken, @@ -150,7 +144,7 @@ describe('Test moderation notifications', function () { const username = 'user' + new Date().getTime() const tmpToken = await servers[0].usersCommand.generateUserAndToken(username) - await uploadVideo(servers[0].url, tmpToken, { name: 'super video' }) + await servers[0].videosCommand.upload({ token: tmpToken, attributes: { name: 'super video' } }) await waitJobs(servers) @@ -175,8 +169,7 @@ describe('Test moderation notifications', function () { } const name = 'abuse ' + buildUUID() - const resVideo = await uploadVideo(servers[0].url, userAccessToken, { name }) - const video = resVideo.body.video + const video = await servers[0].videosCommand.upload({ token: userAccessToken, attributes: { name } }) const body = await servers[0].abusesCommand.report({ token: userAccessToken, videoId: video.id, reason: 'super reason' }) abuseId = body.abuse.id @@ -223,8 +216,7 @@ describe('Test moderation notifications', function () { } const name = 'abuse ' + buildUUID() - const resVideo = await uploadVideo(servers[0].url, userAccessToken, { name }) - const video = resVideo.body.video + const video = await servers[0].videosCommand.upload({ token: userAccessToken, attributes: { name } }) { const body = await servers[0].abusesCommand.report({ token: userAccessToken, videoId: video.id, reason: 'super reason' }) @@ -294,8 +286,7 @@ describe('Test moderation notifications', function () { this.timeout(10000) const name = 'video for abuse ' + buildUUID() - const resVideo = await uploadVideo(servers[0].url, userAccessToken, { name }) - const uuid = resVideo.body.video.uuid + const { uuid } = await servers[0].videosCommand.upload({ token: userAccessToken, attributes: { name } }) await servers[0].blacklistCommand.add({ videoId: uuid }) @@ -307,8 +298,7 @@ describe('Test moderation notifications', function () { this.timeout(10000) const name = 'video for abuse ' + buildUUID() - const resVideo = await uploadVideo(servers[0].url, userAccessToken, { name }) - const uuid = resVideo.body.video.uuid + const { uuid } = await servers[0].videosCommand.upload({ token: userAccessToken, attributes: { name } }) await servers[0].blacklistCommand.add({ videoId: uuid }) @@ -497,8 +487,8 @@ describe('Test moderation notifications', function () { this.timeout(40000) videoName = 'video with auto-blacklist ' + buildUUID() - const resVideo = await uploadVideo(servers[0].url, userAccessToken, { name: videoName }) - videoUUID = resVideo.body.video.uuid + const { uuid } = await servers[0].videosCommand.upload({ token: userAccessToken, attributes: { name: videoName } }) + videoUUID = uuid await waitJobs(servers) await checkVideoAutoBlacklistForModerators(adminBaseParamsServer1, videoUUID, videoName, 'presence') @@ -544,17 +534,16 @@ describe('Test moderation notifications', function () { const name = 'video with auto-blacklist and future schedule ' + buildUUID() - const data = { + const attributes = { name, privacy: VideoPrivacy.PRIVATE, scheduleUpdate: { updateAt: updateAt.toISOString(), - privacy: VideoPrivacy.PUBLIC + privacy: VideoPrivacy.PUBLIC as VideoPrivacy.PUBLIC } } - const resVideo = await uploadVideo(servers[0].url, userAccessToken, data) - const uuid = resVideo.body.video.uuid + const { uuid } = await servers[0].videosCommand.upload({ token: userAccessToken, attributes }) await servers[0].blacklistCommand.remove({ videoId: uuid }) @@ -577,17 +566,16 @@ describe('Test moderation notifications', function () { const name = 'video with schedule done and still auto-blacklisted ' + buildUUID() - const data = { + const attributes = { name, privacy: VideoPrivacy.PRIVATE, scheduleUpdate: { updateAt: updateAt.toISOString(), - privacy: VideoPrivacy.PUBLIC + privacy: VideoPrivacy.PUBLIC as VideoPrivacy.PUBLIC } } - const resVideo = await uploadVideo(servers[0].url, userAccessToken, data) - const uuid = resVideo.body.video.uuid + const { uuid } = await servers[0].videosCommand.upload({ token: userAccessToken, attributes }) await wait(6000) await checkVideoIsPublished(userBaseParams, name, uuid, 'absence') @@ -601,8 +589,7 @@ describe('Test moderation notifications', function () { const name = 'video without auto-blacklist ' + buildUUID() // admin with blacklist right will not be auto-blacklisted - const resVideo = await uploadVideo(servers[0].url, servers[0].accessToken, { name }) - const uuid = resVideo.body.video.uuid + const { uuid } = await servers[0].videosCommand.upload({ attributes: { name } }) await waitJobs(servers) await checkVideoAutoBlacklistForModerators(adminBaseParamsServer1, uuid, name, 'absence') diff --git a/server/tests/api/notifications/notifications-api.ts b/server/tests/api/notifications/notifications-api.ts index f33d8e64d..41e1b8015 100644 --- a/server/tests/api/notifications/notifications-api.ts +++ b/server/tests/api/notifications/notifications-api.ts @@ -10,7 +10,6 @@ import { MockSmtpServer, prepareNotificationsTest, ServerInfo, - uploadRandomVideo, waitJobs } from '@shared/extra-utils' import { UserNotification, UserNotificationSettingValue } from '@shared/models' @@ -35,7 +34,7 @@ describe('Test notifications API', function () { await server.subscriptionsCommand.add({ token: userToken, targetUri: 'root_channel@localhost:' + server.port }) for (let i = 0; i < 10; i++) { - await uploadRandomVideo(server, false) + await server.videosCommand.randomUpload({ wait: false }) } await waitJobs([ server ]) @@ -112,7 +111,7 @@ describe('Test notifications API', function () { expect(info.notificationSettings.newVideoFromSubscription).to.equal(UserNotificationSettingValue.NONE) } - const { name, uuid } = await uploadRandomVideo(server) + const { name, uuid } = await server.videosCommand.randomUpload() const check = { web: true, mail: true } await checkNewVideoFromSubscription({ ...baseParams, check }, name, uuid, 'absence') @@ -131,7 +130,7 @@ describe('Test notifications API', function () { expect(info.notificationSettings.newVideoFromSubscription).to.equal(UserNotificationSettingValue.WEB) } - const { name, uuid } = await uploadRandomVideo(server) + const { name, uuid } = await server.videosCommand.randomUpload() { const check = { mail: true, web: false } @@ -157,7 +156,7 @@ describe('Test notifications API', function () { expect(info.notificationSettings.newVideoFromSubscription).to.equal(UserNotificationSettingValue.EMAIL) } - const { name, uuid } = await uploadRandomVideo(server) + const { name, uuid } = await server.videosCommand.randomUpload() { const check = { mail: false, web: true } @@ -188,7 +187,7 @@ describe('Test notifications API', function () { ) } - const { name, uuid } = await uploadRandomVideo(server) + const { name, uuid } = await server.videosCommand.randomUpload() await checkNewVideoFromSubscription(baseParams, name, uuid, 'presence') }) diff --git a/server/tests/api/notifications/user-notifications.ts b/server/tests/api/notifications/user-notifications.ts index 465349fb9..4db8c1576 100644 --- a/server/tests/api/notifications/user-notifications.ts +++ b/server/tests/api/notifications/user-notifications.ts @@ -14,7 +14,6 @@ import { MockSmtpServer, prepareNotificationsTest, ServerInfo, - updateVideo, uploadRandomVideoOnServers, wait, waitJobs @@ -99,7 +98,7 @@ describe('Test user notifications', function () { privacy: VideoPrivacy.PRIVATE, scheduleUpdate: { updateAt: updateAt.toISOString(), - privacy: VideoPrivacy.PUBLIC + privacy: VideoPrivacy.PUBLIC as VideoPrivacy.PUBLIC } } const { name, uuid } = await uploadRandomVideoOnServers(servers, 1, data) @@ -118,7 +117,7 @@ describe('Test user notifications', function () { privacy: VideoPrivacy.PRIVATE, scheduleUpdate: { updateAt: updateAt.toISOString(), - privacy: VideoPrivacy.PUBLIC + privacy: VideoPrivacy.PUBLIC as VideoPrivacy.PUBLIC } } const { name, uuid } = await uploadRandomVideoOnServers(servers, 2, data) @@ -137,7 +136,7 @@ describe('Test user notifications', function () { privacy: VideoPrivacy.PRIVATE, scheduleUpdate: { updateAt: updateAt.toISOString(), - privacy: VideoPrivacy.PUBLIC + privacy: VideoPrivacy.PUBLIC as VideoPrivacy.PUBLIC } } const { name, uuid } = await uploadRandomVideoOnServers(servers, 1, data) @@ -154,7 +153,7 @@ describe('Test user notifications', function () { await checkNewVideoFromSubscription(baseParams, name, uuid, 'absence') - await updateVideo(servers[0].url, servers[0].accessToken, uuid, { privacy: VideoPrivacy.PUBLIC }) + await servers[0].videosCommand.update({ id: uuid, attributes: { privacy: VideoPrivacy.PUBLIC } }) await waitJobs(servers) await checkNewVideoFromSubscription(baseParams, name, uuid, 'presence') @@ -168,7 +167,7 @@ describe('Test user notifications', function () { await checkNewVideoFromSubscription(baseParams, name, uuid, 'absence') - await updateVideo(servers[1].url, servers[1].accessToken, uuid, { privacy: VideoPrivacy.PUBLIC }) + await servers[1].videosCommand.update({ id: uuid, attributes: { privacy: VideoPrivacy.PUBLIC } }) await waitJobs(servers) await checkNewVideoFromSubscription(baseParams, name, uuid, 'presence') @@ -180,7 +179,7 @@ describe('Test user notifications', function () { const data = { privacy: VideoPrivacy.PRIVATE } const { name, uuid } = await uploadRandomVideoOnServers(servers, 1, data) - await updateVideo(servers[0].url, servers[0].accessToken, uuid, { privacy: VideoPrivacy.UNLISTED }) + await servers[0].videosCommand.update({ id: uuid, attributes: { privacy: VideoPrivacy.UNLISTED } }) await checkNewVideoFromSubscription(baseParams, name, uuid, 'absence') }) @@ -191,7 +190,7 @@ describe('Test user notifications', function () { const data = { privacy: VideoPrivacy.PRIVATE } const { name, uuid } = await uploadRandomVideoOnServers(servers, 2, data) - await updateVideo(servers[1].url, servers[1].accessToken, uuid, { privacy: VideoPrivacy.UNLISTED }) + await servers[1].videosCommand.update({ id: uuid, attributes: { privacy: VideoPrivacy.UNLISTED } }) await waitJobs(servers) await checkNewVideoFromSubscription(baseParams, name, uuid, 'absence') @@ -295,7 +294,7 @@ describe('Test user notifications', function () { privacy: VideoPrivacy.PRIVATE, scheduleUpdate: { updateAt: updateAt.toISOString(), - privacy: VideoPrivacy.PUBLIC + privacy: VideoPrivacy.PUBLIC as VideoPrivacy.PUBLIC } } const { name, uuid } = await uploadRandomVideoOnServers(servers, 2, data) @@ -313,7 +312,7 @@ describe('Test user notifications', function () { privacy: VideoPrivacy.PRIVATE, scheduleUpdate: { updateAt: updateAt.toISOString(), - privacy: VideoPrivacy.PUBLIC + privacy: VideoPrivacy.PUBLIC as VideoPrivacy.PUBLIC } } const { name, uuid } = await uploadRandomVideoOnServers(servers, 2, data) diff --git a/server/tests/api/redundancy/manage-redundancy.ts b/server/tests/api/redundancy/manage-redundancy.ts index 03857f512..efb60dc56 100644 --- a/server/tests/api/redundancy/manage-redundancy.ts +++ b/server/tests/api/redundancy/manage-redundancy.ts @@ -6,12 +6,9 @@ import { cleanupTests, doubleFollow, flushAndRunMultipleServers, - getLocalIdByUUID, RedundancyCommand, ServerInfo, setAccessTokensToServers, - uploadVideo, - uploadVideoAndGetId, waitJobs } from '@shared/extra-utils' import { VideoPrivacy, VideoRedundanciesTarget } from '@shared/models' @@ -59,13 +56,13 @@ describe('Test manage videos redundancy', function () { commands = servers.map(s => s.redundancyCommand) { - const res = await uploadVideo(servers[1].url, servers[1].accessToken, { name: 'video 1 server 2' }) - video1Server2UUID = res.body.video.uuid + const { uuid } = await servers[1].videosCommand.upload({ attributes: { name: 'video 1 server 2' } }) + video1Server2UUID = uuid } { - const res = await uploadVideo(servers[1].url, servers[1].accessToken, { name: 'video 2 server 2' }) - video2Server2UUID = res.body.video.uuid + const { uuid } = await servers[1].videosCommand.upload({ attributes: { name: 'video 2 server 2' } }) + video2Server2UUID = uuid } await waitJobs(servers) @@ -206,9 +203,9 @@ describe('Test manage videos redundancy', function () { it('Should manually add a redundancy and list it', async function () { this.timeout(120000) - const uuid = (await uploadVideoAndGetId({ server: servers[1], videoName: 'video 3 server 2', privacy: VideoPrivacy.UNLISTED })).uuid + const uuid = (await servers[1].videosCommand.quickUpload({ name: 'video 3 server 2', privacy: VideoPrivacy.UNLISTED })).uuid await waitJobs(servers) - const videoId = await getLocalIdByUUID(servers[0].url, uuid) + const videoId = await servers[0].videosCommand.getId({ uuid }) await commands[0].addVideo({ videoId }) diff --git a/server/tests/api/redundancy/redundancy-constraints.ts b/server/tests/api/redundancy/redundancy-constraints.ts index a31278de7..b3f6ed160 100644 --- a/server/tests/api/redundancy/redundancy-constraints.ts +++ b/server/tests/api/redundancy/redundancy-constraints.ts @@ -9,8 +9,6 @@ import { reRunServer, ServerInfo, setAccessTokensToServers, - updateVideo, - uploadVideo, waitJobs } from '@shared/extra-utils' import { VideoPrivacy } from '@shared/models' @@ -38,11 +36,11 @@ describe('Test redundancy constraints', function () { async function uploadWrapper (videoName: string) { // Wait for transcoding - const res = await uploadVideo(localServer.url, localServer.accessToken, { name: 'to transcode', privacy: VideoPrivacy.PRIVATE }) + const { id } = await localServer.videosCommand.upload({ attributes: { name: 'to transcode', privacy: VideoPrivacy.PRIVATE } }) await waitJobs([ localServer ]) // Update video to schedule a federation - await updateVideo(localServer.url, localServer.accessToken, res.body.video.id, { name: videoName, privacy: VideoPrivacy.PUBLIC }) + await localServer.videosCommand.update({ id, attributes: { name: videoName, privacy: VideoPrivacy.PUBLIC } }) } async function getTotalRedundanciesLocalServer () { @@ -80,7 +78,7 @@ describe('Test redundancy constraints', function () { // Get the access tokens await setAccessTokensToServers(servers) - await uploadVideo(localServer.url, localServer.accessToken, { name: 'video 1 server 2' }) + await localServer.videosCommand.upload({ attributes: { name: 'video 1 server 2' } }) await waitJobs(servers) diff --git a/server/tests/api/redundancy/redundancy.ts b/server/tests/api/redundancy/redundancy.ts index 00a5e86cc..6ca9c9303 100644 --- a/server/tests/api/redundancy/redundancy.ts +++ b/server/tests/api/redundancy/redundancy.ts @@ -12,22 +12,16 @@ import { cleanupTests, doubleFollow, flushAndRunMultipleServers, - getVideo, - getVideoWithToken, killallServers, makeGetRequest, - removeVideo, reRunServer, root, ServerInfo, setAccessTokensToServers, - updateVideo, - uploadVideo, - viewVideo, wait, waitJobs } from '@shared/extra-utils' -import { VideoDetails, VideoPrivacy, VideoRedundancyStrategy, VideoRedundancyStrategyWithManual } from '@shared/models' +import { VideoPrivacy, VideoRedundancyStrategy, VideoRedundancyStrategyWithManual } from '@shared/models' const expect = chai.expect @@ -84,11 +78,11 @@ async function flushAndRunServers (strategy: VideoRedundancyStrategy | null, add await setAccessTokensToServers(servers) { - const res = await uploadVideo(servers[1].url, servers[1].accessToken, { name: 'video 1 server 2' }) - video1Server2UUID = res.body.video.uuid - video1Server2Id = res.body.video.id + const { uuid, id } = await servers[1].videosCommand.upload({ attributes: { name: 'video 1 server 2' } }) + video1Server2UUID = uuid + video1Server2Id = id - await viewVideo(servers[1].url, video1Server2UUID) + await servers[1].videosCommand.view({ id: video1Server2UUID }) } await waitJobs(servers) @@ -112,9 +106,8 @@ async function check1WebSeed (videoUUID?: string) { for (const server of servers) { // With token to avoid issues with video follow constraints - const res = await getVideoWithToken(server.url, server.accessToken, videoUUID) + const video = await server.videosCommand.getWithToken({ id: videoUUID }) - const video: VideoDetails = res.body for (const f of video.files) { checkMagnetWebseeds(f, webseeds, server) } @@ -130,9 +123,7 @@ async function check2Webseeds (videoUUID?: string) { ] for (const server of servers) { - const res = await getVideo(server.url, videoUUID) - - const video: VideoDetails = res.body + const video = await server.videosCommand.get({ id: videoUUID }) for (const file of video.files) { checkMagnetWebseeds(file, webseeds, server) @@ -172,8 +163,7 @@ async function check0PlaylistRedundancies (videoUUID?: string) { for (const server of servers) { // With token to avoid issues with video follow constraints - const res = await getVideoWithToken(server.url, server.accessToken, videoUUID) - const video: VideoDetails = res.body + const video = await server.videosCommand.getWithToken({ id: videoUUID }) expect(video.streamingPlaylists).to.be.an('array') expect(video.streamingPlaylists).to.have.lengthOf(1) @@ -185,8 +175,7 @@ async function check1PlaylistRedundancies (videoUUID?: string) { if (!videoUUID) videoUUID = video1Server2UUID for (const server of servers) { - const res = await getVideo(server.url, videoUUID) - const video: VideoDetails = res.body + const video = await server.videosCommand.get({ id: videoUUID }) expect(video.streamingPlaylists).to.have.lengthOf(1) expect(video.streamingPlaylists[0].redundancies).to.have.lengthOf(1) @@ -199,8 +188,8 @@ async function check1PlaylistRedundancies (videoUUID?: string) { const baseUrlPlaylist = servers[1].url + '/static/streaming-playlists/hls' const baseUrlSegment = servers[0].url + '/static/redundancy/hls' - const res = await getVideo(servers[0].url, videoUUID) - const hlsPlaylist = (res.body as VideoDetails).streamingPlaylists[0] + const video = await servers[0].videosCommand.get({ id: videoUUID }) + const hlsPlaylist = video.streamingPlaylists[0] for (const resolution of [ 240, 360, 480, 720 ]) { await checkSegmentHash({ server: servers[1], baseUrlPlaylist, baseUrlSegment, videoUUID, resolution, hlsPlaylist }) @@ -427,8 +416,8 @@ describe('Test videos redundancy', function () { it('Should view 2 times the first video to have > min_views config', async function () { this.timeout(80000) - await viewVideo(servers[0].url, video1Server2UUID) - await viewVideo(servers[2].url, video1Server2UUID) + await servers[0].videosCommand.view({ id: video1Server2UUID }) + await servers[2].videosCommand.view({ id: video1Server2UUID }) await wait(10000) await waitJobs(servers) @@ -449,7 +438,7 @@ describe('Test videos redundancy', function () { it('Should remove the video and the redundancy files', async function () { this.timeout(20000) - await removeVideo(servers[1].url, servers[1].accessToken, video1Server2UUID) + await servers[1].videosCommand.remove({ id: video1Server2UUID }) await waitJobs(servers) @@ -495,8 +484,8 @@ describe('Test videos redundancy', function () { it('Should have 1 redundancy on the first video', async function () { this.timeout(160000) - await viewVideo(servers[0].url, video1Server2UUID) - await viewVideo(servers[2].url, video1Server2UUID) + await servers[0].videosCommand.view({ id: video1Server2UUID }) + await servers[2].videosCommand.view({ id: video1Server2UUID }) await wait(10000) await waitJobs(servers) @@ -512,7 +501,7 @@ describe('Test videos redundancy', function () { it('Should remove the video and the redundancy files', async function () { this.timeout(20000) - await removeVideo(servers[1].url, servers[1].accessToken, video1Server2UUID) + await servers[1].videosCommand.remove({ id: video1Server2UUID }) await waitJobs(servers) @@ -588,8 +577,7 @@ describe('Test videos redundancy', function () { async function checkContains (servers: ServerInfo[], str: string) { for (const server of servers) { - const res = await getVideo(server.url, video1Server2UUID) - const video: VideoDetails = res.body + const video = await server.videosCommand.get({ id: video1Server2UUID }) for (const f of video.files) { expect(f.magnetUri).to.contain(str) @@ -599,8 +587,7 @@ describe('Test videos redundancy', function () { async function checkNotContains (servers: ServerInfo[], str: string) { for (const server of servers) { - const res = await getVideo(server.url, video1Server2UUID) - const video: VideoDetails = res.body + const video = await server.videosCommand.get({ id: video1Server2UUID }) for (const f of video.files) { expect(f.magnetUri).to.not.contain(str) @@ -665,13 +652,13 @@ describe('Test videos redundancy', function () { await check1PlaylistRedundancies(video1Server2UUID) await checkStatsWith1Redundancy(strategy) - const res = await uploadVideo(servers[1].url, servers[1].accessToken, { name: 'video 2 server 2', privacy: VideoPrivacy.PRIVATE }) - video2Server2UUID = res.body.video.uuid + const { uuid } = await servers[1].videosCommand.upload({ attributes: { name: 'video 2 server 2', privacy: VideoPrivacy.PRIVATE } }) + video2Server2UUID = uuid // Wait transcoding before federation await waitJobs(servers) - await updateVideo(servers[1].url, servers[1].accessToken, video2Server2UUID, { privacy: VideoPrivacy.PUBLIC }) + await servers[1].videosCommand.update({ id: video2Server2UUID, attributes: { privacy: VideoPrivacy.PUBLIC } }) }) it('Should cache video 2 webseeds on the first video', async function () { diff --git a/server/tests/api/search/search-activitypub-video-channels.ts b/server/tests/api/search/search-activitypub-video-channels.ts index bcc21381c..75794402d 100644 --- a/server/tests/api/search/search-activitypub-video-channels.ts +++ b/server/tests/api/search/search-activitypub-video-channels.ts @@ -5,12 +5,9 @@ import * as chai from 'chai' import { cleanupTests, flushAndRunMultipleServers, - getVideoChannelVideos, SearchCommand, ServerInfo, setAccessTokensToServers, - updateVideo, - uploadVideo, wait, waitJobs } from '@shared/extra-utils' @@ -53,8 +50,9 @@ describe('Test ActivityPub video channels search', function () { const created = await servers[1].channelsCommand.create({ token: userServer2Token, attributes: channel }) channelIdServer2 = created.id - const res = await uploadVideo(servers[1].url, userServer2Token, { name: 'video 1 server 2', channelId: channelIdServer2 }) - videoServer2UUID = res.body.video.uuid + const attributes = { name: 'video 1 server 2', channelId: channelIdServer2 } + const { uuid } = await servers[1].videosCommand.upload({ token: userServer2Token, attributes }) + videoServer2UUID = uuid } await waitJobs(servers) @@ -149,16 +147,21 @@ describe('Test ActivityPub video channels search', function () { await waitJobs(servers) - const res = await getVideoChannelVideos(servers[0].url, null, 'channel1_server2@localhost:' + servers[1].port, 0, 5) - expect(res.body.total).to.equal(0) - expect(res.body.data).to.have.lengthOf(0) + const { total, data } = await servers[0].videosCommand.listByChannel({ + token: null, + videoChannelName: 'channel1_server2@localhost:' + servers[1].port + }) + expect(total).to.equal(0) + expect(data).to.have.lengthOf(0) }) it('Should list video channel videos of server 2 with token', async function () { - const res = await getVideoChannelVideos(servers[0].url, servers[0].accessToken, 'channel1_server2@localhost:' + servers[1].port, 0, 5) + const { total, data } = await servers[0].videosCommand.listByChannel({ + videoChannelName: 'channel1_server2@localhost:' + servers[1].port + }) - expect(res.body.total).to.equal(1) - expect(res.body.data[0].name).to.equal('video 1 server 2') + expect(total).to.equal(1) + expect(data[0].name).to.equal('video 1 server 2') }) it('Should update video channel of server 2, and refresh it on server 1', async function () { @@ -190,8 +193,8 @@ describe('Test ActivityPub video channels search', function () { it('Should update and add a video on server 2, and update it on server 1 after a search', async function () { this.timeout(60000) - await updateVideo(servers[1].url, userServer2Token, videoServer2UUID, { name: 'video 1 updated' }) - await uploadVideo(servers[1].url, userServer2Token, { name: 'video 2 server 2', channelId: channelIdServer2 }) + await servers[1].videosCommand.update({ token: userServer2Token, id: videoServer2UUID, attributes: { name: 'video 1 updated' } }) + await servers[1].videosCommand.upload({ token: userServer2Token, attributes: { name: 'video 2 server 2', channelId: channelIdServer2 } }) await waitJobs(servers) @@ -204,11 +207,11 @@ describe('Test ActivityPub video channels search', function () { await waitJobs(servers) const videoChannelName = 'channel1_server2@localhost:' + servers[1].port - const res = await getVideoChannelVideos(servers[0].url, servers[0].accessToken, videoChannelName, 0, 5, '-createdAt') + const { total, data } = await servers[0].videosCommand.listByChannel({ videoChannelName, sort: '-createdAt' }) - expect(res.body.total).to.equal(2) - expect(res.body.data[0].name).to.equal('video 2 server 2') - expect(res.body.data[1].name).to.equal('video 1 updated') + expect(total).to.equal(2) + expect(data[0].name).to.equal('video 2 server 2') + expect(data[1].name).to.equal('video 1 updated') }) it('Should delete video channel of server 2, and delete it on server 1', async function () { diff --git a/server/tests/api/search/search-activitypub-video-playlists.ts b/server/tests/api/search/search-activitypub-video-playlists.ts index cb7582d29..46105c12c 100644 --- a/server/tests/api/search/search-activitypub-video-playlists.ts +++ b/server/tests/api/search/search-activitypub-video-playlists.ts @@ -9,7 +9,6 @@ import { ServerInfo, setAccessTokensToServers, setDefaultVideoChannel, - uploadVideoAndGetId, wait, waitJobs } from '@shared/extra-utils' @@ -34,8 +33,8 @@ describe('Test ActivityPub playlists search', function () { await setDefaultVideoChannel(servers) { - const video1 = (await uploadVideoAndGetId({ server: servers[0], videoName: 'video 1' })).uuid - const video2 = (await uploadVideoAndGetId({ server: servers[0], videoName: 'video 2' })).uuid + const video1 = (await servers[0].videosCommand.quickUpload({ name: 'video 1' })).uuid + const video2 = (await servers[0].videosCommand.quickUpload({ name: 'video 2' })).uuid const attributes = { displayName: 'playlist 1 on server 1', @@ -51,8 +50,8 @@ describe('Test ActivityPub playlists search', function () { } { - const videoId = (await uploadVideoAndGetId({ server: servers[1], videoName: 'video 1' })).uuid - video2Server2 = (await uploadVideoAndGetId({ server: servers[1], videoName: 'video 2' })).uuid + const videoId = (await servers[1].videosCommand.quickUpload({ name: 'video 1' })).uuid + video2Server2 = (await servers[1].videosCommand.quickUpload({ name: 'video 2' })).uuid const attributes = { displayName: 'playlist 1 on server 2', diff --git a/server/tests/api/search/search-activitypub-videos.ts b/server/tests/api/search/search-activitypub-videos.ts index 403c84010..19b4d5ed8 100644 --- a/server/tests/api/search/search-activitypub-videos.ts +++ b/server/tests/api/search/search-activitypub-videos.ts @@ -5,17 +5,13 @@ import * as chai from 'chai' import { cleanupTests, flushAndRunMultipleServers, - getVideosList, - removeVideo, SearchCommand, ServerInfo, setAccessTokensToServers, - updateVideo, - uploadVideo, - wait -} from '../../../../shared/extra-utils' -import { waitJobs } from '../../../../shared/extra-utils/server/jobs' -import { VideoPrivacy } from '../../../../shared/models/videos' + wait, + waitJobs +} from '@shared/extra-utils' +import { VideoPrivacy } from '@shared/models' const expect = chai.expect @@ -34,13 +30,13 @@ describe('Test ActivityPub videos search', function () { await setAccessTokensToServers(servers) { - const res = await uploadVideo(servers[0].url, servers[0].accessToken, { name: 'video 1 on server 1' }) - videoServer1UUID = res.body.video.uuid + const { uuid } = await servers[0].videosCommand.upload({ attributes: { name: 'video 1 on server 1' } }) + videoServer1UUID = uuid } { - const res = await uploadVideo(servers[1].url, servers[1].accessToken, { name: 'video 1 on server 2' }) - videoServer2UUID = res.body.video.uuid + const { uuid } = await servers[1].videosCommand.upload({ attributes: { name: 'video 1 on server 2' } }) + videoServer2UUID = uuid } await waitJobs(servers) @@ -109,10 +105,10 @@ describe('Test ActivityPub videos search', function () { }) it('Should not list this remote video', async function () { - const res = await getVideosList(servers[0].url) - expect(res.body.total).to.equal(1) - expect(res.body.data).to.have.lengthOf(1) - expect(res.body.data[0].name).to.equal('video 1 on server 1') + const { total, data } = await servers[0].videosCommand.list() + expect(total).to.equal(1) + expect(data).to.have.lengthOf(1) + expect(data[0].name).to.equal('video 1 on server 1') }) it('Should update video of server 2, and refresh it on server 1', async function () { @@ -131,7 +127,7 @@ describe('Test ActivityPub videos search', function () { privacy: VideoPrivacy.UNLISTED, channelId: videoChannelId } - await updateVideo(servers[1].url, servers[1].accessToken, videoServer2UUID, attributes) + await servers[1].videosCommand.update({ id: videoServer2UUID, attributes }) await waitJobs(servers) // Expire video @@ -157,7 +153,7 @@ describe('Test ActivityPub videos search', function () { it('Should delete video of server 2, and delete it on server 1', async function () { this.timeout(120000) - await removeVideo(servers[1].url, servers[1].accessToken, videoServer2UUID) + await servers[1].videosCommand.remove({ id: videoServer2UUID }) await waitJobs(servers) // Expire video diff --git a/server/tests/api/search/search-index.ts b/server/tests/api/search/search-index.ts index 306f84c3a..d5dc40f60 100644 --- a/server/tests/api/search/search-index.ts +++ b/server/tests/api/search/search-index.ts @@ -2,7 +2,7 @@ import 'mocha' import * as chai from 'chai' -import { cleanupTests, flushAndRunServer, SearchCommand, ServerInfo, setAccessTokensToServers, uploadVideo } from '@shared/extra-utils' +import { cleanupTests, flushAndRunServer, SearchCommand, ServerInfo, setAccessTokensToServers } from '@shared/extra-utils' import { BooleanBothQuery, VideoPlaylistPrivacy, VideoPlaylistType, VideosSearchQuery } from '@shared/models' const expect = chai.expect @@ -20,7 +20,7 @@ describe('Test videos search', function () { await setAccessTokensToServers([ server ]) - await uploadVideo(server.url, server.accessToken, { name: localVideoName }) + await server.videosCommand.upload({ attributes: { name: localVideoName } }) command = server.searchCommand }) diff --git a/server/tests/api/search/search-playlists.ts b/server/tests/api/search/search-playlists.ts index 517884503..2e4773ed6 100644 --- a/server/tests/api/search/search-playlists.ts +++ b/server/tests/api/search/search-playlists.ts @@ -2,16 +2,15 @@ import 'mocha' import * as chai from 'chai' -import { VideoPlaylistPrivacy } from '@shared/models' import { cleanupTests, flushAndRunServer, SearchCommand, ServerInfo, setAccessTokensToServers, - setDefaultVideoChannel, - uploadVideoAndGetId -} from '../../../../shared/extra-utils' + setDefaultVideoChannel +} from '@shared/extra-utils' +import { VideoPlaylistPrivacy } from '@shared/models' const expect = chai.expect @@ -27,7 +26,7 @@ describe('Test playlists search', function () { await setAccessTokensToServers([ server ]) await setDefaultVideoChannel([ server ]) - const videoId = (await uploadVideoAndGetId({ server: server, videoName: 'video' })).uuid + const videoId = (await server.videosCommand.quickUpload({ name: 'video' })).uuid { const attributes = { diff --git a/server/tests/api/search/search-videos.ts b/server/tests/api/search/search-videos.ts index 66f5f3182..148499d5f 100644 --- a/server/tests/api/search/search-videos.ts +++ b/server/tests/api/search/search-videos.ts @@ -10,7 +10,6 @@ import { setAccessTokensToServers, setDefaultVideoChannel, stopFfmpeg, - uploadVideo, wait } from '@shared/extra-utils' import { VideoPrivacy } from '@shared/models' @@ -41,50 +40,49 @@ describe('Test videos search', function () { nsfw: false, language: 'fr' } - await uploadVideo(server.url, server.accessToken, attributes1) + await server.videosCommand.upload({ attributes: attributes1 }) const attributes2 = { ...attributes1, name: attributes1.name + ' - 2', fixture: 'video_short.mp4' } - await uploadVideo(server.url, server.accessToken, attributes2) + await server.videosCommand.upload({ attributes: attributes2 }) { const attributes3 = { ...attributes1, name: attributes1.name + ' - 3', language: undefined } - const res = await uploadVideo(server.url, server.accessToken, attributes3) - const videoId = res.body.video.id - videoUUID = res.body.video.uuid + const { id, uuid } = await server.videosCommand.upload({ attributes: attributes3 }) + videoUUID = uuid await server.captionsCommand.createVideoCaption({ language: 'en', - videoId, + videoId: id, fixture: 'subtitle-good2.vtt', mimeType: 'application/octet-stream' }) await server.captionsCommand.createVideoCaption({ language: 'aa', - videoId, + videoId: id, fixture: 'subtitle-good2.vtt', mimeType: 'application/octet-stream' }) } const attributes4 = { ...attributes1, name: attributes1.name + ' - 4', language: 'pl', nsfw: true } - await uploadVideo(server.url, server.accessToken, attributes4) + await server.videosCommand.upload({ attributes: attributes4 }) await wait(1000) startDate = new Date().toISOString() const attributes5 = { ...attributes1, name: attributes1.name + ' - 5', licence: 2, language: undefined } - await uploadVideo(server.url, server.accessToken, attributes5) + await server.videosCommand.upload({ attributes: attributes5 }) const attributes6 = { ...attributes1, name: attributes1.name + ' - 6', tags: [ 't1', 't2' ] } - await uploadVideo(server.url, server.accessToken, attributes6) + await server.videosCommand.upload({ attributes: attributes6 }) const attributes7 = { ...attributes1, name: attributes1.name + ' - 7', originallyPublishedAt: '2019-02-12T09:58:08.286Z' } - await uploadVideo(server.url, server.accessToken, attributes7) + await server.videosCommand.upload({ attributes: attributes7 }) const attributes8 = { ...attributes1, name: attributes1.name + ' - 8', licence: 4 } - await uploadVideo(server.url, server.accessToken, attributes8) + await server.videosCommand.upload({ attributes: attributes8 }) } { @@ -95,9 +93,9 @@ describe('Test videos search', function () { licence: 2, language: 'en' } - await uploadVideo(server.url, server.accessToken, attributes) + await server.videosCommand.upload({ attributes: attributes }) - await uploadVideo(server.url, server.accessToken, { ...attributes, name: attributes.name + ' duplicate' }) + await server.videosCommand.upload({ attributes: { ...attributes, name: attributes.name + ' duplicate' } }) } { @@ -108,7 +106,7 @@ describe('Test videos search', function () { licence: 3, language: 'pl' } - await uploadVideo(server.url, server.accessToken, attributes) + await server.videosCommand.upload({ attributes: attributes }) } { @@ -117,11 +115,11 @@ describe('Test videos search', function () { tags: [ 'aaaa', 'bbbb', 'cccc' ], category: 1 } - await uploadVideo(server.url, server.accessToken, attributes1) - await uploadVideo(server.url, server.accessToken, { ...attributes1, category: 2 }) + await server.videosCommand.upload({ attributes: attributes1 }) + await server.videosCommand.upload({ attributes: { ...attributes1, category: 2 } }) - await uploadVideo(server.url, server.accessToken, { ...attributes1, tags: [ 'cccc', 'dddd' ] }) - await uploadVideo(server.url, server.accessToken, { ...attributes1, tags: [ 'eeee', 'ffff' ] }) + await server.videosCommand.upload({ attributes: { ...attributes1, tags: [ 'cccc', 'dddd' ] } }) + await server.videosCommand.upload({ attributes: { ...attributes1, tags: [ 'eeee', 'ffff' ] } }) } { @@ -129,8 +127,8 @@ describe('Test videos search', function () { name: 'aaaa 2', category: 1 } - await uploadVideo(server.url, server.accessToken, attributes1) - await uploadVideo(server.url, server.accessToken, { ...attributes1, category: 2 }) + await server.videosCommand.upload({ attributes: attributes1 }) + await server.videosCommand.upload({ attributes: { ...attributes1, category: 2 } }) } command = server.searchCommand diff --git a/server/tests/api/server/bulk.ts b/server/tests/api/server/bulk.ts index 20a9a3dc7..c83bcfb22 100644 --- a/server/tests/api/server/bulk.ts +++ b/server/tests/api/server/bulk.ts @@ -7,13 +7,10 @@ import { cleanupTests, doubleFollow, flushAndRunMultipleServers, - getVideosList, ServerInfo, setAccessTokensToServers, - uploadVideo, waitJobs } from '@shared/extra-utils' -import { Video } from '@shared/models' const expect = chai.expect @@ -64,11 +61,10 @@ describe('Test bulk actions', function () { describe('Bulk remove comments', function () { async function checkInstanceCommentsRemoved () { { - const res = await getVideosList(servers[0].url) - const videos = res.body.data as Video[] + const { data } = await servers[0].videosCommand.list() // Server 1 should not have these comments anymore - for (const video of videos) { + for (const video of data) { const { data } = await servers[0].commentsCommand.listThreads({ videoId: video.id }) const comment = data.find(c => c.text === 'comment by user 3') @@ -77,11 +73,10 @@ describe('Test bulk actions', function () { } { - const res = await getVideosList(servers[1].url) - const videos = res.body.data as Video[] + const { data } = await servers[1].videosCommand.list() // Server 1 should not have these comments on videos of server 1 - for (const video of videos) { + for (const video of data) { const { data } = await servers[1].commentsCommand.listThreads({ videoId: video.id }) const comment = data.find(c => c.text === 'comment by user 3') @@ -97,17 +92,17 @@ describe('Test bulk actions', function () { before(async function () { this.timeout(120000) - await uploadVideo(servers[0].url, servers[0].accessToken, { name: 'video 1 server 1' }) - await uploadVideo(servers[0].url, servers[0].accessToken, { name: 'video 2 server 1' }) - await uploadVideo(servers[0].url, user1Token, { name: 'video 3 server 1' }) + await servers[0].videosCommand.upload({ attributes: { name: 'video 1 server 1' } }) + await servers[0].videosCommand.upload({ attributes: { name: 'video 2 server 1' } }) + await servers[0].videosCommand.upload({ token: user1Token, attributes: { name: 'video 3 server 1' } }) - await uploadVideo(servers[1].url, servers[1].accessToken, { name: 'video 1 server 2' }) + await servers[1].videosCommand.upload({ attributes: { name: 'video 1 server 2' } }) await waitJobs(servers) { - const res = await getVideosList(servers[0].url) - for (const video of res.body.data) { + const { data } = await servers[0].videosCommand.list() + for (const video of data) { await servers[0].commentsCommand.createThread({ videoId: video.id, text: 'comment by root server 1' }) await servers[0].commentsCommand.createThread({ token: user1Token, videoId: video.id, text: 'comment by user 1' }) await servers[0].commentsCommand.createThread({ token: user2Token, videoId: video.id, text: 'comment by user 2' }) @@ -115,9 +110,9 @@ describe('Test bulk actions', function () { } { - const res = await getVideosList(servers[1].url) + const { data } = await servers[1].videosCommand.list() - for (const video of res.body.data) { + for (const video of data) { await servers[1].commentsCommand.createThread({ videoId: video.id, text: 'comment by root server 2' }) const comment = await servers[1].commentsCommand.createThread({ token: user3Token, videoId: video.id, text: 'comment by user 3' }) @@ -142,9 +137,9 @@ describe('Test bulk actions', function () { await waitJobs(servers) for (const server of servers) { - const res = await getVideosList(server.url) + const { data } = await server.videosCommand.list() - for (const video of res.body.data) { + for (const video of data) { const { data } = await server.commentsCommand.listThreads({ videoId: video.id }) const comment = data.find(c => c.text === 'comment by user 2') diff --git a/server/tests/api/server/config.ts b/server/tests/api/server/config.ts index 95dafd378..c613511ed 100644 --- a/server/tests/api/server/config.ts +++ b/server/tests/api/server/config.ts @@ -11,8 +11,7 @@ import { parallelTests, reRunServer, ServerInfo, - setAccessTokensToServers, - uploadVideo + setAccessTokensToServers } from '@shared/extra-utils' import { CustomConfig } from '@shared/models' @@ -242,8 +241,8 @@ describe('Test config', function () { expect(data.video.file.extensions).to.contain('.webm') expect(data.video.file.extensions).to.contain('.ogv') - await uploadVideo(server.url, server.accessToken, { fixture: 'video_short.mkv' }, HttpStatusCode.UNSUPPORTED_MEDIA_TYPE_415) - await uploadVideo(server.url, server.accessToken, { fixture: 'sample.ogg' }, HttpStatusCode.UNSUPPORTED_MEDIA_TYPE_415) + await server.videosCommand.upload({ attributes: { fixture: 'video_short.mkv' }, expectedStatus: HttpStatusCode.UNSUPPORTED_MEDIA_TYPE_415 }) + await server.videosCommand.upload({ attributes: { fixture: 'sample.ogg' }, expectedStatus: HttpStatusCode.UNSUPPORTED_MEDIA_TYPE_415 }) expect(data.contactForm.enabled).to.be.true }) @@ -448,8 +447,8 @@ describe('Test config', function () { expect(data.video.file.extensions).to.contain('.ogg') expect(data.video.file.extensions).to.contain('.flac') - await uploadVideo(server.url, server.accessToken, { fixture: 'video_short.mkv' }, HttpStatusCode.OK_200) - await uploadVideo(server.url, server.accessToken, { fixture: 'sample.ogg' }, HttpStatusCode.OK_200) + await server.videosCommand.upload({ attributes: { fixture: 'video_short.mkv' }, expectedStatus: HttpStatusCode.OK_200 }) + await server.videosCommand.upload({ attributes: { fixture: 'sample.ogg' }, expectedStatus: HttpStatusCode.OK_200 }) }) it('Should have the configuration updated after a restart', async function () { diff --git a/server/tests/api/server/email.ts b/server/tests/api/server/email.ts index 422db6ceb..aeda5fddb 100644 --- a/server/tests/api/server/email.ts +++ b/server/tests/api/server/email.ts @@ -3,15 +3,7 @@ import 'mocha' import * as chai from 'chai' import { HttpStatusCode } from '@shared/core-utils' -import { - cleanupTests, - flushAndRunServer, - MockSmtpServer, - ServerInfo, - setAccessTokensToServers, - uploadVideo, - waitJobs -} from '@shared/extra-utils' +import { cleanupTests, flushAndRunServer, MockSmtpServer, ServerInfo, setAccessTokensToServers, waitJobs } from '@shared/extra-utils' const expect = chai.expect @@ -58,20 +50,18 @@ describe('Test emails', function () { } { - const attributes = { - name: 'my super user video' - } - const res = await uploadVideo(server.url, userAccessToken, attributes) - videoUserUUID = res.body.video.uuid + const attributes = { name: 'my super user video' } + const { uuid } = await server.videosCommand.upload({ token: userAccessToken, attributes }) + videoUserUUID = uuid } { const attributes = { name: 'my super name' } - const res = await uploadVideo(server.url, server.accessToken, attributes) - videoUUID = res.body.video.uuid - videoId = res.body.video.id + const { uuid, id } = await server.videosCommand.upload({ attributes }) + videoUUID = uuid + videoId = id } }) diff --git a/server/tests/api/server/follow-constraints.ts b/server/tests/api/server/follow-constraints.ts index 29ccb264d..f9014aeee 100644 --- a/server/tests/api/server/follow-constraints.ts +++ b/server/tests/api/server/follow-constraints.ts @@ -3,19 +3,8 @@ import 'mocha' import * as chai from 'chai' import { HttpStatusCode } from '@shared/core-utils' +import { cleanupTests, doubleFollow, flushAndRunMultipleServers, ServerInfo, setAccessTokensToServers } from '@shared/extra-utils' import { PeerTubeProblemDocument, ServerErrorCode } from '@shared/models' -import { - cleanupTests, - doubleFollow, - flushAndRunMultipleServers, - getAccountVideos, - getVideo, - getVideoChannelVideos, - getVideoWithToken, - ServerInfo, - setAccessTokensToServers, - uploadVideo -} from '../../../../shared/extra-utils' const expect = chai.expect @@ -23,7 +12,7 @@ describe('Test follow constraints', function () { let servers: ServerInfo[] = [] let video1UUID: string let video2UUID: string - let userAccessToken: string + let userToken: string before(async function () { this.timeout(90000) @@ -34,12 +23,12 @@ describe('Test follow constraints', function () { await setAccessTokensToServers(servers) { - const res = await uploadVideo(servers[0].url, servers[0].accessToken, { name: 'video server 1' }) - video1UUID = res.body.video.uuid + const { uuid } = await servers[0].videosCommand.upload({ attributes: { name: 'video server 1' } }) + video1UUID = uuid } { - const res = await uploadVideo(servers[1].url, servers[1].accessToken, { name: 'video server 2' }) - video2UUID = res.body.video.uuid + const { uuid } = await servers[1].videosCommand.upload({ attributes: { name: 'video server 2' } }) + video2UUID = uuid } const user = { @@ -47,7 +36,7 @@ describe('Test follow constraints', function () { password: 'super_password' } await servers[0].usersCommand.create({ username: user.username, password: user.password }) - userAccessToken = await servers[0].loginCommand.getAccessToken(user) + userToken = await servers[0].loginCommand.getAccessToken(user) await doubleFollow(servers[0], servers[1]) }) @@ -57,81 +46,81 @@ describe('Test follow constraints', function () { describe('With an unlogged user', function () { it('Should get the local video', async function () { - await getVideo(servers[0].url, video1UUID, HttpStatusCode.OK_200) + await servers[0].videosCommand.get({ id: video1UUID }) }) it('Should get the remote video', async function () { - await getVideo(servers[0].url, video2UUID, HttpStatusCode.OK_200) + await servers[0].videosCommand.get({ id: video2UUID }) }) it('Should list local account videos', async function () { - const res = await getAccountVideos(servers[0].url, undefined, 'root@localhost:' + servers[0].port, 0, 5) + const { total, data } = await servers[0].videosCommand.listByAccount({ accountName: 'root@localhost:' + servers[0].port }) - expect(res.body.total).to.equal(1) - expect(res.body.data).to.have.lengthOf(1) + expect(total).to.equal(1) + expect(data).to.have.lengthOf(1) }) it('Should list remote account videos', async function () { - const res = await getAccountVideos(servers[0].url, undefined, 'root@localhost:' + servers[1].port, 0, 5) + const { total, data } = await servers[0].videosCommand.listByAccount({ accountName: 'root@localhost:' + servers[1].port }) - expect(res.body.total).to.equal(1) - expect(res.body.data).to.have.lengthOf(1) + expect(total).to.equal(1) + expect(data).to.have.lengthOf(1) }) it('Should list local channel videos', async function () { const videoChannelName = 'root_channel@localhost:' + servers[0].port - const res = await getVideoChannelVideos(servers[0].url, undefined, videoChannelName, 0, 5) + const { total, data } = await servers[0].videosCommand.listByChannel({ videoChannelName }) - expect(res.body.total).to.equal(1) - expect(res.body.data).to.have.lengthOf(1) + expect(total).to.equal(1) + expect(data).to.have.lengthOf(1) }) it('Should list remote channel videos', async function () { const videoChannelName = 'root_channel@localhost:' + servers[1].port - const res = await getVideoChannelVideos(servers[0].url, undefined, videoChannelName, 0, 5) + const { total, data } = await servers[0].videosCommand.listByChannel({ videoChannelName }) - expect(res.body.total).to.equal(1) - expect(res.body.data).to.have.lengthOf(1) + expect(total).to.equal(1) + expect(data).to.have.lengthOf(1) }) }) describe('With a logged user', function () { it('Should get the local video', async function () { - await getVideoWithToken(servers[0].url, userAccessToken, video1UUID, HttpStatusCode.OK_200) + await servers[0].videosCommand.getWithToken({ token: userToken, id: video1UUID }) }) it('Should get the remote video', async function () { - await getVideoWithToken(servers[0].url, userAccessToken, video2UUID, HttpStatusCode.OK_200) + await servers[0].videosCommand.getWithToken({ token: userToken, id: video2UUID }) }) it('Should list local account videos', async function () { - const res = await getAccountVideos(servers[0].url, userAccessToken, 'root@localhost:' + servers[0].port, 0, 5) + const { total, data } = await servers[0].videosCommand.listByAccount({ token: userToken, accountName: 'root@localhost:' + servers[0].port }) - expect(res.body.total).to.equal(1) - expect(res.body.data).to.have.lengthOf(1) + expect(total).to.equal(1) + expect(data).to.have.lengthOf(1) }) it('Should list remote account videos', async function () { - const res = await getAccountVideos(servers[0].url, userAccessToken, 'root@localhost:' + servers[1].port, 0, 5) + const { total, data } = await servers[0].videosCommand.listByAccount({ token: userToken, accountName: 'root@localhost:' + servers[1].port }) - expect(res.body.total).to.equal(1) - expect(res.body.data).to.have.lengthOf(1) + expect(total).to.equal(1) + expect(data).to.have.lengthOf(1) }) it('Should list local channel videos', async function () { const videoChannelName = 'root_channel@localhost:' + servers[0].port - const res = await getVideoChannelVideos(servers[0].url, userAccessToken, videoChannelName, 0, 5) + const { total, data } = await servers[0].videosCommand.listByChannel({ token: userToken, videoChannelName }) - expect(res.body.total).to.equal(1) - expect(res.body.data).to.have.lengthOf(1) + expect(total).to.equal(1) + expect(data).to.have.lengthOf(1) }) it('Should list remote channel videos', async function () { const videoChannelName = 'root_channel@localhost:' + servers[1].port - const res = await getVideoChannelVideos(servers[0].url, userAccessToken, videoChannelName, 0, 5) + const { total, data } = await servers[0].videosCommand.listByChannel({ token: userToken, videoChannelName }) - expect(res.body.total).to.equal(1) - expect(res.body.data).to.have.lengthOf(1) + expect(total).to.equal(1) + expect(data).to.have.lengthOf(1) }) }) }) @@ -147,13 +136,12 @@ describe('Test follow constraints', function () { describe('With an unlogged user', function () { it('Should get the local video', async function () { - await getVideo(servers[0].url, video1UUID, HttpStatusCode.OK_200) + await servers[0].videosCommand.get({ id: video1UUID }) }) it('Should not get the remote video', async function () { - const res = await getVideo(servers[0].url, video2UUID, HttpStatusCode.FORBIDDEN_403) - - const error = res.body as PeerTubeProblemDocument + const body = await servers[0].videosCommand.get({ id: video2UUID, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) + const error = body as unknown as PeerTubeProblemDocument const doc = 'https://docs.joinpeertube.org/api-rest-reference.html#section/Errors/does_not_respect_follow_constraints' expect(error.type).to.equal(doc) @@ -168,73 +156,79 @@ describe('Test follow constraints', function () { }) it('Should list local account videos', async function () { - const res = await getAccountVideos(servers[0].url, undefined, 'root@localhost:' + servers[0].port, 0, 5) + const { total, data } = await servers[0].videosCommand.listByAccount({ + token: undefined, + accountName: 'root@localhost:' + servers[0].port + }) - expect(res.body.total).to.equal(1) - expect(res.body.data).to.have.lengthOf(1) + expect(total).to.equal(1) + expect(data).to.have.lengthOf(1) }) it('Should not list remote account videos', async function () { - const res = await getAccountVideos(servers[0].url, undefined, 'root@localhost:' + servers[1].port, 0, 5) + const { total, data } = await servers[0].videosCommand.listByAccount({ + token: undefined, + accountName: 'root@localhost:' + servers[1].port + }) - expect(res.body.total).to.equal(0) - expect(res.body.data).to.have.lengthOf(0) + expect(total).to.equal(0) + expect(data).to.have.lengthOf(0) }) it('Should list local channel videos', async function () { const videoChannelName = 'root_channel@localhost:' + servers[0].port - const res = await getVideoChannelVideos(servers[0].url, undefined, videoChannelName, 0, 5) + const { total, data } = await servers[0].videosCommand.listByChannel({ token: undefined, videoChannelName }) - expect(res.body.total).to.equal(1) - expect(res.body.data).to.have.lengthOf(1) + expect(total).to.equal(1) + expect(data).to.have.lengthOf(1) }) it('Should not list remote channel videos', async function () { const videoChannelName = 'root_channel@localhost:' + servers[1].port - const res = await getVideoChannelVideos(servers[0].url, undefined, videoChannelName, 0, 5) + const { total, data } = await servers[0].videosCommand.listByChannel({ token: undefined, videoChannelName }) - expect(res.body.total).to.equal(0) - expect(res.body.data).to.have.lengthOf(0) + expect(total).to.equal(0) + expect(data).to.have.lengthOf(0) }) }) describe('With a logged user', function () { it('Should get the local video', async function () { - await getVideoWithToken(servers[0].url, userAccessToken, video1UUID, HttpStatusCode.OK_200) + await servers[0].videosCommand.getWithToken({ token: userToken, id: video1UUID }) }) it('Should get the remote video', async function () { - await getVideoWithToken(servers[0].url, userAccessToken, video2UUID, HttpStatusCode.OK_200) + await servers[0].videosCommand.getWithToken({ token: userToken, id: video2UUID }) }) it('Should list local account videos', async function () { - const res = await getAccountVideos(servers[0].url, userAccessToken, 'root@localhost:' + servers[0].port, 0, 5) + const { total, data } = await servers[0].videosCommand.listByAccount({ token: userToken, accountName: 'root@localhost:' + servers[0].port }) - expect(res.body.total).to.equal(1) - expect(res.body.data).to.have.lengthOf(1) + expect(total).to.equal(1) + expect(data).to.have.lengthOf(1) }) it('Should list remote account videos', async function () { - const res = await getAccountVideos(servers[0].url, userAccessToken, 'root@localhost:' + servers[1].port, 0, 5) + const { total, data } = await servers[0].videosCommand.listByAccount({ token: userToken, accountName: 'root@localhost:' + servers[1].port }) - expect(res.body.total).to.equal(1) - expect(res.body.data).to.have.lengthOf(1) + expect(total).to.equal(1) + expect(data).to.have.lengthOf(1) }) it('Should list local channel videos', async function () { const videoChannelName = 'root_channel@localhost:' + servers[0].port - const res = await getVideoChannelVideos(servers[0].url, userAccessToken, videoChannelName, 0, 5) + const { total, data } = await servers[0].videosCommand.listByChannel({ token: userToken, videoChannelName }) - expect(res.body.total).to.equal(1) - expect(res.body.data).to.have.lengthOf(1) + expect(total).to.equal(1) + expect(data).to.have.lengthOf(1) }) it('Should list remote channel videos', async function () { const videoChannelName = 'root_channel@localhost:' + servers[1].port - const res = await getVideoChannelVideos(servers[0].url, userAccessToken, videoChannelName, 0, 5) + const { total, data } = await servers[0].videosCommand.listByChannel({ token: userToken, videoChannelName }) - expect(res.body.total).to.equal(1) - expect(res.body.data).to.have.lengthOf(1) + expect(total).to.equal(1) + expect(data).to.have.lengthOf(1) }) }) }) diff --git a/server/tests/api/server/follows.ts b/server/tests/api/server/follows.ts index 02d25e67f..5ce8938fa 100644 --- a/server/tests/api/server/follows.ts +++ b/server/tests/api/server/follows.ts @@ -9,12 +9,9 @@ import { expectAccountFollows, flushAndRunMultipleServers, FollowsCommand, - getVideosList, - rateVideo, ServerInfo, setAccessTokensToServers, testCaptionFile, - uploadVideo, waitJobs } from '@shared/extra-utils' import { Video, VideoPrivacy } from '@shared/models' @@ -287,22 +284,28 @@ describe('Test follows', function () { it('Should upload a video on server 2 and 3 and propagate only the video of server 2', async function () { this.timeout(60000) - await uploadVideo(servers[1].url, servers[1].accessToken, { name: 'server2' }) - await uploadVideo(servers[2].url, servers[2].accessToken, { name: 'server3' }) + await servers[1].videosCommand.upload({ attributes: { name: 'server2' } }) + await servers[2].videosCommand.upload({ attributes: { name: 'server3' } }) await waitJobs(servers) - let res = await getVideosList(servers[0].url) - expect(res.body.total).to.equal(1) - expect(res.body.data[0].name).to.equal('server2') + { + const { total, data } = await servers[0].videosCommand.list() + expect(total).to.equal(1) + expect(data[0].name).to.equal('server2') + } - res = await getVideosList(servers[1].url) - expect(res.body.total).to.equal(1) - expect(res.body.data[0].name).to.equal('server2') + { + const { total, data } = await servers[1].videosCommand.list() + expect(total).to.equal(1) + expect(data[0].name).to.equal('server2') + } - res = await getVideosList(servers[2].url) - expect(res.body.total).to.equal(1) - expect(res.body.data[0].name).to.equal('server3') + { + const { total, data } = await servers[2].videosCommand.list() + expect(total).to.equal(1) + expect(data[0].name).to.equal('server3') + } }) describe('Should propagate data on a new following', function () { @@ -319,21 +322,21 @@ describe('Test follows', function () { tags: [ 'tag1', 'tag2', 'tag3' ] } - await uploadVideo(servers[2].url, servers[2].accessToken, { name: 'server3-2' }) - await uploadVideo(servers[2].url, servers[2].accessToken, { name: 'server3-3' }) - await uploadVideo(servers[2].url, servers[2].accessToken, video4Attributes) - await uploadVideo(servers[2].url, servers[2].accessToken, { name: 'server3-5' }) - await uploadVideo(servers[2].url, servers[2].accessToken, { name: 'server3-6' }) + await servers[2].videosCommand.upload({ attributes: { name: 'server3-2' } }) + await servers[2].videosCommand.upload({ attributes: { name: 'server3-3' } }) + await servers[2].videosCommand.upload({ attributes: video4Attributes }) + await servers[2].videosCommand.upload({ attributes: { name: 'server3-5' } }) + await servers[2].videosCommand.upload({ attributes: { name: 'server3-6' } }) { const userAccessToken = await servers[2].usersCommand.generateUserAndToken('captain') - const resVideos = await getVideosList(servers[2].url) - video4 = resVideos.body.data.find(v => v.name === 'server3-4') + const { data } = await servers[2].videosCommand.list() + video4 = data.find(v => v.name === 'server3-4') { - await rateVideo(servers[2].url, servers[2].accessToken, video4.id, 'like') - await rateVideo(servers[2].url, userAccessToken, video4.id, 'dislike') + await servers[2].videosCommand.rate({ id: video4.id, rating: 'like' }) + await servers[2].videosCommand.rate({ token: userAccessToken, id: video4.id, rating: 'dislike' }) } { @@ -401,12 +404,12 @@ describe('Test follows', function () { }) it('Should have propagated videos', async function () { - const res = await getVideosList(servers[0].url) - expect(res.body.total).to.equal(7) + const { total, data } = await servers[0].videosCommand.list() + expect(total).to.equal(7) - const video2 = res.body.data.find(v => v.name === 'server3-2') - video4 = res.body.data.find(v => v.name === 'server3-4') - const video6 = res.body.data.find(v => v.name === 'server3-6') + const video2 = data.find(v => v.name === 'server3-2') + video4 = data.find(v => v.name === 'server3-4') + const video6 = data.find(v => v.name === 'server3-6') expect(video2).to.not.be.undefined expect(video4).to.not.be.undefined @@ -447,7 +450,7 @@ describe('Test follows', function () { } ] } - await completeVideoCheck(servers[0].url, video4, checkAttributes) + await completeVideoCheck(servers[0], video4, checkAttributes) }) it('Should have propagated comments', async function () { @@ -542,8 +545,8 @@ describe('Test follows', function () { await waitJobs(servers) - const res = await getVideosList(servers[0].url) - expect(res.body.total).to.equal(1) + const { total } = await servers[0].videosCommand.list() + expect(total).to.equal(1) }) }) diff --git a/server/tests/api/server/handle-down.ts b/server/tests/api/server/handle-down.ts index d45c3ae8a..35b905a8c 100644 --- a/server/tests/api/server/handle-down.ts +++ b/server/tests/api/server/handle-down.ts @@ -8,19 +8,14 @@ import { CommentsCommand, completeVideoCheck, flushAndRunMultipleServers, - getVideo, - getVideosList, killallServers, reRunServer, ServerInfo, setAccessTokensToServers, - updateVideo, - uploadVideo, - uploadVideoAndGetId, wait, waitJobs } from '@shared/extra-utils' -import { JobState, Video, VideoPrivacy } from '@shared/models' +import { JobState, VideoCreateResult, VideoPrivacy } from '@shared/models' const expect = chai.expect @@ -30,9 +25,9 @@ describe('Test handle downs', function () { let threadIdServer2: number let commentIdServer1: number let commentIdServer2: number - let missedVideo1: Video - let missedVideo2: Video - let unlistedVideo: Video + let missedVideo1: VideoCreateResult + let missedVideo2: VideoCreateResult + let unlistedVideo: VideoCreateResult const videoIdsServer1: string[] = [] @@ -110,15 +105,15 @@ describe('Test handle downs', function () { await waitJobs(servers) // Upload a video to server 1 - await uploadVideo(servers[0].url, servers[0].accessToken, videoAttributes) + await servers[0].videosCommand.upload({ attributes: videoAttributes }) await waitJobs(servers) // And check all servers have this video for (const server of servers) { - const res = await getVideosList(server.url) - expect(res.body.data).to.be.an('array') - expect(res.body.data).to.have.lengthOf(1) + const { data } = await server.videosCommand.list() + expect(data).to.be.an('array') + expect(data).to.have.lengthOf(1) } // Kill server 2 @@ -126,7 +121,7 @@ describe('Test handle downs', function () { // Remove server 2 follower for (let i = 0; i < 10; i++) { - await uploadVideo(servers[0].url, servers[0].accessToken, videoAttributes) + await servers[0].videosCommand.upload({ attributes: videoAttributes }) } await waitJobs([ servers[0], servers[2] ]) @@ -134,15 +129,12 @@ describe('Test handle downs', function () { // Kill server 3 await killallServers([ servers[2] ]) - const resLastVideo1 = await uploadVideo(servers[0].url, servers[0].accessToken, videoAttributes) - missedVideo1 = resLastVideo1.body.video + missedVideo1 = await servers[0].videosCommand.upload({ attributes: videoAttributes }) - const resLastVideo2 = await uploadVideo(servers[0].url, servers[0].accessToken, videoAttributes) - missedVideo2 = resLastVideo2.body.video + missedVideo2 = await servers[0].videosCommand.upload({ attributes: videoAttributes }) // Unlisted video - const resVideo = await uploadVideo(servers[0].url, servers[0].accessToken, unlistedVideoAttributes) - unlistedVideo = resVideo.body.video + unlistedVideo = await servers[0].videosCommand.upload({ attributes: unlistedVideoAttributes }) // Add comments to video 2 { @@ -202,25 +194,27 @@ describe('Test handle downs', function () { it('Should send an update to server 3, and automatically fetch the video', async function () { this.timeout(15000) - const res1 = await getVideosList(servers[2].url) - expect(res1.body.data).to.be.an('array') - expect(res1.body.data).to.have.lengthOf(11) + { + const { data } = await servers[2].videosCommand.list() + expect(data).to.be.an('array') + expect(data).to.have.lengthOf(11) + } - await updateVideo(servers[0].url, servers[0].accessToken, missedVideo1.uuid, {}) - await updateVideo(servers[0].url, servers[0].accessToken, unlistedVideo.uuid, {}) + await servers[0].videosCommand.update({ id: missedVideo1.uuid }) + await servers[0].videosCommand.update({ id: unlistedVideo.uuid }) await waitJobs(servers) - const res = await getVideosList(servers[2].url) - expect(res.body.data).to.be.an('array') - // 1 video is unlisted - expect(res.body.data).to.have.lengthOf(12) + { + const { data } = await servers[2].videosCommand.list() + expect(data).to.be.an('array') + // 1 video is unlisted + expect(data).to.have.lengthOf(12) + } // Check unlisted video - const resVideo = await getVideo(servers[2].url, unlistedVideo.uuid) - expect(resVideo.body).not.to.be.undefined - - await completeVideoCheck(servers[2].url, resVideo.body, unlistedCheckAttributes) + const video = await servers[2].videosCommand.get({ id: unlistedVideo.uuid }) + await completeVideoCheck(servers[2], video, unlistedCheckAttributes) }) it('Should send comments on a video to server 3, and automatically fetch the video', async function () { @@ -230,8 +224,7 @@ describe('Test handle downs', function () { await waitJobs(servers) - const resVideo = await getVideo(servers[2].url, missedVideo2.uuid) - expect(resVideo.body).not.to.be.undefined + await servers[2].videosCommand.get({ id: missedVideo2.uuid }) { const { data } = await servers[2].commentsCommand.listThreads({ videoId: missedVideo2.uuid }) @@ -293,14 +286,14 @@ describe('Test handle downs', function () { this.timeout(120000) for (let i = 0; i < 10; i++) { - const uuid = (await uploadVideoAndGetId({ server: servers[0], videoName: 'video ' + i })).uuid + const uuid = (await servers[0].videosCommand.quickUpload({ name: 'video ' + i })).uuid videoIdsServer1.push(uuid) } await waitJobs(servers) for (const id of videoIdsServer1) { - await getVideo(servers[1].url, id) + await servers[1].videosCommand.get({ id }) } await waitJobs(servers) @@ -310,7 +303,7 @@ describe('Test handle downs', function () { await wait(11000) // Refresh video -> score + 10 = 30 - await getVideo(servers[1].url, videoIdsServer1[0]) + await servers[1].videosCommand.get({ id: videoIdsServer1[0] }) await waitJobs(servers) }) @@ -325,14 +318,14 @@ describe('Test handle downs', function () { for (let i = 0; i < 5; i++) { try { - await getVideo(servers[1].url, videoIdsServer1[i]) + await servers[1].videosCommand.get({ id: videoIdsServer1[i] }) await waitJobs([ servers[1] ]) await wait(1500) } catch {} } for (const id of videoIdsServer1) { - await getVideo(servers[1].url, id, HttpStatusCode.FORBIDDEN_403) + await servers[1].videosCommand.get({ id, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) } }) diff --git a/server/tests/api/server/jobs.ts b/server/tests/api/server/jobs.ts index 6854568d3..aa4c7587b 100644 --- a/server/tests/api/server/jobs.ts +++ b/server/tests/api/server/jobs.ts @@ -9,7 +9,6 @@ import { flushAndRunMultipleServers, ServerInfo, setAccessTokensToServers, - uploadVideo, waitJobs } from '@shared/extra-utils' @@ -32,8 +31,8 @@ describe('Test jobs', function () { it('Should create some jobs', async function () { this.timeout(120000) - await uploadVideo(servers[1].url, servers[1].accessToken, { name: 'video1' }) - await uploadVideo(servers[1].url, servers[1].accessToken, { name: 'video2' }) + await servers[1].videosCommand.upload({ attributes: { name: 'video1' } }) + await servers[1].videosCommand.upload({ attributes: { name: 'video2' } }) await waitJobs(servers) }) diff --git a/server/tests/api/server/logs.ts b/server/tests/api/server/logs.ts index 096d63e21..e7bef5a4a 100644 --- a/server/tests/api/server/logs.ts +++ b/server/tests/api/server/logs.ts @@ -10,7 +10,6 @@ import { reRunServer, ServerInfo, setAccessTokensToServers, - uploadVideo, waitJobs } from '@shared/extra-utils' @@ -34,12 +33,12 @@ describe('Test logs', function () { it('Should get logs with a start date', async function () { this.timeout(20000) - await uploadVideo(server.url, server.accessToken, { name: 'video 1' }) + await server.videosCommand.upload({ attributes: { name: 'video 1' } }) await waitJobs([ server ]) const now = new Date() - await uploadVideo(server.url, server.accessToken, { name: 'video 2' }) + await server.videosCommand.upload({ attributes: { name: 'video 2' } }) await waitJobs([ server ]) const body = await logsCommand.getLogs({ startDate: now }) @@ -52,17 +51,17 @@ describe('Test logs', function () { it('Should get logs with an end date', async function () { this.timeout(30000) - await uploadVideo(server.url, server.accessToken, { name: 'video 3' }) + await server.videosCommand.upload({ attributes: { name: 'video 3' } }) await waitJobs([ server ]) const now1 = new Date() - await uploadVideo(server.url, server.accessToken, { name: 'video 4' }) + await server.videosCommand.upload({ attributes: { name: 'video 4' } }) await waitJobs([ server ]) const now2 = new Date() - await uploadVideo(server.url, server.accessToken, { name: 'video 5' }) + await server.videosCommand.upload({ attributes: { name: 'video 5' } }) await waitJobs([ server ]) const body = await logsCommand.getLogs({ startDate: now1, endDate: now2 }) @@ -78,7 +77,7 @@ describe('Test logs', function () { const now = new Date() - await uploadVideo(server.url, server.accessToken, { name: 'video 6' }) + await server.videosCommand.upload({ attributes: { name: 'video 6' } }) await waitJobs([ server ]) { @@ -131,12 +130,12 @@ describe('Test logs', function () { it('Should get logs with a start date', async function () { this.timeout(20000) - await uploadVideo(server.url, server.accessToken, { name: 'video 7' }) + await server.videosCommand.upload({ attributes: { name: 'video 7' } }) await waitJobs([ server ]) const now = new Date() - await uploadVideo(server.url, server.accessToken, { name: 'video 8' }) + await server.videosCommand.upload({ attributes: { name: 'video 8' } }) await waitJobs([ server ]) const body = await logsCommand.getAuditLogs({ startDate: now }) @@ -157,17 +156,17 @@ describe('Test logs', function () { it('Should get logs with an end date', async function () { this.timeout(30000) - await uploadVideo(server.url, server.accessToken, { name: 'video 9' }) + await server.videosCommand.upload({ attributes: { name: 'video 9' } }) await waitJobs([ server ]) const now1 = new Date() - await uploadVideo(server.url, server.accessToken, { name: 'video 10' }) + await server.videosCommand.upload({ attributes: { name: 'video 10' } }) await waitJobs([ server ]) const now2 = new Date() - await uploadVideo(server.url, server.accessToken, { name: 'video 11' }) + await server.videosCommand.upload({ attributes: { name: 'video 11' } }) await waitJobs([ server ]) const body = await logsCommand.getAuditLogs({ startDate: now1, endDate: now2 }) diff --git a/server/tests/api/server/reverse-proxy.ts b/server/tests/api/server/reverse-proxy.ts index b8bae161a..5a6491430 100644 --- a/server/tests/api/server/reverse-proxy.ts +++ b/server/tests/api/server/reverse-proxy.ts @@ -2,20 +2,11 @@ import { expect } from 'chai' import { HttpStatusCode } from '@shared/core-utils' -import { - cleanupTests, - flushAndRunServer, - getVideo, - ServerInfo, - setAccessTokensToServers, - uploadVideo, - viewVideo, - wait -} from '@shared/extra-utils' +import { cleanupTests, flushAndRunServer, ServerInfo, setAccessTokensToServers, wait } from '@shared/extra-utils' describe('Test application behind a reverse proxy', function () { let server: ServerInfo - let videoId: number + let videoId: string before(async function () { this.timeout(30000) @@ -42,60 +33,60 @@ describe('Test application behind a reverse proxy', function () { server = await flushAndRunServer(1, config) await setAccessTokensToServers([ server ]) - const { body } = await uploadVideo(server.url, server.accessToken, {}) - videoId = body.video.uuid + const { uuid } = await server.videosCommand.upload() + videoId = uuid }) it('Should view a video only once with the same IP by default', async function () { this.timeout(20000) - await viewVideo(server.url, videoId) - await viewVideo(server.url, videoId) + await server.videosCommand.view({ id: videoId }) + await server.videosCommand.view({ id: videoId }) // Wait the repeatable job await wait(8000) - const { body } = await getVideo(server.url, videoId) - expect(body.views).to.equal(1) + const video = await server.videosCommand.get({ id: videoId }) + expect(video.views).to.equal(1) }) it('Should view a video 2 times with the X-Forwarded-For header set', async function () { this.timeout(20000) - await viewVideo(server.url, videoId, HttpStatusCode.NO_CONTENT_204, '0.0.0.1,127.0.0.1') - await viewVideo(server.url, videoId, HttpStatusCode.NO_CONTENT_204, '0.0.0.2,127.0.0.1') + await server.videosCommand.view({ id: videoId, xForwardedFor: '0.0.0.1,127.0.0.1' }) + await server.videosCommand.view({ id: videoId, xForwardedFor: '0.0.0.2,127.0.0.1' }) // Wait the repeatable job await wait(8000) - const { body } = await getVideo(server.url, videoId) - expect(body.views).to.equal(3) + const video = await server.videosCommand.get({ id: videoId }) + expect(video.views).to.equal(3) }) it('Should view a video only once with the same client IP in the X-Forwarded-For header', async function () { this.timeout(20000) - await viewVideo(server.url, videoId, HttpStatusCode.NO_CONTENT_204, '0.0.0.4,0.0.0.3,::ffff:127.0.0.1') - await viewVideo(server.url, videoId, HttpStatusCode.NO_CONTENT_204, '0.0.0.5,0.0.0.3,127.0.0.1') + await server.videosCommand.view({ id: videoId, xForwardedFor: '0.0.0.4,0.0.0.3,::ffff:127.0.0.1' }) + await server.videosCommand.view({ id: videoId, xForwardedFor: '0.0.0.5,0.0.0.3,127.0.0.1' }) // Wait the repeatable job await wait(8000) - const { body } = await getVideo(server.url, videoId) - expect(body.views).to.equal(4) + const video = await server.videosCommand.get({ id: videoId }) + expect(video.views).to.equal(4) }) it('Should view a video two times with a different client IP in the X-Forwarded-For header', async function () { this.timeout(20000) - await viewVideo(server.url, videoId, HttpStatusCode.NO_CONTENT_204, '0.0.0.8,0.0.0.6,127.0.0.1') - await viewVideo(server.url, videoId, HttpStatusCode.NO_CONTENT_204, '0.0.0.8,0.0.0.7,127.0.0.1') + await server.videosCommand.view({ id: videoId, xForwardedFor: '0.0.0.8,0.0.0.6,127.0.0.1' }) + await server.videosCommand.view({ id: videoId, xForwardedFor: '0.0.0.8,0.0.0.7,127.0.0.1' }) // Wait the repeatable job await wait(8000) - const { body } = await getVideo(server.url, videoId) - expect(body.views).to.equal(6) + const video = await server.videosCommand.get({ id: videoId }) + expect(video.views).to.equal(6) }) it('Should rate limit logins', async function () { @@ -140,13 +131,13 @@ describe('Test application behind a reverse proxy', function () { for (let i = 0; i < 100; i++) { try { - await getVideo(server.url, videoId) + await server.videosCommand.get({ id: videoId }) } catch { // don't care if it fails } } - await getVideo(server.url, videoId, HttpStatusCode.TOO_MANY_REQUESTS_429) + await server.videosCommand.get({ id: videoId, expectedStatus: HttpStatusCode.TOO_MANY_REQUESTS_429 }) }) after(async function () { diff --git a/server/tests/api/server/services.ts b/server/tests/api/server/services.ts index 77b95de10..a62fb3939 100644 --- a/server/tests/api/server/services.ts +++ b/server/tests/api/server/services.ts @@ -2,15 +2,8 @@ import 'mocha' import * as chai from 'chai' +import { cleanupTests, flushAndRunServer, ServerInfo, setAccessTokensToServers, setDefaultVideoChannel } from '@shared/extra-utils' import { Video, VideoPlaylistPrivacy } from '@shared/models' -import { - getVideosList, - ServerInfo, - setAccessTokensToServers, - setDefaultVideoChannel, - uploadVideo -} from '../../../../shared/extra-utils' -import { cleanupTests, flushAndRunServer } from '../../../../shared/extra-utils/server/servers' const expect = chai.expect @@ -29,13 +22,11 @@ describe('Test services', function () { await setDefaultVideoChannel([ server ]) { - const videoAttributes = { - name: 'my super name' - } - await uploadVideo(server.url, server.accessToken, videoAttributes) + const attributes = { name: 'my super name' } + await server.videosCommand.upload({ attributes }) - const res = await getVideosList(server.url) - video = res.body.data[0] + const { data } = await server.videosCommand.list() + video = data[0] } { diff --git a/server/tests/api/server/stats.ts b/server/tests/api/server/stats.ts index a35709c26..3eb1efb94 100644 --- a/server/tests/api/server/stats.ts +++ b/server/tests/api/server/stats.ts @@ -8,8 +8,6 @@ import { flushAndRunMultipleServers, ServerInfo, setAccessTokensToServers, - uploadVideo, - viewVideo, wait, waitJobs } from '@shared/extra-utils' @@ -36,12 +34,11 @@ describe('Test stats (excluding redundancy)', function () { await servers[0].usersCommand.create({ username: user.username, password: user.password }) - const resVideo = await uploadVideo(servers[0].url, servers[0].accessToken, { fixture: 'video_short.webm' }) - const videoUUID = resVideo.body.video.uuid + const { uuid } = await servers[0].videosCommand.upload({ attributes: { fixture: 'video_short.webm' } }) - await servers[0].commentsCommand.createThread({ videoId: videoUUID, text: 'comment' }) + await servers[0].commentsCommand.createThread({ videoId: uuid, text: 'comment' }) - await viewVideo(servers[0].url, videoUUID) + await servers[0].videosCommand.view({ id: uuid }) // Wait the video views repeatable job await wait(8000) @@ -154,7 +151,7 @@ describe('Test stats (excluding redundancy)', function () { } { - await uploadVideo(server.url, server.accessToken, { fixture: 'video_short.webm', channelId }) + await server.videosCommand.upload({ attributes: { fixture: 'video_short.webm', channelId } }) const data = await server.statsCommand.get() @@ -213,7 +210,7 @@ describe('Test stats (excluding redundancy)', function () { } }) - await uploadVideo(servers[0].url, servers[0].accessToken, { name: 'video', fixture: 'video_short.webm' }) + await servers[0].videosCommand.upload({ attributes: { name: 'video', fixture: 'video_short.webm' } }) await waitJobs(servers) @@ -243,7 +240,7 @@ describe('Test stats (excluding redundancy)', function () { const first = await servers[1].statsCommand.get() for (let i = 0; i < 10; i++) { - await uploadVideo(servers[0].url, servers[0].accessToken, { name: 'video' }) + await servers[0].videosCommand.upload({ attributes: { name: 'video' } }) } await waitJobs(servers) diff --git a/server/tests/api/server/tracker.ts b/server/tests/api/server/tracker.ts index 868dc8977..032012edf 100644 --- a/server/tests/api/server/tracker.ts +++ b/server/tests/api/server/tracker.ts @@ -1,19 +1,9 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await,@typescript-eslint/no-floating-promises */ -import * as magnetUtil from 'magnet-uri' import 'mocha' -import { - cleanupTests, - flushAndRunServer, - getVideo, - killallServers, - reRunServer, - ServerInfo, - uploadVideo -} from '../../../../shared/extra-utils' -import { setAccessTokensToServers } from '../../../../shared/extra-utils/index' -import { VideoDetails } from '../../../../shared/models/videos' +import * as magnetUtil from 'magnet-uri' import * as WebTorrent from 'webtorrent' +import { cleanupTests, flushAndRunServer, killallServers, reRunServer, ServerInfo, setAccessTokensToServers } from '@shared/extra-utils' describe('Test tracker', function () { let server: ServerInfo @@ -26,11 +16,8 @@ describe('Test tracker', function () { await setAccessTokensToServers([ server ]) { - const res = await uploadVideo(server.url, server.accessToken, {}) - const videoUUID = res.body.video.uuid - - const resGet = await getVideo(server.url, videoUUID) - const video: VideoDetails = resGet.body + const { uuid } = await server.videosCommand.upload() + const video = await server.videosCommand.get({ id: uuid }) goodMagnet = video.files[0].magnetUri const parsed = magnetUtil.decode(goodMagnet) diff --git a/server/tests/api/users/user-subscriptions.ts b/server/tests/api/users/user-subscriptions.ts index c09a85a32..622cddb7d 100644 --- a/server/tests/api/users/user-subscriptions.ts +++ b/server/tests/api/users/user-subscriptions.ts @@ -6,12 +6,9 @@ import { cleanupTests, doubleFollow, flushAndRunMultipleServers, - getVideosList, ServerInfo, setAccessTokensToServers, SubscriptionsCommand, - updateVideo, - uploadVideo, waitJobs } from '@shared/extra-utils' @@ -44,10 +41,10 @@ describe('Test users subscriptions', function () { users.push({ accessToken }) const videoName1 = 'video 1-' + server.serverNumber - await uploadVideo(server.url, accessToken, { name: videoName1 }) + await server.videosCommand.upload({ token: accessToken, attributes: { name: videoName1 } }) const videoName2 = 'video 2-' + server.serverNumber - await uploadVideo(server.url, accessToken, { name: videoName2 }) + await server.videosCommand.upload({ token: accessToken, attributes: { name: videoName2 } }) } } @@ -57,9 +54,9 @@ describe('Test users subscriptions', function () { }) it('Should display videos of server 2 on server 1', async function () { - const res = await getVideosList(servers[0].url) + const { total } = await servers[0].videosCommand.list() - expect(res.body.total).to.equal(4) + expect(total).to.equal(4) }) it('User of server 1 should follow user of server 3 and root of server 1', async function () { @@ -70,17 +67,17 @@ describe('Test users subscriptions', function () { await waitJobs(servers) - const res = await uploadVideo(servers[2].url, users[2].accessToken, { name: 'video server 3 added after follow' }) - video3UUID = res.body.video.uuid + const { uuid } = await servers[2].videosCommand.upload({ attributes: { name: 'video server 3 added after follow' } }) + video3UUID = uuid await waitJobs(servers) }) it('Should not display videos of server 3 on server 1', async function () { - const res = await getVideosList(servers[0].url) + const { total, data } = await servers[0].videosCommand.list() + expect(total).to.equal(4) - expect(res.body.total).to.equal(4) - for (const video of res.body.data) { + for (const video of data) { expect(video.name).to.not.contain('1-3') expect(video.name).to.not.contain('2-3') expect(video.name).to.not.contain('video server 3 added after follow') @@ -186,7 +183,7 @@ describe('Test users subscriptions', function () { this.timeout(60000) const videoName = 'video server 1 added after follow' - await uploadVideo(servers[0].url, servers[0].accessToken, { name: videoName }) + await servers[0].videosCommand.upload({ attributes: { name: videoName } }) await waitJobs(servers) @@ -212,10 +209,10 @@ describe('Test users subscriptions', function () { } { - const res = await getVideosList(servers[0].url) + const { data, total } = await servers[0].videosCommand.list() + expect(total).to.equal(5) - expect(res.body.total).to.equal(5) - for (const video of res.body.data) { + for (const video of data) { expect(video.name).to.not.contain('1-3') expect(video.name).to.not.contain('2-3') expect(video.name).to.not.contain('video server 3 added after follow') @@ -230,13 +227,12 @@ describe('Test users subscriptions', function () { await waitJobs(servers) - const res = await getVideosList(servers[0].url) - - expect(res.body.total).to.equal(8) + const { data, total } = await servers[0].videosCommand.list() + expect(total).to.equal(8) const names = [ '1-3', '2-3', 'video server 3 added after follow' ] for (const name of names) { - const video = res.body.data.find(v => v.name.indexOf(name) === -1) + const video = data.find(v => v.name.includes(name)) expect(video).to.not.be.undefined } }) @@ -248,10 +244,10 @@ describe('Test users subscriptions', function () { await waitJobs(servers) - const res = await getVideosList(servers[0].url) + const { total, data } = await servers[0].videosCommand.list() + expect(total).to.equal(5) - expect(res.body.total).to.equal(5) - for (const video of res.body.data) { + for (const video of data) { expect(video.name).to.not.contain('1-3') expect(video.name).to.not.contain('2-3') expect(video.name).to.not.contain('video server 3 added after follow') @@ -284,7 +280,7 @@ describe('Test users subscriptions', function () { it('Should update a video of server 3 and see the updated video on server 1', async function () { this.timeout(30000) - await updateVideo(servers[2].url, users[2].accessToken, video3UUID, { name: 'video server 3 added after follow updated' }) + await servers[2].videosCommand.update({ id: video3UUID, attributes: { name: 'video server 3 added after follow updated' } }) await waitJobs(servers) @@ -329,10 +325,10 @@ describe('Test users subscriptions', function () { }) it('Should correctly display public videos on server 1', async function () { - const res = await getVideosList(servers[0].url) + const { total, data } = await servers[0].videosCommand.list() + expect(total).to.equal(5) - expect(res.body.total).to.equal(5) - for (const video of res.body.data) { + for (const video of data) { expect(video.name).to.not.contain('1-3') expect(video.name).to.not.contain('2-3') expect(video.name).to.not.contain('video server 3 added after follow updated') @@ -360,10 +356,10 @@ describe('Test users subscriptions', function () { } { - const res = await getVideosList(servers[0].url) + const { total, data } = await servers[0].videosCommand.list() + expect(total).to.equal(5) - expect(res.body.total).to.equal(5) - for (const video of res.body.data) { + for (const video of data) { expect(video.name).to.not.contain('1-3') expect(video.name).to.not.contain('2-3') expect(video.name).to.not.contain('video server 3 added after follow updated') diff --git a/server/tests/api/users/users-multiple-servers.ts b/server/tests/api/users/users-multiple-servers.ts index 43e67ee60..3ae105008 100644 --- a/server/tests/api/users/users-multiple-servers.ts +++ b/server/tests/api/users/users-multiple-servers.ts @@ -9,11 +9,9 @@ import { cleanupTests, doubleFollow, flushAndRunMultipleServers, - getAccountVideos, ServerInfo, setAccessTokensToServers, testImage, - uploadVideo, waitJobs } from '@shared/extra-utils' import { User } from '@shared/models' @@ -44,7 +42,7 @@ describe('Test users with multiple servers', function () { await doubleFollow(servers[1], servers[2]) // The root user of server 1 is propagated to servers 2 and 3 - await uploadVideo(servers[0].url, servers[0].accessToken, {}) + await servers[0].videosCommand.upload() { const user = { @@ -57,8 +55,8 @@ describe('Test users with multiple servers', function () { } { - const resVideo = await uploadVideo(servers[0].url, userAccessToken, {}) - videoUUID = resVideo.body.video.uuid + const { uuid } = await servers[0].videosCommand.upload({ token: userAccessToken }) + videoUUID = uuid } await waitJobs(servers) @@ -133,31 +131,29 @@ describe('Test users with multiple servers', function () { it('Should list account videos', async function () { for (const server of servers) { - const res = await getAccountVideos(server.url, server.accessToken, 'user1@localhost:' + servers[0].port, 0, 5) + const { total, data } = await server.videosCommand.listByAccount({ accountName: 'user1@localhost:' + servers[0].port }) - expect(res.body.total).to.equal(1) - expect(res.body.data).to.be.an('array') - expect(res.body.data).to.have.lengthOf(1) - expect(res.body.data[0].uuid).to.equal(videoUUID) + expect(total).to.equal(1) + expect(data).to.be.an('array') + expect(data).to.have.lengthOf(1) + expect(data[0].uuid).to.equal(videoUUID) } }) it('Should search through account videos', async function () { this.timeout(10_000) - const resVideo = await uploadVideo(servers[0].url, userAccessToken, { name: 'Kami no chikara' }) + const created = await servers[0].videosCommand.upload({ token: userAccessToken, attributes: { name: 'Kami no chikara' } }) await waitJobs(servers) for (const server of servers) { - const res = await getAccountVideos(server.url, server.accessToken, 'user1@localhost:' + servers[0].port, 0, 5, undefined, { - search: 'Kami' - }) - - expect(res.body.total).to.equal(1) - expect(res.body.data).to.be.an('array') - expect(res.body.data).to.have.lengthOf(1) - expect(res.body.data[0].uuid).to.equal(resVideo.body.video.uuid) + const { total, data } = await server.videosCommand.listByAccount({ accountName: 'user1@localhost:' + servers[0].port, search: 'Kami' }) + + expect(total).to.equal(1) + expect(data).to.be.an('array') + expect(data).to.have.lengthOf(1) + expect(data[0].uuid).to.equal(created.uuid) } }) diff --git a/server/tests/api/users/users.ts b/server/tests/api/users/users.ts index 30d7e850d..6f3873939 100644 --- a/server/tests/api/users/users.ts +++ b/server/tests/api/users/users.ts @@ -6,17 +6,12 @@ import { HttpStatusCode } from '@shared/core-utils' import { cleanupTests, flushAndRunServer, - getMyVideos, - getVideosList, killallServers, makePutBodyRequest, - rateVideo, - removeVideo, reRunServer, ServerInfo, setAccessTokensToServers, testImage, - uploadVideo, waitJobs } from '@shared/extra-utils' import { AbuseState, OAuth2ErrorCode, UserAdminFlag, UserRole, Video, VideoPlaylistType } from '@shared/models' @@ -25,8 +20,8 @@ const expect = chai.expect describe('Test users', function () { let server: ServerInfo - let accessToken: string - let accessTokenUser: string + let token: string + let userToken: string let videoId: number let userId: number const user = { @@ -101,18 +96,17 @@ describe('Test users', function () { }) it('Should not be able to upload a video', async function () { - accessToken = 'my_super_token' + token = 'my_super_token' - const videoAttributes = {} - await uploadVideo(server.url, accessToken, videoAttributes, HttpStatusCode.UNAUTHORIZED_401) + await server.videosCommand.upload({ token, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should not be able to follow', async function () { - accessToken = 'my_super_token' + token = 'my_super_token' await server.followsCommand.follow({ targets: [ 'http://example.com' ], - token: accessToken, + token, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -122,7 +116,7 @@ describe('Test users', function () { it('Should be able to login', async function () { const body = await server.loginCommand.login({ expectedStatus: HttpStatusCode.OK_200 }) - accessToken = body.access_token + token = body.access_token }) it('Should be able to login with an insensitive username', async function () { @@ -140,33 +134,31 @@ describe('Test users', function () { describe('Upload', function () { it('Should upload the video with the correct token', async function () { - const videoAttributes = {} - await uploadVideo(server.url, accessToken, videoAttributes) - const res = await getVideosList(server.url) - const video = res.body.data[0] + await server.videosCommand.upload({ token }) + const { data } = await server.videosCommand.list() + const video = data[0] expect(video.account.name).to.equal('root') videoId = video.id }) it('Should upload the video again with the correct token', async function () { - const videoAttributes = {} - await uploadVideo(server.url, accessToken, videoAttributes) + await server.videosCommand.upload({ token }) }) }) describe('Ratings', function () { it('Should retrieve a video rating', async function () { - await rateVideo(server.url, accessToken, videoId, 'like') - const rating = await server.usersCommand.getMyRating({ token: accessToken, videoId }) + await server.videosCommand.rate({ id: videoId, rating: 'like' }) + const rating = await server.usersCommand.getMyRating({ token, videoId }) expect(rating.videoId).to.equal(videoId) expect(rating.rating).to.equal('like') }) it('Should retrieve ratings list', async function () { - await rateVideo(server.url, accessToken, videoId, 'like') + await server.videosCommand.rate({ id: videoId, rating: 'like' }) const body = await server.accountsCommand.listRatings({ accountName: server.user.username }) @@ -190,13 +182,13 @@ describe('Test users', function () { describe('Remove video', function () { it('Should not be able to remove the video with an incorrect token', async function () { - await removeVideo(server.url, 'bad_token', videoId, HttpStatusCode.UNAUTHORIZED_401) + await server.videosCommand.remove({ token: 'bad_token', id: videoId, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should not be able to remove the video with the token of another account') it('Should be able to remove the video with the correct token', async function () { - await removeVideo(server.url, accessToken, videoId) + await server.videosCommand.remove({ token, id: videoId }) }) }) @@ -210,7 +202,7 @@ describe('Test users', function () { }) it('Should not be able to upload a video', async function () { - await uploadVideo(server.url, server.accessToken, { name: 'video' }, HttpStatusCode.UNAUTHORIZED_401) + await server.videosCommand.upload({ attributes: { name: 'video' }, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should not be able to rate a video', async function () { @@ -281,11 +273,11 @@ describe('Test users', function () { }) it('Should be able to login with this user', async function () { - accessTokenUser = await server.loginCommand.getAccessToken(user) + userToken = await server.loginCommand.getAccessToken(user) }) it('Should be able to get user information', async function () { - const userMe = await server.usersCommand.getMyInfo({ token: accessTokenUser }) + const userMe = await server.usersCommand.getMyInfo({ token: userToken }) const userGet = await server.usersCommand.get({ userId: userMe.id, withStats: true }) @@ -323,15 +315,15 @@ describe('Test users', function () { it('Should be able to upload a video with this user', async function () { this.timeout(10000) - const videoAttributes = { + const attributes = { name: 'super user video', fixture: 'video_short.webm' } - await uploadVideo(server.url, accessTokenUser, videoAttributes) + await server.videosCommand.upload({ token: userToken, attributes }) }) it('Should have video quota updated', async function () { - const quota = await server.usersCommand.getMyQuotaUsed({ token: accessTokenUser }) + const quota = await server.usersCommand.getMyQuotaUsed({ token: userToken }) expect(quota.videoQuotaUsed).to.equal(218910) const { data } = await server.usersCommand.list() @@ -340,13 +332,11 @@ describe('Test users', function () { }) it('Should be able to list my videos', async function () { - const res = await getMyVideos(server.url, accessTokenUser, 0, 5) - expect(res.body.total).to.equal(1) - - const videos = res.body.data - expect(videos).to.have.lengthOf(1) + const { total, data } = await server.videosCommand.listMyVideos({ token: userToken }) + expect(total).to.equal(1) + expect(data).to.have.lengthOf(1) - const video: Video = videos[0] + const video: Video = data[0] expect(video.name).to.equal('super user video') expect(video.thumbnailPath).to.not.be.null expect(video.previewPath).to.not.be.null @@ -354,19 +344,15 @@ describe('Test users', function () { it('Should be able to search in my videos', async function () { { - const res = await getMyVideos(server.url, accessTokenUser, 0, 5, '-createdAt', 'user video') - expect(res.body.total).to.equal(1) - - const videos = res.body.data - expect(videos).to.have.lengthOf(1) + const { total, data } = await server.videosCommand.listMyVideos({ token: userToken, sort: '-createdAt', search: 'user video' }) + expect(total).to.equal(1) + expect(data).to.have.lengthOf(1) } { - const res = await getMyVideos(server.url, accessTokenUser, 0, 5, '-createdAt', 'toto') - expect(res.body.total).to.equal(0) - - const videos = res.body.data - expect(videos).to.have.lengthOf(0) + const { total, data } = await server.videosCommand.listMyVideos({ token: userToken, sort: '-createdAt', search: 'toto' }) + expect(total).to.equal(0) + expect(data).to.have.lengthOf(0) } }) @@ -382,17 +368,17 @@ describe('Test users', function () { } { - const videoAttributes = { + const attributes = { name: 'super user video 2', fixture: 'video_short.webm' } - await uploadVideo(server.url, accessTokenUser, videoAttributes) + await server.videosCommand.upload({ token: userToken, attributes }) await waitJobs([ server ]) } { - const data = await server.usersCommand.getMyQuotaUsed({ token: accessTokenUser }) + const data = await server.usersCommand.getMyQuotaUsed({ token: userToken }) expect(data.videoQuotaUsed).to.be.greaterThan(220000) } }) @@ -505,7 +491,7 @@ describe('Test users', function () { it('Should update my password', async function () { await server.usersCommand.updateMe({ - token: accessTokenUser, + token: userToken, currentPassword: 'super password', password: 'new password' }) @@ -516,11 +502,11 @@ describe('Test users', function () { it('Should be able to change the NSFW display attribute', async function () { await server.usersCommand.updateMe({ - token: accessTokenUser, + token: userToken, nsfwPolicy: 'do_not_list' }) - const user = await server.usersCommand.getMyInfo({ token: accessTokenUser }) + const user = await server.usersCommand.getMyInfo({ token: userToken }) expect(user.username).to.equal('user_1') expect(user.email).to.equal('user_1@example.com') expect(user.nsfwPolicy).to.equal('do_not_list') @@ -532,32 +518,32 @@ describe('Test users', function () { it('Should be able to change the autoPlayVideo attribute', async function () { await server.usersCommand.updateMe({ - token: accessTokenUser, + token: userToken, autoPlayVideo: false }) - const user = await server.usersCommand.getMyInfo({ token: accessTokenUser }) + const user = await server.usersCommand.getMyInfo({ token: userToken }) expect(user.autoPlayVideo).to.be.false }) it('Should be able to change the autoPlayNextVideo attribute', async function () { await server.usersCommand.updateMe({ - token: accessTokenUser, + token: userToken, autoPlayNextVideo: true }) - const user = await server.usersCommand.getMyInfo({ token: accessTokenUser }) + const user = await server.usersCommand.getMyInfo({ token: userToken }) expect(user.autoPlayNextVideo).to.be.true }) it('Should be able to change the email attribute', async function () { await server.usersCommand.updateMe({ - token: accessTokenUser, + token: userToken, currentPassword: 'new password', email: 'updated@example.com' }) - const user = await server.usersCommand.getMyInfo({ token: accessTokenUser }) + const user = await server.usersCommand.getMyInfo({ token: userToken }) expect(user.username).to.equal('user_1') expect(user.email).to.equal('updated@example.com') expect(user.nsfwPolicy).to.equal('do_not_list') @@ -570,9 +556,9 @@ describe('Test users', function () { it('Should be able to update my avatar with a gif', async function () { const fixture = 'avatar.gif' - await server.usersCommand.updateMyAvatar({ token: accessTokenUser, fixture }) + await server.usersCommand.updateMyAvatar({ token: userToken, fixture }) - const user = await server.usersCommand.getMyInfo({ token: accessTokenUser }) + const user = await server.usersCommand.getMyInfo({ token: userToken }) await testImage(server.url, 'avatar-resized', user.account.avatar.path, '.gif') }) @@ -580,17 +566,17 @@ describe('Test users', function () { for (const extension of [ '.png', '.gif' ]) { const fixture = 'avatar' + extension - await server.usersCommand.updateMyAvatar({ token: accessTokenUser, fixture }) + await server.usersCommand.updateMyAvatar({ token: userToken, fixture }) - const user = await server.usersCommand.getMyInfo({ token: accessTokenUser }) + const user = await server.usersCommand.getMyInfo({ token: userToken }) await testImage(server.url, 'avatar-resized', user.account.avatar.path, extension) } }) it('Should be able to update my display name', async function () { - await server.usersCommand.updateMe({ token: accessTokenUser, displayName: 'new display name' }) + await server.usersCommand.updateMe({ token: userToken, displayName: 'new display name' }) - const user = await server.usersCommand.getMyInfo({ token: accessTokenUser }) + const user = await server.usersCommand.getMyInfo({ token: userToken }) expect(user.username).to.equal('user_1') expect(user.email).to.equal('updated@example.com') expect(user.nsfwPolicy).to.equal('do_not_list') @@ -601,9 +587,9 @@ describe('Test users', function () { }) it('Should be able to update my description', async function () { - await server.usersCommand.updateMe({ token: accessTokenUser, description: 'my super description updated' }) + await server.usersCommand.updateMe({ token: userToken, description: 'my super description updated' }) - const user = await server.usersCommand.getMyInfo({ token: accessTokenUser }) + const user = await server.usersCommand.getMyInfo({ token: userToken }) expect(user.username).to.equal('user_1') expect(user.email).to.equal('updated@example.com') expect(user.nsfwPolicy).to.equal('do_not_list') @@ -617,21 +603,21 @@ describe('Test users', function () { it('Should be able to update my theme', async function () { for (const theme of [ 'background-red', 'default', 'instance-default' ]) { - await server.usersCommand.updateMe({ token: accessTokenUser, theme }) + await server.usersCommand.updateMe({ token: userToken, theme }) - const user = await server.usersCommand.getMyInfo({ token: accessTokenUser }) + const user = await server.usersCommand.getMyInfo({ token: userToken }) expect(user.theme).to.equal(theme) } }) it('Should be able to update my modal preferences', async function () { await server.usersCommand.updateMe({ - token: accessTokenUser, + token: userToken, noInstanceConfigWarningModal: true, noWelcomeModal: true }) - const user = await server.usersCommand.getMyInfo({ token: accessTokenUser }) + const user = await server.usersCommand.getMyInfo({ token: userToken }) expect(user.noWelcomeModal).to.be.true expect(user.noInstanceConfigWarningModal).to.be.true }) @@ -641,7 +627,7 @@ describe('Test users', function () { it('Should be able to update another user', async function () { await server.usersCommand.update({ userId, - token: accessToken, + token, email: 'updated2@example.com', emailVerified: true, videoQuota: 42, @@ -650,7 +636,7 @@ describe('Test users', function () { pluginAuth: 'toto' }) - const user = await server.usersCommand.get({ token: accessToken, userId }) + const user = await server.usersCommand.get({ token, userId }) expect(user.username).to.equal('user_1') expect(user.email).to.equal('updated2@example.com') @@ -664,39 +650,39 @@ describe('Test users', function () { }) it('Should reset the auth plugin', async function () { - await server.usersCommand.update({ userId, token: accessToken, pluginAuth: null }) + await server.usersCommand.update({ userId, token, pluginAuth: null }) - const user = await server.usersCommand.get({ token: accessToken, userId }) + const user = await server.usersCommand.get({ token, userId }) expect(user.pluginAuth).to.be.null }) it('Should have removed the user token', async function () { - await server.usersCommand.getMyQuotaUsed({ token: accessTokenUser, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) + await server.usersCommand.getMyQuotaUsed({ token: userToken, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) - accessTokenUser = await server.loginCommand.getAccessToken(user) + userToken = await server.loginCommand.getAccessToken(user) }) it('Should be able to update another user password', async function () { - await server.usersCommand.update({ userId, token: accessToken, password: 'password updated' }) + await server.usersCommand.update({ userId, token, password: 'password updated' }) - await server.usersCommand.getMyQuotaUsed({ token: accessTokenUser, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) + await server.usersCommand.getMyQuotaUsed({ token: userToken, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) await server.loginCommand.login({ user, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) user.password = 'password updated' - accessTokenUser = await server.loginCommand.getAccessToken(user) + userToken = await server.loginCommand.getAccessToken(user) }) }) describe('Video blacklists', function () { it('Should be able to list video blacklist by a moderator', async function () { - await server.blacklistCommand.list({ token: accessTokenUser }) + await server.blacklistCommand.list({ token: userToken }) }) }) describe('Remove a user', function () { it('Should be able to remove this user', async function () { - await server.usersCommand.remove({ userId, token: accessToken }) + await server.usersCommand.remove({ userId, token }) }) it('Should not be able to login with this user', async function () { @@ -704,11 +690,10 @@ describe('Test users', function () { }) it('Should not have videos of this user', async function () { - const res = await getVideosList(server.url) - - expect(res.body.total).to.equal(1) + const { data, total } = await server.videosCommand.list() + expect(total).to.equal(1) - const video = res.body.data[0] + const video = data[0] expect(video.account.name).to.equal('root') }) }) @@ -832,12 +817,11 @@ describe('Test users', function () { }) it('Should report correct videos count', async function () { - const videoAttributes = { - name: 'video to test user stats' - } - await uploadVideo(server.url, user17AccessToken, videoAttributes) - const res1 = await getVideosList(server.url) - videoId = res1.body.data.find(video => video.name === videoAttributes.name).id + const attributes = { name: 'video to test user stats' } + await server.videosCommand.upload({ token: user17AccessToken, attributes }) + + const { data } = await server.videosCommand.list() + videoId = data.find(video => video.name === attributes.name).id const user = await server.usersCommand.get({ userId: user17Id, withStats: true }) expect(user.videosCount).to.equal(1) diff --git a/server/tests/api/videos/audio-only.ts b/server/tests/api/videos/audio-only.ts index 9b516af81..e31905b36 100644 --- a/server/tests/api/videos/audio-only.ts +++ b/server/tests/api/videos/audio-only.ts @@ -4,17 +4,7 @@ import 'mocha' import * as chai from 'chai' import { join } from 'path' import { getAudioStream, getVideoStreamSize } from '@server/helpers/ffprobe-utils' -import { - cleanupTests, - doubleFollow, - flushAndRunMultipleServers, - getVideo, - ServerInfo, - setAccessTokensToServers, - uploadVideo, - waitJobs -} from '../../../../shared/extra-utils' -import { VideoDetails } from '../../../../shared/models/videos' +import { cleanupTests, doubleFollow, flushAndRunMultipleServers, ServerInfo, setAccessTokensToServers, waitJobs } from '@shared/extra-utils' const expect = chai.expect @@ -58,15 +48,13 @@ describe('Test audio only video transcoding', function () { it('Should upload a video and transcode it', async function () { this.timeout(120000) - const resUpload = await uploadVideo(servers[0].url, servers[0].accessToken, { name: 'audio only' }) - videoUUID = resUpload.body.video.uuid + const { uuid } = await servers[0].videosCommand.upload({ attributes: { name: 'audio only' } }) + videoUUID = uuid await waitJobs(servers) for (const server of servers) { - const res = await getVideo(server.url, videoUUID) - const video: VideoDetails = res.body - + const video = await server.videosCommand.get({ id: videoUUID }) expect(video.streamingPlaylists).to.have.lengthOf(1) for (const files of [ video.files, video.streamingPlaylists[0].files ]) { diff --git a/server/tests/api/videos/multiple-servers.ts b/server/tests/api/videos/multiple-servers.ts index 169bb2e23..5c13ac629 100644 --- a/server/tests/api/videos/multiple-servers.ts +++ b/server/tests/api/videos/multiple-servers.ts @@ -13,17 +13,9 @@ import { dateIsValid, doubleFollow, flushAndRunMultipleServers, - getLocalVideos, - getVideo, - getVideosList, - rateVideo, - removeVideo, ServerInfo, setAccessTokensToServers, testImage, - updateVideo, - uploadVideo, - viewVideo, wait, waitJobs, webtorrentAdd @@ -67,10 +59,9 @@ describe('Test multiple servers', function () { it('Should not have videos for all servers', async function () { for (const server of servers) { - const res = await getVideosList(server.url) - const videos = res.body.data - expect(videos).to.be.an('array') - expect(videos.length).to.equal(0) + const { data } = await server.videosCommand.list() + expect(data).to.be.an('array') + expect(data.length).to.equal(0) } }) @@ -78,7 +69,7 @@ describe('Test multiple servers', function () { it('Should upload the video on server 1 and propagate on each server', async function () { this.timeout(25000) - const videoAttributes = { + const attributes = { name: 'my super name for server 1', category: 5, licence: 4, @@ -91,7 +82,7 @@ describe('Test multiple servers', function () { channelId: videoChannelId, fixture: 'video_short1.webm' } - await uploadVideo(servers[0].url, servers[0].accessToken, videoAttributes) + await servers[0].videosCommand.upload({ attributes }) await waitJobs(servers) @@ -134,14 +125,13 @@ describe('Test multiple servers', function () { ] } - const res = await getVideosList(server.url) - const videos = res.body.data - expect(videos).to.be.an('array') - expect(videos.length).to.equal(1) - const video = videos[0] + const { data } = await server.videosCommand.list() + expect(data).to.be.an('array') + expect(data.length).to.equal(1) + const video = data[0] - await completeVideoCheck(server.url, video, checkAttributes) - publishedAt = video.publishedAt + await completeVideoCheck(server, video, checkAttributes) + publishedAt = video.publishedAt as string } }) @@ -155,7 +145,7 @@ describe('Test multiple servers', function () { await servers[1].usersCommand.create({ username: user.username, password: user.password }) const userAccessToken = await servers[1].loginCommand.getAccessToken(user) - const videoAttributes = { + const attributes = { name: 'my super name for server 2', category: 4, licence: 3, @@ -168,7 +158,7 @@ describe('Test multiple servers', function () { thumbnailfile: 'thumbnail.jpg', previewfile: 'preview.jpg' } - await uploadVideo(servers[1].url, userAccessToken, videoAttributes, HttpStatusCode.OK_200, 'resumable') + await servers[1].videosCommand.upload({ token: userAccessToken, attributes, mode: 'resumable' }) // Transcoding await waitJobs(servers) @@ -223,65 +213,67 @@ describe('Test multiple servers', function () { previewfile: 'preview' } - const res = await getVideosList(server.url) - const videos = res.body.data - expect(videos).to.be.an('array') - expect(videos.length).to.equal(2) - const video = videos[1] + const { data } = await server.videosCommand.list() + expect(data).to.be.an('array') + expect(data.length).to.equal(2) + const video = data[1] - await completeVideoCheck(server.url, video, checkAttributes) + await completeVideoCheck(server, video, checkAttributes) } }) it('Should upload two videos on server 3 and propagate on each server', async function () { this.timeout(45000) - const videoAttributes1 = { - name: 'my super name for server 3', - category: 6, - licence: 5, - language: 'de', - nsfw: true, - description: 'my super description for server 3', - support: 'my super support text for server 3', - tags: [ 'tag1p3' ], - fixture: 'video_short3.webm' + { + const attributes = { + name: 'my super name for server 3', + category: 6, + licence: 5, + language: 'de', + nsfw: true, + description: 'my super description for server 3', + support: 'my super support text for server 3', + tags: [ 'tag1p3' ], + fixture: 'video_short3.webm' + } + await servers[2].videosCommand.upload({ attributes }) } - await uploadVideo(servers[2].url, servers[2].accessToken, videoAttributes1) - - const videoAttributes2 = { - name: 'my super name for server 3-2', - category: 7, - licence: 6, - language: 'ko', - nsfw: false, - description: 'my super description for server 3-2', - support: 'my super support text for server 3-2', - tags: [ 'tag2p3', 'tag3p3', 'tag4p3' ], - fixture: 'video_short.webm' + + { + const attributes = { + name: 'my super name for server 3-2', + category: 7, + licence: 6, + language: 'ko', + nsfw: false, + description: 'my super description for server 3-2', + support: 'my super support text for server 3-2', + tags: [ 'tag2p3', 'tag3p3', 'tag4p3' ], + fixture: 'video_short.webm' + } + await servers[2].videosCommand.upload({ attributes }) } - await uploadVideo(servers[2].url, servers[2].accessToken, videoAttributes2) await waitJobs(servers) // All servers should have this video for (const server of servers) { const isLocal = server.url === 'http://localhost:' + servers[2].port - const res = await getVideosList(server.url) + const { data } = await server.videosCommand.list() - const videos = res.body.data - expect(videos).to.be.an('array') - expect(videos.length).to.equal(4) + expect(data).to.be.an('array') + expect(data.length).to.equal(4) // We not sure about the order of the two last uploads let video1 = null let video2 = null - if (videos[2].name === 'my super name for server 3') { - video1 = videos[2] - video2 = videos[3] + if (data[2].name === 'my super name for server 3') { + video1 = data[2] + video2 = data[3] } else { - video1 = videos[3] - video2 = videos[2] + video1 = data[3] + video2 = data[2] } const checkAttributesVideo1 = { @@ -316,7 +308,7 @@ describe('Test multiple servers', function () { } ] } - await completeVideoCheck(server.url, video1, checkAttributesVideo1) + await completeVideoCheck(server, video1, checkAttributesVideo1) const checkAttributesVideo2 = { name: 'my super name for server 3-2', @@ -350,38 +342,38 @@ describe('Test multiple servers', function () { } ] } - await completeVideoCheck(server.url, video2, checkAttributesVideo2) + await completeVideoCheck(server, video2, checkAttributesVideo2) } }) }) describe('It should list local videos', function () { it('Should list only local videos on server 1', async function () { - const { body } = await getLocalVideos(servers[0].url) + const { data, total } = await servers[0].videosCommand.list({ filter: 'local' }) - expect(body.total).to.equal(1) - expect(body.data).to.be.an('array') - expect(body.data.length).to.equal(1) - expect(body.data[0].name).to.equal('my super name for server 1') + expect(total).to.equal(1) + expect(data).to.be.an('array') + expect(data.length).to.equal(1) + expect(data[0].name).to.equal('my super name for server 1') }) it('Should list only local videos on server 2', async function () { - const { body } = await getLocalVideos(servers[1].url) + const { data, total } = await servers[1].videosCommand.list({ filter: 'local' }) - expect(body.total).to.equal(1) - expect(body.data).to.be.an('array') - expect(body.data.length).to.equal(1) - expect(body.data[0].name).to.equal('my super name for server 2') + expect(total).to.equal(1) + expect(data).to.be.an('array') + expect(data.length).to.equal(1) + expect(data[0].name).to.equal('my super name for server 2') }) it('Should list only local videos on server 3', async function () { - const { body } = await getLocalVideos(servers[2].url) + const { data, total } = await servers[2].videosCommand.list({ filter: 'local' }) - expect(body.total).to.equal(2) - expect(body.data).to.be.an('array') - expect(body.data.length).to.equal(2) - expect(body.data[0].name).to.equal('my super name for server 3') - expect(body.data[1].name).to.equal('my super name for server 3-2') + expect(total).to.equal(2) + expect(data).to.be.an('array') + expect(data.length).to.equal(2) + expect(data[0].name).to.equal('my super name for server 3') + expect(data[1].name).to.equal('my super name for server 3-2') }) }) @@ -389,15 +381,13 @@ describe('Test multiple servers', function () { it('Should add the file 1 by asking server 3', async function () { this.timeout(10000) - const res = await getVideosList(servers[2].url) - - const video = res.body.data[0] - toRemove.push(res.body.data[2]) - toRemove.push(res.body.data[3]) + const { data } = await servers[2].videosCommand.list() - const res2 = await getVideo(servers[2].url, video.id) - const videoDetails = res2.body + const video = data[0] + toRemove.push(data[2]) + toRemove.push(data[3]) + const videoDetails = await servers[2].videosCommand.get({ id: video.id }) const torrent = await webtorrentAdd(videoDetails.files[0].magnetUri, true) expect(torrent.files).to.be.an('array') expect(torrent.files.length).to.equal(1) @@ -407,11 +397,10 @@ describe('Test multiple servers', function () { it('Should add the file 2 by asking server 1', async function () { this.timeout(10000) - const res = await getVideosList(servers[0].url) + const { data } = await servers[0].videosCommand.list() - const video = res.body.data[1] - const res2 = await getVideo(servers[0].url, video.id) - const videoDetails = res2.body + const video = data[1] + const videoDetails = await servers[0].videosCommand.get({ id: video.id }) const torrent = await webtorrentAdd(videoDetails.files[0].magnetUri, true) expect(torrent.files).to.be.an('array') @@ -422,11 +411,10 @@ describe('Test multiple servers', function () { it('Should add the file 3 by asking server 2', async function () { this.timeout(10000) - const res = await getVideosList(servers[1].url) + const { data } = await servers[1].videosCommand.list() - const video = res.body.data[2] - const res2 = await getVideo(servers[1].url, video.id) - const videoDetails = res2.body + const video = data[2] + const videoDetails = await servers[1].videosCommand.get({ id: video.id }) const torrent = await webtorrentAdd(videoDetails.files[0].magnetUri, true) expect(torrent.files).to.be.an('array') @@ -437,11 +425,10 @@ describe('Test multiple servers', function () { it('Should add the file 3-2 by asking server 1', async function () { this.timeout(10000) - const res = await getVideosList(servers[0].url) + const { data } = await servers[0].videosCommand.list() - const video = res.body.data[3] - const res2 = await getVideo(servers[0].url, video.id) - const videoDetails = res2.body + const video = data[3] + const videoDetails = await servers[0].videosCommand.get({ id: video.id }) const torrent = await webtorrentAdd(videoDetails.files[0].magnetUri) expect(torrent.files).to.be.an('array') @@ -452,11 +439,10 @@ describe('Test multiple servers', function () { it('Should add the file 2 in 360p by asking server 1', async function () { this.timeout(10000) - const res = await getVideosList(servers[0].url) + const { data } = await servers[0].videosCommand.list() - const video = res.body.data.find(v => v.name === 'my super name for server 2') - const res2 = await getVideo(servers[0].url, video.id) - const videoDetails = res2.body + const video = data.find(v => v.name === 'my super name for server 2') + const videoDetails = await servers[0].videosCommand.get({ id: video.id }) const file = videoDetails.files.find(f => f.resolution.id === 360) expect(file).not.to.be.undefined @@ -475,30 +461,36 @@ describe('Test multiple servers', function () { let remoteVideosServer3 = [] before(async function () { - const res1 = await getVideosList(servers[0].url) - remoteVideosServer1 = res1.body.data.filter(video => video.isLocal === false).map(video => video.uuid) + { + const { data } = await servers[0].videosCommand.list() + remoteVideosServer1 = data.filter(video => video.isLocal === false).map(video => video.uuid) + } - const res2 = await getVideosList(servers[1].url) - remoteVideosServer2 = res2.body.data.filter(video => video.isLocal === false).map(video => video.uuid) + { + const { data } = await servers[1].videosCommand.list() + remoteVideosServer2 = data.filter(video => video.isLocal === false).map(video => video.uuid) + } - const res3 = await getVideosList(servers[2].url) - localVideosServer3 = res3.body.data.filter(video => video.isLocal === true).map(video => video.uuid) - remoteVideosServer3 = res3.body.data.filter(video => video.isLocal === false).map(video => video.uuid) + { + const { data } = await servers[2].videosCommand.list() + localVideosServer3 = data.filter(video => video.isLocal === true).map(video => video.uuid) + remoteVideosServer3 = data.filter(video => video.isLocal === false).map(video => video.uuid) + } }) it('Should view multiple videos on owned servers', async function () { this.timeout(30000) - await viewVideo(servers[2].url, localVideosServer3[0]) + await servers[2].videosCommand.view({ id: localVideosServer3[0] }) await wait(1000) - await viewVideo(servers[2].url, localVideosServer3[0]) - await viewVideo(servers[2].url, localVideosServer3[1]) + await servers[2].videosCommand.view({ id: localVideosServer3[0] }) + await servers[2].videosCommand.view({ id: localVideosServer3[1] }) await wait(1000) - await viewVideo(servers[2].url, localVideosServer3[0]) - await viewVideo(servers[2].url, localVideosServer3[0]) + await servers[2].videosCommand.view({ id: localVideosServer3[0] }) + await servers[2].videosCommand.view({ id: localVideosServer3[0] }) await waitJobs(servers) @@ -508,11 +500,10 @@ describe('Test multiple servers', function () { await waitJobs(servers) for (const server of servers) { - const res = await getVideosList(server.url) + const { data } = await server.videosCommand.list() - const videos = res.body.data - const video0 = videos.find(v => v.uuid === localVideosServer3[0]) - const video1 = videos.find(v => v.uuid === localVideosServer3[1]) + const video0 = data.find(v => v.uuid === localVideosServer3[0]) + const video1 = data.find(v => v.uuid === localVideosServer3[1]) expect(video0.views).to.equal(3) expect(video1.views).to.equal(1) @@ -523,16 +514,16 @@ describe('Test multiple servers', function () { this.timeout(45000) const tasks: Promise[] = [] - tasks.push(viewVideo(servers[0].url, remoteVideosServer1[0])) - tasks.push(viewVideo(servers[1].url, remoteVideosServer2[0])) - tasks.push(viewVideo(servers[1].url, remoteVideosServer2[0])) - tasks.push(viewVideo(servers[2].url, remoteVideosServer3[0])) - tasks.push(viewVideo(servers[2].url, remoteVideosServer3[1])) - tasks.push(viewVideo(servers[2].url, remoteVideosServer3[1])) - tasks.push(viewVideo(servers[2].url, remoteVideosServer3[1])) - tasks.push(viewVideo(servers[2].url, localVideosServer3[1])) - tasks.push(viewVideo(servers[2].url, localVideosServer3[1])) - tasks.push(viewVideo(servers[2].url, localVideosServer3[1])) + tasks.push(servers[0].videosCommand.view({ id: remoteVideosServer1[0] })) + tasks.push(servers[1].videosCommand.view({ id: remoteVideosServer2[0] })) + tasks.push(servers[1].videosCommand.view({ id: remoteVideosServer2[0] })) + tasks.push(servers[2].videosCommand.view({ id: remoteVideosServer3[0] })) + tasks.push(servers[2].videosCommand.view({ id: remoteVideosServer3[1] })) + tasks.push(servers[2].videosCommand.view({ id: remoteVideosServer3[1] })) + tasks.push(servers[2].videosCommand.view({ id: remoteVideosServer3[1] })) + tasks.push(servers[2].videosCommand.view({ id: localVideosServer3[1] })) + tasks.push(servers[2].videosCommand.view({ id: localVideosServer3[1] })) + tasks.push(servers[2].videosCommand.view({ id: localVideosServer3[1] })) await Promise.all(tasks) @@ -546,18 +537,16 @@ describe('Test multiple servers', function () { let baseVideos = null for (const server of servers) { - const res = await getVideosList(server.url) - - const videos = res.body.data + const { data } = await server.videosCommand.list() // Initialize base videos for future comparisons if (baseVideos === null) { - baseVideos = videos + baseVideos = data continue } for (const baseVideo of baseVideos) { - const sameVideo = videos.find(video => video.name === baseVideo.name) + const sameVideo = data.find(video => video.name === baseVideo.name) expect(baseVideo.views).to.equal(sameVideo.views) } } @@ -566,17 +555,17 @@ describe('Test multiple servers', function () { it('Should like and dislikes videos on different services', async function () { this.timeout(50000) - await rateVideo(servers[0].url, servers[0].accessToken, remoteVideosServer1[0], 'like') + await servers[0].videosCommand.rate({ id: remoteVideosServer1[0], rating: 'like' }) await wait(500) - await rateVideo(servers[0].url, servers[0].accessToken, remoteVideosServer1[0], 'dislike') + await servers[0].videosCommand.rate({ id: remoteVideosServer1[0], rating: 'dislike' }) await wait(500) - await rateVideo(servers[0].url, servers[0].accessToken, remoteVideosServer1[0], 'like') - await rateVideo(servers[2].url, servers[2].accessToken, localVideosServer3[1], 'like') + await servers[0].videosCommand.rate({ id: remoteVideosServer1[0], rating: 'like' }) + await servers[2].videosCommand.rate({ id: localVideosServer3[1], rating: 'like' }) await wait(500) - await rateVideo(servers[2].url, servers[2].accessToken, localVideosServer3[1], 'dislike') - await rateVideo(servers[2].url, servers[2].accessToken, remoteVideosServer3[1], 'dislike') + await servers[2].videosCommand.rate({ id: localVideosServer3[1], rating: 'dislike' }) + await servers[2].videosCommand.rate({ id: remoteVideosServer3[1], rating: 'dislike' }) await wait(500) - await rateVideo(servers[2].url, servers[2].accessToken, remoteVideosServer3[0], 'like') + await servers[2].videosCommand.rate({ id: remoteVideosServer3[0], rating: 'like' }) await waitJobs(servers) await wait(5000) @@ -584,18 +573,16 @@ describe('Test multiple servers', function () { let baseVideos = null for (const server of servers) { - const res = await getVideosList(server.url) - - const videos = res.body.data + const { data } = await server.videosCommand.list() // Initialize base videos for future comparisons if (baseVideos === null) { - baseVideos = videos + baseVideos = data continue } for (const baseVideo of baseVideos) { - const sameVideo = videos.find(video => video.name === baseVideo.name) + const sameVideo = data.find(video => video.name === baseVideo.name) expect(baseVideo.likes).to.equal(sameVideo.likes) expect(baseVideo.dislikes).to.equal(sameVideo.dislikes) } @@ -621,7 +608,7 @@ describe('Test multiple servers', function () { previewfile: 'preview.jpg' } - await updateVideo(servers[2].url, servers[2].accessToken, toRemove[0].id, attributes) + await servers[2].videosCommand.update({ id: toRemove[0].id, attributes }) await waitJobs(servers) }) @@ -630,10 +617,9 @@ describe('Test multiple servers', function () { this.timeout(10000) for (const server of servers) { - const res = await getVideosList(server.url) + const { data } = await server.videosCommand.list() - const videos = res.body.data - const videoUpdated = videos.find(video => video.name === 'my super video updated') + const videoUpdated = data.find(video => video.name === 'my super video updated') expect(!!videoUpdated).to.be.true const isLocal = server.url === 'http://localhost:' + servers[2].port @@ -672,15 +658,15 @@ describe('Test multiple servers', function () { thumbnailfile: 'thumbnail', previewfile: 'preview' } - await completeVideoCheck(server.url, videoUpdated, checkAttributes) + await completeVideoCheck(server, videoUpdated, checkAttributes) } }) it('Should remove the videos 3 and 3-2 by asking server 3', async function () { this.timeout(10000) - await removeVideo(servers[2].url, servers[2].accessToken, toRemove[0].id) - await removeVideo(servers[2].url, servers[2].accessToken, toRemove[1].id) + await servers[2].videosCommand.remove({ id: toRemove[0].id }) + await servers[2].videosCommand.remove({ id: toRemove[1].id }) await waitJobs(servers) }) @@ -694,27 +680,24 @@ describe('Test multiple servers', function () { it('Should have videos 1 and 3 on each server', async function () { for (const server of servers) { - const res = await getVideosList(server.url) - - const videos = res.body.data - expect(videos).to.be.an('array') - expect(videos.length).to.equal(2) - expect(videos[0].name).not.to.equal(videos[1].name) - expect(videos[0].name).not.to.equal(toRemove[0].name) - expect(videos[1].name).not.to.equal(toRemove[0].name) - expect(videos[0].name).not.to.equal(toRemove[1].name) - expect(videos[1].name).not.to.equal(toRemove[1].name) - - videoUUID = videos.find(video => video.name === 'my super name for server 1').uuid + const { data } = await server.videosCommand.list() + + expect(data).to.be.an('array') + expect(data.length).to.equal(2) + expect(data[0].name).not.to.equal(data[1].name) + expect(data[0].name).not.to.equal(toRemove[0].name) + expect(data[1].name).not.to.equal(toRemove[0].name) + expect(data[0].name).not.to.equal(toRemove[1].name) + expect(data[1].name).not.to.equal(toRemove[1].name) + + videoUUID = data.find(video => video.name === 'my super name for server 1').uuid } }) it('Should get the same video by UUID on each server', async function () { let baseVideo = null for (const server of servers) { - const res = await getVideo(server.url, videoUUID) - - const video = res.body + const video = await server.videosCommand.get({ id: videoUUID }) if (baseVideo === null) { baseVideo = video @@ -737,8 +720,7 @@ describe('Test multiple servers', function () { it('Should get the preview from each server', async function () { for (const server of servers) { - const res = await getVideo(server.url, videoUUID) - const video = res.body + const video = await server.videosCommand.get({ id: videoUUID }) await testImage(server.url, 'video_short1-preview.webm', video.previewPath) } @@ -975,14 +957,14 @@ describe('Test multiple servers', function () { downloadEnabled: false } - await updateVideo(servers[0].url, servers[0].accessToken, videoUUID, attributes) + await servers[0].videosCommand.update({ id: videoUUID, attributes }) await waitJobs(servers) for (const server of servers) { - const res = await getVideo(server.url, videoUUID) - expect(res.body.commentsEnabled).to.be.false - expect(res.body.downloadEnabled).to.be.false + const video = await server.videosCommand.get({ id: videoUUID }) + expect(video.commentsEnabled).to.be.false + expect(video.downloadEnabled).to.be.false const text = 'my super forbidden comment' await server.commentsCommand.createThread({ videoId: videoUUID, text, expectedStatus: HttpStatusCode.CONFLICT_409 }) @@ -1010,8 +992,8 @@ describe('Test multiple servers', function () { await waitJobs(servers) for (const server of servers) { - const res = await getVideosList(server.url) - const video = res.body.data.find(v => v.name === 'minimum parameters') + const { data } = await server.videosCommand.list() + const video = data.find(v => v.name === 'minimum parameters') const isLocal = server.url === 'http://localhost:' + servers[1].port const checkAttributes = { @@ -1058,7 +1040,7 @@ describe('Test multiple servers', function () { } ] } - await completeVideoCheck(server.url, video, checkAttributes) + await completeVideoCheck(server, video, checkAttributes) } }) }) diff --git a/server/tests/api/videos/resumable-upload.ts b/server/tests/api/videos/resumable-upload.ts index 642c115d0..b7756a4a8 100644 --- a/server/tests/api/videos/resumable-upload.ts +++ b/server/tests/api/videos/resumable-upload.ts @@ -9,8 +9,6 @@ import { buildAbsoluteFixturePath, cleanupTests, flushAndRunServer, - prepareResumableUpload, - sendResumableChunks, ServerInfo, setAccessTokensToServers, setDefaultVideoChannel @@ -45,7 +43,7 @@ describe('Test resumable upload', function () { const mimetype = 'video/mp4' - const res = await prepareResumableUpload({ url: server.url, token: server.accessToken, attributes, size, mimetype }) + const res = await server.videosCommand.prepareResumableUpload({ attributes, size, mimetype }) return res.header['location'].split('?')[1] } @@ -63,15 +61,13 @@ describe('Test resumable upload', function () { const size = await buildSize(defaultFixture, options.size) const absoluteFilePath = buildAbsoluteFixturePath(defaultFixture) - return sendResumableChunks({ - url: server.url, - token: server.accessToken, + return server.videosCommand.sendResumableChunks({ pathUploadId, videoFilePath: absoluteFilePath, size, contentLength, contentRangeBuilder, - specialStatus: expectedStatus + expectedStatus }) } diff --git a/server/tests/api/videos/single-server.ts b/server/tests/api/videos/single-server.ts index af1703e02..da0b2011e 100644 --- a/server/tests/api/videos/single-server.ts +++ b/server/tests/api/videos/single-server.ts @@ -2,34 +2,17 @@ import 'mocha' import * as chai from 'chai' -import { keyBy } from 'lodash' - import { checkVideoFilesWereRemoved, cleanupTests, completeVideoCheck, flushAndRunServer, - getVideo, - getVideoCategories, - getVideoLanguages, - getVideoLicences, - getVideoPrivacies, - getVideosList, - getVideosListPagination, - getVideosListSort, - getVideosWithFilters, - rateVideo, - removeVideo, ServerInfo, setAccessTokensToServers, testImage, - updateVideo, - uploadVideo, - viewVideo, wait -} from '../../../../shared/extra-utils' -import { VideoPrivacy } from '../../../../shared/models/videos' -import { HttpStatusCode } from '@shared/core-utils' +} from '@shared/extra-utils' +import { Video, VideoPrivacy } from '@shared/models' const expect = chai.expect @@ -37,8 +20,8 @@ describe('Test a single server', function () { function runSuite (mode: 'legacy' | 'resumable') { let server: ServerInfo = null - let videoId = -1 - let videoId2 = -1 + let videoId: number | string + let videoId2: string let videoUUID = '' let videosListBase: any[] = null @@ -117,128 +100,116 @@ describe('Test a single server', function () { }) it('Should list video categories', async function () { - const res = await getVideoCategories(server.url) - - const categories = res.body + const categories = await server.videosCommand.getCategories() expect(Object.keys(categories)).to.have.length.above(10) expect(categories[11]).to.equal('News & Politics') }) it('Should list video licences', async function () { - const res = await getVideoLicences(server.url) - - const licences = res.body + const licences = await server.videosCommand.getLicences() expect(Object.keys(licences)).to.have.length.above(5) expect(licences[3]).to.equal('Attribution - No Derivatives') }) it('Should list video languages', async function () { - const res = await getVideoLanguages(server.url) - - const languages = res.body + const languages = await server.videosCommand.getLanguages() expect(Object.keys(languages)).to.have.length.above(5) expect(languages['ru']).to.equal('Russian') }) it('Should list video privacies', async function () { - const res = await getVideoPrivacies(server.url) - - const privacies = res.body + const privacies = await server.videosCommand.getPrivacies() expect(Object.keys(privacies)).to.have.length.at.least(3) expect(privacies[3]).to.equal('Private') }) it('Should not have videos', async function () { - const res = await getVideosList(server.url) + const { data, total } = await server.videosCommand.list() - expect(res.body.total).to.equal(0) - expect(res.body.data).to.be.an('array') - expect(res.body.data.length).to.equal(0) + expect(total).to.equal(0) + expect(data).to.be.an('array') + expect(data.length).to.equal(0) }) it('Should upload the video', async function () { this.timeout(10000) - const videoAttributes = { + const attributes = { name: 'my super name', category: 2, nsfw: true, licence: 6, tags: [ 'tag1', 'tag2', 'tag3' ] } - const res = await uploadVideo(server.url, server.accessToken, videoAttributes, HttpStatusCode.OK_200, mode) - expect(res.body.video).to.not.be.undefined - expect(res.body.video.id).to.equal(1) - expect(res.body.video.uuid).to.have.length.above(5) + const video = await server.videosCommand.upload({ attributes, mode }) + expect(video).to.not.be.undefined + expect(video.id).to.equal(1) + expect(video.uuid).to.have.length.above(5) - videoId = res.body.video.id - videoUUID = res.body.video.uuid + videoId = video.id + videoUUID = video.uuid }) it('Should get and seed the uploaded video', async function () { this.timeout(5000) - const res = await getVideosList(server.url) + const { data, total } = await server.videosCommand.list() - expect(res.body.total).to.equal(1) - expect(res.body.data).to.be.an('array') - expect(res.body.data.length).to.equal(1) + expect(total).to.equal(1) + expect(data).to.be.an('array') + expect(data.length).to.equal(1) - const video = res.body.data[0] - await completeVideoCheck(server.url, video, getCheckAttributes()) + const video = data[0] + await completeVideoCheck(server, video, getCheckAttributes()) }) it('Should get the video by UUID', async function () { this.timeout(5000) - const res = await getVideo(server.url, videoUUID) - - const video = res.body - await completeVideoCheck(server.url, video, getCheckAttributes()) + const video = await server.videosCommand.get({ id: videoUUID }) + await completeVideoCheck(server, video, getCheckAttributes()) }) it('Should have the views updated', async function () { this.timeout(20000) - await viewVideo(server.url, videoId) - await viewVideo(server.url, videoId) - await viewVideo(server.url, videoId) + await server.videosCommand.view({ id: videoId }) + await server.videosCommand.view({ id: videoId }) + await server.videosCommand.view({ id: videoId }) await wait(1500) - await viewVideo(server.url, videoId) - await viewVideo(server.url, videoId) + await server.videosCommand.view({ id: videoId }) + await server.videosCommand.view({ id: videoId }) await wait(1500) - await viewVideo(server.url, videoId) - await viewVideo(server.url, videoId) + await server.videosCommand.view({ id: videoId }) + await server.videosCommand.view({ id: videoId }) // Wait the repeatable job await wait(8000) - const res = await getVideo(server.url, videoId) - - const video = res.body + const video = await server.videosCommand.get({ id: videoId }) expect(video.views).to.equal(3) }) it('Should remove the video', async function () { - await removeVideo(server.url, server.accessToken, videoId) + await server.videosCommand.remove({ id: videoId }) await checkVideoFilesWereRemoved(videoUUID, server) }) it('Should not have videos', async function () { - const res = await getVideosList(server.url) + const { total, data } = await server.videosCommand.list() - expect(res.body.total).to.equal(0) - expect(res.body.data).to.be.an('array') - expect(res.body.data).to.have.lengthOf(0) + expect(total).to.equal(0) + expect(data).to.be.an('array') + expect(data).to.have.lengthOf(0) }) it('Should upload 6 videos', async function () { @@ -250,7 +221,7 @@ describe('Test a single server', function () { ]) for (const video of videos) { - const videoAttributes = { + const attributes = { name: video + ' name', description: video + ' description', category: 2, @@ -261,19 +232,20 @@ describe('Test a single server', function () { fixture: video } - await uploadVideo(server.url, server.accessToken, videoAttributes, HttpStatusCode.OK_200, mode) + await server.videosCommand.upload({ attributes, mode }) } }) it('Should have the correct durations', async function () { - const res = await getVideosList(server.url) + const { total, data } = await server.videosCommand.list() + + expect(total).to.equal(6) + expect(data).to.be.an('array') + expect(data).to.have.lengthOf(6) - expect(res.body.total).to.equal(6) - const videos = res.body.data - expect(videos).to.be.an('array') - expect(videos).to.have.lengthOf(6) + const videosByName: { [ name: string ]: Video } = {} + data.forEach(v => { videosByName[v.name] = v }) - const videosByName = keyBy<{ duration: number }>(videos, 'name') expect(videosByName['video_short.mp4 name'].duration).to.equal(5) expect(videosByName['video_short.ogv name'].duration).to.equal(5) expect(videosByName['video_short.webm name'].duration).to.equal(5) @@ -283,96 +255,87 @@ describe('Test a single server', function () { }) it('Should have the correct thumbnails', async function () { - const res = await getVideosList(server.url) + const { data } = await server.videosCommand.list() - const videos = res.body.data // For the next test - videosListBase = videos + videosListBase = data - for (const video of videos) { + for (const video of data) { const videoName = video.name.replace(' name', '') await testImage(server.url, videoName, video.thumbnailPath) } }) it('Should list only the two first videos', async function () { - const res = await getVideosListPagination(server.url, 0, 2, 'name') + const { total, data } = await server.videosCommand.list({ start: 0, count: 2, sort: 'name' }) - const videos = res.body.data - expect(res.body.total).to.equal(6) - expect(videos.length).to.equal(2) - expect(videos[0].name).to.equal(videosListBase[0].name) - expect(videos[1].name).to.equal(videosListBase[1].name) + expect(total).to.equal(6) + expect(data.length).to.equal(2) + expect(data[0].name).to.equal(videosListBase[0].name) + expect(data[1].name).to.equal(videosListBase[1].name) }) it('Should list only the next three videos', async function () { - const res = await getVideosListPagination(server.url, 2, 3, 'name') + const { total, data } = await server.videosCommand.list({ start: 2, count: 3, sort: 'name' }) - const videos = res.body.data - expect(res.body.total).to.equal(6) - expect(videos.length).to.equal(3) - expect(videos[0].name).to.equal(videosListBase[2].name) - expect(videos[1].name).to.equal(videosListBase[3].name) - expect(videos[2].name).to.equal(videosListBase[4].name) + expect(total).to.equal(6) + expect(data.length).to.equal(3) + expect(data[0].name).to.equal(videosListBase[2].name) + expect(data[1].name).to.equal(videosListBase[3].name) + expect(data[2].name).to.equal(videosListBase[4].name) }) it('Should list the last video', async function () { - const res = await getVideosListPagination(server.url, 5, 6, 'name') + const { total, data } = await server.videosCommand.list({ start: 5, count: 6, sort: 'name' }) - const videos = res.body.data - expect(res.body.total).to.equal(6) - expect(videos.length).to.equal(1) - expect(videos[0].name).to.equal(videosListBase[5].name) + expect(total).to.equal(6) + expect(data.length).to.equal(1) + expect(data[0].name).to.equal(videosListBase[5].name) }) it('Should not have the total field', async function () { - const res = await getVideosListPagination(server.url, 5, 6, 'name', true) + const { total, data } = await server.videosCommand.list({ start: 5, count: 6, sort: 'name', skipCount: true }) - const videos = res.body.data - expect(res.body.total).to.not.exist - expect(videos.length).to.equal(1) - expect(videos[0].name).to.equal(videosListBase[5].name) + expect(total).to.not.exist + expect(data.length).to.equal(1) + expect(data[0].name).to.equal(videosListBase[5].name) }) it('Should list and sort by name in descending order', async function () { - const res = await getVideosListSort(server.url, '-name') + const { total, data } = await server.videosCommand.list({ sort: '-name' }) - const videos = res.body.data - expect(res.body.total).to.equal(6) - expect(videos.length).to.equal(6) - expect(videos[0].name).to.equal('video_short.webm name') - expect(videos[1].name).to.equal('video_short.ogv name') - expect(videos[2].name).to.equal('video_short.mp4 name') - expect(videos[3].name).to.equal('video_short3.webm name') - expect(videos[4].name).to.equal('video_short2.webm name') - expect(videos[5].name).to.equal('video_short1.webm name') + expect(total).to.equal(6) + expect(data.length).to.equal(6) + expect(data[0].name).to.equal('video_short.webm name') + expect(data[1].name).to.equal('video_short.ogv name') + expect(data[2].name).to.equal('video_short.mp4 name') + expect(data[3].name).to.equal('video_short3.webm name') + expect(data[4].name).to.equal('video_short2.webm name') + expect(data[5].name).to.equal('video_short1.webm name') - videoId = videos[3].uuid - videoId2 = videos[5].uuid + videoId = data[3].uuid + videoId2 = data[5].uuid }) it('Should list and sort by trending in descending order', async function () { - const res = await getVideosListPagination(server.url, 0, 2, '-trending') + const { total, data } = await server.videosCommand.list({ start: 0, count: 2, sort: '-trending' }) - const videos = res.body.data - expect(res.body.total).to.equal(6) - expect(videos.length).to.equal(2) + expect(total).to.equal(6) + expect(data.length).to.equal(2) }) it('Should list and sort by hotness in descending order', async function () { - const res = await getVideosListPagination(server.url, 0, 2, '-hot') + const { total, data } = await server.videosCommand.list({ start: 0, count: 2, sort: '-hot' }) - const videos = res.body.data - expect(res.body.total).to.equal(6) - expect(videos.length).to.equal(2) + expect(total).to.equal(6) + expect(data.length).to.equal(2) }) it('Should list and sort by best in descending order', async function () { - const res = await getVideosListPagination(server.url, 0, 2, '-best') + const { total, data } = await server.videosCommand.list({ start: 0, count: 2, sort: '-best' }) - const videos = res.body.data - expect(res.body.total).to.equal(6) - expect(videos.length).to.equal(2) + expect(total).to.equal(6) + expect(data.length).to.equal(2) }) it('Should update a video', async function () { @@ -387,67 +350,66 @@ describe('Test a single server', function () { downloadEnabled: false, tags: [ 'tagup1', 'tagup2' ] } - await updateVideo(server.url, server.accessToken, videoId, attributes) + await server.videosCommand.update({ id: videoId, attributes }) }) it('Should filter by tags and category', async function () { - const res1 = await getVideosWithFilters(server.url, { tagsAllOf: [ 'tagup1', 'tagup2' ], categoryOneOf: [ 4 ] }) - expect(res1.body.total).to.equal(1) - expect(res1.body.data[0].name).to.equal('my super video updated') + { + const { data, total } = await server.videosCommand.list({ tagsAllOf: [ 'tagup1', 'tagup2' ], categoryOneOf: [ 4 ] }) + expect(total).to.equal(1) + expect(data[0].name).to.equal('my super video updated') + } - const res2 = await getVideosWithFilters(server.url, { tagsAllOf: [ 'tagup1', 'tagup2' ], categoryOneOf: [ 3 ] }) - expect(res2.body.total).to.equal(0) + { + const { total } = await server.videosCommand.list({ tagsAllOf: [ 'tagup1', 'tagup2' ], categoryOneOf: [ 3 ] }) + expect(total).to.equal(0) + } }) it('Should have the video updated', async function () { this.timeout(60000) - const res = await getVideo(server.url, videoId) - const video = res.body + const video = await server.videosCommand.get({ id: videoId }) - await completeVideoCheck(server.url, video, updateCheckAttributes()) + await completeVideoCheck(server, video, updateCheckAttributes()) }) it('Should update only the tags of a video', async function () { const attributes = { tags: [ 'supertag', 'tag1', 'tag2' ] } - await updateVideo(server.url, server.accessToken, videoId, attributes) + await server.videosCommand.update({ id: videoId, attributes }) - const res = await getVideo(server.url, videoId) - const video = res.body + const video = await server.videosCommand.get({ id: videoId }) - await completeVideoCheck(server.url, video, Object.assign(updateCheckAttributes(), attributes)) + await completeVideoCheck(server, video, Object.assign(updateCheckAttributes(), attributes)) }) it('Should update only the description of a video', async function () { const attributes = { description: 'hello everybody' } - await updateVideo(server.url, server.accessToken, videoId, attributes) + await server.videosCommand.update({ id: videoId, attributes }) - const res = await getVideo(server.url, videoId) - const video = res.body + const video = await server.videosCommand.get({ id: videoId }) const expectedAttributes = Object.assign(updateCheckAttributes(), { tags: [ 'supertag', 'tag1', 'tag2' ] }, attributes) - await completeVideoCheck(server.url, video, expectedAttributes) + await completeVideoCheck(server, video, expectedAttributes) }) it('Should like a video', async function () { - await rateVideo(server.url, server.accessToken, videoId, 'like') + await server.videosCommand.rate({ id: videoId, rating: 'like' }) - const res = await getVideo(server.url, videoId) - const video = res.body + const video = await server.videosCommand.get({ id: videoId }) expect(video.likes).to.equal(1) expect(video.dislikes).to.equal(0) }) it('Should dislike the same video', async function () { - await rateVideo(server.url, server.accessToken, videoId, 'dislike') + await server.videosCommand.rate({ id: videoId, rating: 'dislike' }) - const res = await getVideo(server.url, videoId) - const video = res.body + const video = await server.videosCommand.get({ id: videoId }) expect(video.likes).to.equal(0) expect(video.dislikes).to.equal(1) @@ -457,10 +419,10 @@ describe('Test a single server', function () { { const now = new Date() const attributes = { originallyPublishedAt: now.toISOString() } - await updateVideo(server.url, server.accessToken, videoId, attributes) + await server.videosCommand.update({ id: videoId, attributes }) - const res = await getVideosListSort(server.url, '-originallyPublishedAt') - const names = res.body.data.map(v => v.name) + const { data } = await server.videosCommand.list({ sort: '-originallyPublishedAt' }) + const names = data.map(v => v.name) expect(names[0]).to.equal('my super video updated') expect(names[1]).to.equal('video_short2.webm name') @@ -473,10 +435,10 @@ describe('Test a single server', function () { { const now = new Date() const attributes = { originallyPublishedAt: now.toISOString() } - await updateVideo(server.url, server.accessToken, videoId2, attributes) + await server.videosCommand.update({ id: videoId2, attributes }) - const res = await getVideosListSort(server.url, '-originallyPublishedAt') - const names = res.body.data.map(v => v.name) + const { data } = await server.videosCommand.list({ sort: '-originallyPublishedAt' }) + const names = data.map(v => v.name) expect(names[0]).to.equal('video_short1.webm name') expect(names[1]).to.equal('my super video updated') diff --git a/server/tests/api/videos/video-captions.ts b/server/tests/api/videos/video-captions.ts index d4a5385ab..4c67e96f7 100644 --- a/server/tests/api/videos/video-captions.ts +++ b/server/tests/api/videos/video-captions.ts @@ -7,11 +7,9 @@ import { cleanupTests, doubleFollow, flushAndRunMultipleServers, - removeVideo, ServerInfo, setAccessTokensToServers, testCaptionFile, - uploadVideo, wait, waitJobs } from '@shared/extra-utils' @@ -34,8 +32,8 @@ describe('Test video captions', function () { await waitJobs(servers) - const res = await uploadVideo(servers[0].url, servers[0].accessToken, { name: 'my video name' }) - videoUUID = res.body.video.uuid + const { uuid } = await servers[0].videosCommand.upload({ attributes: { name: 'my video name' } }) + videoUUID = uuid await waitJobs(servers) }) @@ -180,7 +178,7 @@ describe('Test video captions', function () { }) it('Should remove the video, and thus all video captions', async function () { - await removeVideo(servers[0].url, servers[0].accessToken, videoUUID) + await servers[0].videosCommand.remove({ id: videoUUID }) await checkVideoFilesWereRemoved(videoUUID, servers[0]) }) diff --git a/server/tests/api/videos/video-change-ownership.ts b/server/tests/api/videos/video-change-ownership.ts index b0bbd5a0d..b85edd920 100644 --- a/server/tests/api/videos/video-change-ownership.ts +++ b/server/tests/api/videos/video-change-ownership.ts @@ -2,22 +2,19 @@ import 'mocha' import * as chai from 'chai' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '@shared/core-utils' import { ChangeOwnershipCommand, cleanupTests, doubleFollow, flushAndRunMultipleServers, flushAndRunServer, - getVideo, - getVideosList, ServerInfo, setAccessTokensToServers, setDefaultVideoChannel, - uploadVideo -} from '../../../../shared/extra-utils' -import { waitJobs } from '../../../../shared/extra-utils/server/jobs' -import { VideoDetails, VideoPrivacy } from '../../../../shared/models/videos' + waitJobs +} from '@shared/extra-utils' +import { VideoPrivacy } from '@shared/models' const expect = chai.expect @@ -71,14 +68,13 @@ describe('Test video change ownership - nominal', function () { } { - const videoAttributes = { + const attributes = { name: 'my super name', description: 'my super description' } - const res = await uploadVideo(servers[0].url, firstUserToken, videoAttributes) + const { id } = await servers[0].videosCommand.upload({ token: firstUserToken, attributes }) - const resVideo = await getVideo(servers[0].url, res.body.video.id) - servers[0].video = resVideo.body + servers[0].video = await servers[0].videosCommand.get({ id }) } { @@ -212,9 +208,7 @@ describe('Test video change ownership - nominal', function () { it('Should have the channel of the video updated', async function () { for (const server of servers) { - const res = await getVideo(server.url, servers[0].video.uuid) - - const video: VideoDetails = res.body + const video = await server.videosCommand.get({ id: servers[0].video.uuid }) expect(video.name).to.equal('my super name') expect(video.channel.displayName).to.equal('Main second channel') @@ -243,9 +237,7 @@ describe('Test video change ownership - nominal', function () { await waitJobs(servers) for (const server of servers) { - const res = await getVideo(server.url, servers[0].video.uuid) - - const video: VideoDetails = res.body + const video = await server.videosCommand.get({ id: servers[0].video.uuid }) expect(video.name).to.equal('my super name') expect(video.channel.displayName).to.equal('Main second channel') @@ -280,20 +272,18 @@ describe('Test video change ownership - quota too small', function () { secondUserToken = await server.loginCommand.getAccessToken(secondUser) // Upload some videos on the server - const video1Attributes = { + const attributes = { name: 'my super name', description: 'my super description' } - await uploadVideo(server.url, firstUserToken, video1Attributes) + await server.videosCommand.upload({ token: firstUserToken, attributes }) await waitJobs(server) - const res = await getVideosList(server.url) - const videos = res.body.data - - expect(videos.length).to.equal(1) + const { data } = await server.videosCommand.list() + expect(data.length).to.equal(1) - server.video = videos.find(video => video.name === 'my super name') + server.video = data.find(video => video.name === 'my super name') }) it('Should send a request to change ownership of a video', async function () { diff --git a/server/tests/api/videos/video-channels.ts b/server/tests/api/videos/video-channels.ts index 2e57cbbff..170cc942e 100644 --- a/server/tests/api/videos/video-channels.ts +++ b/server/tests/api/videos/video-channels.ts @@ -8,20 +8,15 @@ import { cleanupTests, doubleFollow, flushAndRunMultipleServers, - getVideo, - getVideoChannelVideos, ServerInfo, setAccessTokensToServers, setDefaultVideoChannel, testFileExistsOrNot, testImage, - updateVideo, - uploadVideo, - viewVideo, wait, waitJobs } from '@shared/extra-utils' -import { User, Video, VideoChannel, VideoDetails } from '@shared/models' +import { User, VideoChannel } from '@shared/models' const expect = chai.expect @@ -77,9 +72,9 @@ describe('Test video channels', function () { // The channel is 1 is propagated to servers 2 { - const videoAttributesArg = { name: 'my video name', channelId: secondVideoChannelId, support: 'video support field' } - const res = await uploadVideo(servers[0].url, servers[0].accessToken, videoAttributesArg) - videoUUID = res.body.video.uuid + const attributes = { name: 'my video name', channelId: secondVideoChannelId, support: 'video support field' } + const { uuid } = await servers[0].videosCommand.upload({ attributes }) + videoUUID = uuid } await waitJobs(servers) @@ -219,9 +214,7 @@ describe('Test video channels', function () { it('Should not have updated the video support field', async function () { for (const server of servers) { - const res = await getVideo(server.url, videoUUID) - const video: VideoDetails = res.body - + const video = await server.videosCommand.get({ id: videoUUID }) expect(video.support).to.equal('video support field') } }) @@ -239,9 +232,7 @@ describe('Test video channels', function () { await waitJobs(servers) for (const server of servers) { - const res = await getVideo(server.url, videoUUID) - const video: VideoDetails = res.body - + const video = await server.videosCommand.get({ id: videoUUID }) expect(video.support).to.equal(videoChannelAttributes.support) } }) @@ -333,18 +324,19 @@ describe('Test video channels', function () { for (const server of servers) { const channelURI = 'second_video_channel@localhost:' + servers[0].port - const res1 = await getVideoChannelVideos(server.url, server.accessToken, channelURI, 0, 5) - expect(res1.body.total).to.equal(1) - expect(res1.body.data).to.be.an('array') - expect(res1.body.data).to.have.lengthOf(1) - expect(res1.body.data[0].name).to.equal('my video name') + const { total, data } = await server.videosCommand.listByChannel({ videoChannelName: channelURI }) + + expect(total).to.equal(1) + expect(data).to.be.an('array') + expect(data).to.have.lengthOf(1) + expect(data[0].name).to.equal('my video name') } }) it('Should change the video channel of a video', async function () { this.timeout(10000) - await updateVideo(servers[0].url, servers[0].accessToken, videoUUID, { channelId: servers[0].videoChannel.id }) + await servers[0].videosCommand.update({ id: videoUUID, attributes: { channelId: servers[0].videoChannel.id } }) await waitJobs(servers) }) @@ -353,18 +345,21 @@ describe('Test video channels', function () { this.timeout(10000) for (const server of servers) { - const secondChannelURI = 'second_video_channel@localhost:' + servers[0].port - const res1 = await getVideoChannelVideos(server.url, server.accessToken, secondChannelURI, 0, 5) - expect(res1.body.total).to.equal(0) - - const channelURI = 'root_channel@localhost:' + servers[0].port - const res2 = await getVideoChannelVideos(server.url, server.accessToken, channelURI, 0, 5) - expect(res2.body.total).to.equal(1) - - const videos: Video[] = res2.body.data - expect(videos).to.be.an('array') - expect(videos).to.have.lengthOf(1) - expect(videos[0].name).to.equal('my video name') + { + const secondChannelURI = 'second_video_channel@localhost:' + servers[0].port + const { total } = await server.videosCommand.listByChannel({ videoChannelName: secondChannelURI }) + expect(total).to.equal(0) + } + + { + const channelURI = 'root_channel@localhost:' + servers[0].port + const { total, data } = await server.videosCommand.listByChannel({ videoChannelName: channelURI }) + expect(total).to.equal(1) + + expect(data).to.be.an('array') + expect(data).to.have.lengthOf(1) + expect(data[0].name).to.equal('my video name') + } } }) @@ -417,8 +412,8 @@ describe('Test video channels', function () { { // video has been posted on channel servers[0].videoChannel.id since last update - await viewVideo(servers[0].url, videoUUID, 204, '0.0.0.1,127.0.0.1') - await viewVideo(servers[0].url, videoUUID, 204, '0.0.0.2,127.0.0.1') + await servers[0].videosCommand.view({ id: videoUUID, xForwardedFor: '0.0.0.1,127.0.0.1' }) + await servers[0].videosCommand.view({ id: videoUUID, xForwardedFor: '0.0.0.2,127.0.0.1' }) // Wait the repeatable job await wait(8000) @@ -460,7 +455,7 @@ describe('Test video channels', function () { it('Should list channels by updatedAt desc if a video has been uploaded', async function () { this.timeout(30000) - await uploadVideo(servers[0].url, servers[0].accessToken, { channelId: totoChannel }) + await servers[0].videosCommand.upload({ attributes: { channelId: totoChannel } }) await waitJobs(servers) for (const server of servers) { @@ -470,7 +465,7 @@ describe('Test video channels', function () { expect(data[1].name).to.equal('root_channel') } - await uploadVideo(servers[0].url, servers[0].accessToken, { channelId: servers[0].videoChannel.id }) + await servers[0].videosCommand.upload({ attributes: { channelId: servers[0].videoChannel.id } }) await waitJobs(servers) for (const server of servers) { diff --git a/server/tests/api/videos/video-comments.ts b/server/tests/api/videos/video-comments.ts index 266824d58..41be54c81 100644 --- a/server/tests/api/videos/video-comments.ts +++ b/server/tests/api/videos/video-comments.ts @@ -9,8 +9,7 @@ import { flushAndRunServer, ServerInfo, setAccessTokensToServers, - testImage, - uploadVideo + testImage } from '@shared/extra-utils' const expect = chai.expect @@ -33,9 +32,9 @@ describe('Test video comments', function () { await setAccessTokensToServers([ server ]) - const res = await uploadVideo(server.url, server.accessToken, {}) - videoUUID = res.body.video.uuid - videoId = res.body.video.id + const { id, uuid } = await server.videosCommand.upload() + videoUUID = uuid + videoId = id await server.usersCommand.updateMyAvatar({ fixture: 'avatar.png' }) diff --git a/server/tests/api/videos/video-description.ts b/server/tests/api/videos/video-description.ts index e1c9afe79..6ac9206f5 100644 --- a/server/tests/api/videos/video-description.ts +++ b/server/tests/api/videos/video-description.ts @@ -2,19 +2,7 @@ import 'mocha' import * as chai from 'chai' -import { - cleanupTests, - flushAndRunMultipleServers, - getVideo, - getVideoDescription, - getVideosList, - ServerInfo, - setAccessTokensToServers, - updateVideo, - uploadVideo -} from '../../../../shared/extra-utils/index' -import { doubleFollow } from '../../../../shared/extra-utils/server/follows' -import { waitJobs } from '../../../../shared/extra-utils/server/jobs' +import { cleanupTests, doubleFollow, flushAndRunMultipleServers, ServerInfo, setAccessTokensToServers, waitJobs } from '@shared/extra-utils' const expect = chai.expect @@ -43,20 +31,19 @@ describe('Test video description', function () { const attributes = { description: longDescription } - await uploadVideo(servers[0].url, servers[0].accessToken, attributes) + await servers[0].videosCommand.upload({ attributes }) await waitJobs(servers) - const res = await getVideosList(servers[0].url) + const { data } = await servers[0].videosCommand.list() - videoId = res.body.data[0].id - videoUUID = res.body.data[0].uuid + videoId = data[0].id + videoUUID = data[0].uuid }) it('Should have a truncated description on each server', async function () { for (const server of servers) { - const res = await getVideo(server.url, videoUUID) - const video = res.body + const video = await server.videosCommand.get({ id: videoUUID }) // 30 characters * 6 -> 240 characters const truncatedDescription = 'my super description for server 1'.repeat(7) + @@ -68,11 +55,10 @@ describe('Test video description', function () { it('Should fetch long description on each server', async function () { for (const server of servers) { - const res = await getVideo(server.url, videoUUID) - const video = res.body + const video = await server.videosCommand.get({ id: videoUUID }) - const res2 = await getVideoDescription(server.url, video.descriptionPath) - expect(res2.body.description).to.equal(longDescription) + const { description } = await server.videosCommand.getDescription({ descriptionPath: video.descriptionPath }) + expect(description).to.equal(longDescription) } }) @@ -82,20 +68,19 @@ describe('Test video description', function () { const attributes = { description: 'short description' } - await updateVideo(servers[0].url, servers[0].accessToken, videoId, attributes) + await servers[0].videosCommand.update({ id: videoId, attributes }) await waitJobs(servers) }) it('Should have a small description on each server', async function () { for (const server of servers) { - const res = await getVideo(server.url, videoUUID) - const video = res.body + const video = await server.videosCommand.get({ id: videoUUID }) expect(video.description).to.equal('short description') - const res2 = await getVideoDescription(server.url, video.descriptionPath) - expect(res2.body.description).to.equal('short description') + const { description } = await server.videosCommand.getDescription({ descriptionPath: video.descriptionPath }) + expect(description).to.equal('short description') } }) diff --git a/server/tests/api/videos/video-hls.ts b/server/tests/api/videos/video-hls.ts index 428e1316d..d63b81694 100644 --- a/server/tests/api/videos/video-hls.ts +++ b/server/tests/api/videos/video-hls.ts @@ -3,7 +3,7 @@ import 'mocha' import * as chai from 'chai' import { join } from 'path' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '@shared/core-utils' import { checkDirectoryIsEmpty, checkResolutionsInMasterPlaylist, @@ -12,26 +12,20 @@ import { cleanupTests, doubleFollow, flushAndRunMultipleServers, - getVideo, makeRawRequest, - removeVideo, ServerInfo, setAccessTokensToServers, - updateVideo, - uploadVideo, waitJobs, webtorrentAdd -} from '../../../../shared/extra-utils' -import { VideoDetails } from '../../../../shared/models/videos' -import { VideoStreamingPlaylistType } from '../../../../shared/models/videos/video-streaming-playlist.type' +} from '@shared/extra-utils' +import { VideoStreamingPlaylistType } from '@shared/models' import { DEFAULT_AUDIO_RESOLUTION } from '../../../initializers/constants' const expect = chai.expect async function checkHlsPlaylist (servers: ServerInfo[], videoUUID: string, hlsOnly: boolean, resolutions = [ 240, 360, 480, 720 ]) { for (const server of servers) { - const resVideoDetails = await getVideo(server.url, videoUUID) - const videoDetails: VideoDetails = resVideoDetails.body + const videoDetails = await server.videosCommand.get({ id: videoUUID }) const baseUrl = `http://${videoDetails.account.host}` expect(videoDetails.streamingPlaylists).to.have.lengthOf(1) @@ -113,8 +107,8 @@ describe('Test HLS videos', function () { it('Should upload a video and transcode it to HLS', async function () { this.timeout(120000) - const res = await uploadVideo(servers[0].url, servers[0].accessToken, { name: 'video 1', fixture: 'video_short.webm' }) - videoUUID = res.body.video.uuid + const { uuid } = await servers[0].videosCommand.upload({ attributes: { name: 'video 1', fixture: 'video_short.webm' } }) + videoUUID = uuid await waitJobs(servers) @@ -124,8 +118,8 @@ describe('Test HLS videos', function () { it('Should upload an audio file and transcode it to HLS', async function () { this.timeout(120000) - const res = await uploadVideo(servers[0].url, servers[0].accessToken, { name: 'video audio', fixture: 'sample.ogg' }) - videoAudioUUID = res.body.video.uuid + const { uuid } = await servers[0].videosCommand.upload({ attributes: { name: 'video audio', fixture: 'sample.ogg' } }) + videoAudioUUID = uuid await waitJobs(servers) @@ -135,7 +129,7 @@ describe('Test HLS videos', function () { it('Should update the video', async function () { this.timeout(10000) - await updateVideo(servers[0].url, servers[0].accessToken, videoUUID, { name: 'video 1 updated' }) + await servers[0].videosCommand.update({ id: videoUUID, attributes: { name: 'video 1 updated' } }) await waitJobs(servers) @@ -145,14 +139,14 @@ describe('Test HLS videos', function () { it('Should delete videos', async function () { this.timeout(10000) - await removeVideo(servers[0].url, servers[0].accessToken, videoUUID) - await removeVideo(servers[0].url, servers[0].accessToken, videoAudioUUID) + await servers[0].videosCommand.remove({ id: videoUUID }) + await servers[0].videosCommand.remove({ id: videoAudioUUID }) await waitJobs(servers) for (const server of servers) { - await getVideo(server.url, videoUUID, HttpStatusCode.NOT_FOUND_404) - await getVideo(server.url, videoAudioUUID, HttpStatusCode.NOT_FOUND_404) + await server.videosCommand.get({ id: videoUUID, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) + await server.videosCommand.get({ id: videoAudioUUID, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) } }) diff --git a/server/tests/api/videos/video-imports.ts b/server/tests/api/videos/video-imports.ts index 052c052b4..31fdfe12e 100644 --- a/server/tests/api/videos/video-imports.ts +++ b/server/tests/api/videos/video-imports.ts @@ -7,9 +7,6 @@ import { cleanupTests, doubleFollow, flushAndRunMultipleServers, - getMyVideos, - getVideo, - getVideosList, ImportsCommand, ServerInfo, setAccessTokensToServers, @@ -17,7 +14,7 @@ import { testImage, waitJobs } from '@shared/extra-utils' -import { VideoDetails, VideoPrivacy, VideoResolution } from '@shared/models' +import { VideoPrivacy, VideoResolution } from '@shared/models' const expect = chai.expect @@ -29,8 +26,7 @@ describe('Test video imports', function () { if (areHttpImportTestsDisabled()) return async function checkVideosServer1 (server: ServerInfo, idHttp: string, idMagnet: string, idTorrent: string) { - const resHttp = await getVideo(server.url, idHttp) - const videoHttp: VideoDetails = resHttp.body + const videoHttp = await server.videosCommand.get({ id: idHttp }) expect(videoHttp.name).to.equal('small video - youtube') // FIXME: youtube-dl seems broken @@ -47,10 +43,8 @@ describe('Test video imports', function () { expect(originallyPublishedAt.getMonth()).to.equal(0) expect(originallyPublishedAt.getFullYear()).to.equal(2019) - const resMagnet = await getVideo(server.url, idMagnet) - const videoMagnet: VideoDetails = resMagnet.body - const resTorrent = await getVideo(server.url, idTorrent) - const videoTorrent: VideoDetails = resTorrent.body + const videoMagnet = await server.videosCommand.get({ id: idMagnet }) + const videoTorrent = await server.videosCommand.get({ id: idTorrent }) for (const video of [ videoMagnet, videoTorrent ]) { expect(video.category.label).to.equal('Misc') @@ -70,8 +64,7 @@ describe('Test video imports', function () { } async function checkVideoServer2 (server: ServerInfo, id: number | string) { - const res = await getVideo(server.url, id) - const video: VideoDetails = res.body + const video = await server.videosCommand.get({ id }) expect(video.name).to.equal('my super name') expect(video.category.label).to.equal('Entertainment') @@ -190,15 +183,14 @@ Ajouter un sous-titre est vraiment facile`) }) it('Should list the videos to import in my videos on server 1', async function () { - const res = await getMyVideos(servers[0].url, servers[0].accessToken, 0, 5, 'createdAt') + const { total, data } = await servers[0].videosCommand.listMyVideos({ sort: 'createdAt' }) - expect(res.body.total).to.equal(3) + expect(total).to.equal(3) - const videos = res.body.data - expect(videos).to.have.lengthOf(3) - expect(videos[0].name).to.equal('small video - youtube') - expect(videos[1].name).to.equal('super peertube2 video') - expect(videos[2].name).to.equal('你好 世界 720p.mp4') + expect(data).to.have.lengthOf(3) + expect(data[0].name).to.equal('small video - youtube') + expect(data[1].name).to.equal('super peertube2 video') + expect(data[2].name).to.equal('你好 世界 720p.mp4') }) it('Should list the videos to import in my imports on server 1', async function () { @@ -229,11 +221,11 @@ Ajouter un sous-titre est vraiment facile`) await waitJobs(servers) for (const server of servers) { - const res = await getVideosList(server.url) - expect(res.body.total).to.equal(3) - expect(res.body.data).to.have.lengthOf(3) + const { total, data } = await server.videosCommand.list() + expect(total).to.equal(3) + expect(data).to.have.lengthOf(3) - const [ videoHttp, videoMagnet, videoTorrent ] = res.body.data + const [ videoHttp, videoMagnet, videoTorrent ] = data await checkVideosServer1(server, videoHttp.uuid, videoMagnet.uuid, videoTorrent.uuid) } }) @@ -262,13 +254,13 @@ Ajouter un sous-titre est vraiment facile`) await waitJobs(servers) for (const server of servers) { - const res = await getVideosList(server.url) - expect(res.body.total).to.equal(4) - expect(res.body.data).to.have.lengthOf(4) + const { total, data } = await server.videosCommand.list() + expect(total).to.equal(4) + expect(data).to.have.lengthOf(4) - await checkVideoServer2(server, res.body.data[0].uuid) + await checkVideoServer2(server, data[0].uuid) - const [ , videoHttp, videoMagnet, videoTorrent ] = res.body.data + const [ , videoHttp, videoMagnet, videoTorrent ] = data await checkVideosServer1(server, videoHttp.uuid, videoMagnet.uuid, videoTorrent.uuid) } }) @@ -288,8 +280,7 @@ Ajouter un sous-titre est vraiment facile`) await waitJobs(servers) for (const server of servers) { - const res = await getVideo(server.url, videoUUID) - const video: VideoDetails = res.body + const video = await server.videosCommand.get({ id: videoUUID }) expect(video.name).to.equal('transcoded video') expect(video.files).to.have.lengthOf(4) @@ -339,8 +330,7 @@ Ajouter un sous-titre est vraiment facile`) await waitJobs(servers) // test resolution - const res2 = await getVideo(servers[0].url, videoUUID) - const video: VideoDetails = res2.body + const video = await servers[0].videosCommand.get({ id: videoUUID }) expect(video.name).to.equal('hdr video') const maxResolution = Math.max.apply(Math, video.files.map(function (o) { return o.resolution.id })) expect(maxResolution, 'expected max resolution not met').to.equals(VideoResolution.H_1080P) diff --git a/server/tests/api/videos/video-nsfw.ts b/server/tests/api/videos/video-nsfw.ts index 9dc26fca6..b8fff096d 100644 --- a/server/tests/api/videos/video-nsfw.ts +++ b/server/tests/api/videos/video-nsfw.ts @@ -2,18 +2,7 @@ import 'mocha' import * as chai from 'chai' -import { - cleanupTests, - flushAndRunServer, - getAccountVideos, - getMyVideos, - getVideoChannelVideos, - getVideosList, - getVideosListWithToken, - ServerInfo, - setAccessTokensToServers, - uploadVideo -} from '@shared/extra-utils' +import { cleanupTests, flushAndRunServer, ServerInfo, setAccessTokensToServers } from '@shared/extra-utils' import { BooleanBothQuery, CustomConfig, ResultList, Video, VideosOverview } from '@shared/models' const expect = chai.expect @@ -37,10 +26,10 @@ describe('Test video NSFW policy', function () { if (token) { promises = [ - getVideosListWithToken(server.url, token, query).then(res => res.body), server.searchCommand.advancedVideoSearch({ token, search: { search: 'n', sort: '-publishedAt', ...query } }), - getAccountVideos(server.url, token, accountName, 0, 5, undefined, query).then(res => res.body), - getVideoChannelVideos(server.url, token, videoChannelName, 0, 5, undefined, query).then(res => res.body) + server.videosCommand.listWithToken({ token, ...query }), + server.videosCommand.listByAccount({ token, accountName, ...query }), + server.videosCommand.listByChannel({ token, videoChannelName, ...query }) ] // Overviews do not support video filters @@ -54,10 +43,10 @@ describe('Test video NSFW policy', function () { } promises = [ - getVideosList(server.url).then(res => res.body), server.searchCommand.searchVideos({ search: 'n', sort: '-publishedAt' }), - getAccountVideos(server.url, undefined, accountName, 0, 5).then(res => res.body), - getVideoChannelVideos(server.url, undefined, videoChannelName, 0, 5).then(res => res.body) + server.videosCommand.list(), + server.videosCommand.listByAccount({ accountName }), + server.videosCommand.listByChannel({ videoChannelName }) ] // Overviews do not support video filters @@ -79,12 +68,12 @@ describe('Test video NSFW policy', function () { { const attributes = { name: 'nsfw', nsfw: true, category: 1 } - await uploadVideo(server.url, server.accessToken, attributes) + await server.videosCommand.upload({ attributes }) } { const attributes = { name: 'normal', nsfw: false, category: 1 } - await uploadVideo(server.url, server.accessToken, attributes) + await server.videosCommand.upload({ attributes }) } customConfig = await server.configCommand.getCustomConfig() @@ -192,13 +181,12 @@ describe('Test video NSFW policy', function () { }) it('Should be able to see my NSFW videos even with do_not_list user NSFW policy', async function () { - const res = await getMyVideos(server.url, server.accessToken, 0, 5) - expect(res.body.total).to.equal(2) + const { total, data } = await server.videosCommand.listMyVideos() + expect(total).to.equal(2) - const videos = res.body.data - expect(videos).to.have.lengthOf(2) - expect(videos[0].name).to.equal('normal') - expect(videos[1].name).to.equal('nsfw') + expect(data).to.have.lengthOf(2) + expect(data[0].name).to.equal('normal') + expect(data[1].name).to.equal('nsfw') }) it('Should display NSFW videos when the nsfw param === true', async function () { diff --git a/server/tests/api/videos/video-playlist-thumbnails.ts b/server/tests/api/videos/video-playlist-thumbnails.ts index af5df8d90..14739af20 100644 --- a/server/tests/api/videos/video-playlist-thumbnails.ts +++ b/server/tests/api/videos/video-playlist-thumbnails.ts @@ -10,7 +10,6 @@ import { setAccessTokensToServers, setDefaultVideoChannel, testImage, - uploadVideoAndGetId, waitJobs } from '../../../../shared/extra-utils' import { VideoPlaylistPrivacy } from '../../../../shared/models/videos/playlist/video-playlist-privacy.model' @@ -55,8 +54,8 @@ describe('Playlist thumbnail', function () { // Server 1 and server 2 follow each other await doubleFollow(servers[0], servers[1]) - video1 = (await uploadVideoAndGetId({ server: servers[0], videoName: 'video 1' })).id - video2 = (await uploadVideoAndGetId({ server: servers[0], videoName: 'video 2' })).id + video1 = (await servers[0].videosCommand.quickUpload({ name: 'video 1' })).id + video2 = (await servers[0].videosCommand.quickUpload({ name: 'video 2' })).id await waitJobs(servers) }) diff --git a/server/tests/api/videos/video-playlists.ts b/server/tests/api/videos/video-playlists.ts index e57d86c14..40f61ca19 100644 --- a/server/tests/api/videos/video-playlists.ts +++ b/server/tests/api/videos/video-playlists.ts @@ -13,9 +13,6 @@ import { setAccessTokensToServers, setDefaultVideoChannel, testImage, - updateVideo, - uploadVideo, - uploadVideoAndGetId, wait, waitJobs } from '@shared/extra-utils' @@ -99,14 +96,14 @@ describe('Test video playlists', function () { for (const server of servers) { for (let i = 0; i < 7; i++) { const name = `video ${i} server ${server.serverNumber}` - const resVideo = await uploadVideo(server.url, server.accessToken, { name, nsfw: false }) + const video = await server.videosCommand.upload({ attributes: { name, nsfw: false } }) - server.videos.push(resVideo.body.video) + server.videos.push(video) } } } - nsfwVideoServer1 = (await uploadVideoAndGetId({ server: servers[0], videoName: 'NSFW video', nsfw: true })).id + nsfwVideoServer1 = (await servers[0].videosCommand.quickUpload({ name: 'NSFW video', nsfw: true })).id userTokenServer1 = await servers[0].usersCommand.generateUserAndToken('user1') @@ -620,9 +617,9 @@ describe('Test video playlists', function () { return commands[0].addElement({ token: userTokenServer1, playlistId: playlistServer1Id2, attributes }) } - video1 = (await uploadVideoAndGetId({ server: servers[0], videoName: 'video 89', token: userTokenServer1 })).uuid - video2 = (await uploadVideoAndGetId({ server: servers[1], videoName: 'video 90' })).uuid - video3 = (await uploadVideoAndGetId({ server: servers[0], videoName: 'video 91', nsfw: true })).uuid + video1 = (await servers[0].videosCommand.quickUpload({ name: 'video 89', token: userTokenServer1 })).uuid + video2 = (await servers[1].videosCommand.quickUpload({ name: 'video 90' })).uuid + video3 = (await servers[0].videosCommand.quickUpload({ name: 'video 91', nsfw: true })).uuid await waitJobs(servers) @@ -640,7 +637,7 @@ describe('Test video playlists', function () { const position = 1 { - await updateVideo(servers[0].url, servers[0].accessToken, video1, { privacy: VideoPrivacy.PRIVATE }) + await servers[0].videosCommand.update({ id: video1, attributes: { privacy: VideoPrivacy.PRIVATE } }) await waitJobs(servers) await checkPlaylistElementType(groupUser1, playlistServer1UUID2, VideoPlaylistElementType.REGULAR, position, name, 3) @@ -650,7 +647,7 @@ describe('Test video playlists', function () { } { - await updateVideo(servers[0].url, servers[0].accessToken, video1, { privacy: VideoPrivacy.PUBLIC }) + await servers[0].videosCommand.update({ id: video1, attributes: { privacy: VideoPrivacy.PUBLIC } }) await waitJobs(servers) await checkPlaylistElementType(groupUser1, playlistServer1UUID2, VideoPlaylistElementType.REGULAR, position, name, 3) diff --git a/server/tests/api/videos/video-privacy.ts b/server/tests/api/videos/video-privacy.ts index 4e349e350..bcf431edb 100644 --- a/server/tests/api/videos/video-privacy.ts +++ b/server/tests/api/videos/video-privacy.ts @@ -3,22 +3,8 @@ import 'mocha' import * as chai from 'chai' import { HttpStatusCode } from '@shared/core-utils' -import { - cleanupTests, - doubleFollow, - flushAndRunServer, - getMyVideos, - getVideo, - getVideosList, - getVideosListWithToken, - getVideoWithToken, - ServerInfo, - setAccessTokensToServers, - updateVideo, - uploadVideo, - waitJobs -} from '@shared/extra-utils' -import { Video, VideoCreateResult, VideoPrivacy } from '@shared/models' +import { cleanupTests, doubleFollow, flushAndRunServer, ServerInfo, setAccessTokensToServers, waitJobs } from '@shared/extra-utils' +import { VideoCreateResult, VideoPrivacy } from '@shared/models' const expect = chai.expect @@ -66,55 +52,53 @@ describe('Test video privacy', function () { for (const privacy of [ VideoPrivacy.PRIVATE, VideoPrivacy.INTERNAL ]) { const attributes = { privacy } - await uploadVideo(servers[0].url, servers[0].accessToken, attributes) + await servers[0].videosCommand.upload({ attributes }) } await waitJobs(servers) }) it('Should not have these private and internal videos on server 2', async function () { - const res = await getVideosList(servers[1].url) + const { total, data } = await servers[1].videosCommand.list() - expect(res.body.total).to.equal(0) - expect(res.body.data).to.have.lengthOf(0) + expect(total).to.equal(0) + expect(data).to.have.lengthOf(0) }) it('Should not list the private and internal videos for an unauthenticated user on server 1', async function () { - const res = await getVideosList(servers[0].url) + const { total, data } = await servers[0].videosCommand.list() - expect(res.body.total).to.equal(0) - expect(res.body.data).to.have.lengthOf(0) + expect(total).to.equal(0) + expect(data).to.have.lengthOf(0) }) it('Should not list the private video and list the internal video for an authenticated user on server 1', async function () { - const res = await getVideosListWithToken(servers[0].url, servers[0].accessToken) + const { total, data } = await servers[0].videosCommand.listWithToken() - expect(res.body.total).to.equal(1) - expect(res.body.data).to.have.lengthOf(1) + expect(total).to.equal(1) + expect(data).to.have.lengthOf(1) - expect(res.body.data[0].privacy.id).to.equal(VideoPrivacy.INTERNAL) + expect(data[0].privacy.id).to.equal(VideoPrivacy.INTERNAL) }) it('Should list my (private and internal) videos', async function () { - const res = await getMyVideos(servers[0].url, servers[0].accessToken, 0, 10) + const { total, data } = await servers[0].videosCommand.listMyVideos() - expect(res.body.total).to.equal(2) - expect(res.body.data).to.have.lengthOf(2) + expect(total).to.equal(2) + expect(data).to.have.lengthOf(2) - const videos: Video[] = res.body.data - - const privateVideo = videos.find(v => v.privacy.id === VideoPrivacy.PRIVATE) + const privateVideo = data.find(v => v.privacy.id === VideoPrivacy.PRIVATE) privateVideoId = privateVideo.id privateVideoUUID = privateVideo.uuid - const internalVideo = videos.find(v => v.privacy.id === VideoPrivacy.INTERNAL) + const internalVideo = data.find(v => v.privacy.id === VideoPrivacy.INTERNAL) internalVideoId = internalVideo.id internalVideoUUID = internalVideo.uuid }) it('Should not be able to watch the private/internal video with non authenticated user', async function () { - await getVideo(servers[0].url, privateVideoUUID, HttpStatusCode.UNAUTHORIZED_401) - await getVideo(servers[0].url, internalVideoUUID, HttpStatusCode.UNAUTHORIZED_401) + await servers[0].videosCommand.get({ id: privateVideoUUID, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) + await servers[0].videosCommand.get({ id: internalVideoUUID, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should not be able to watch the private video with another user', async function () { @@ -127,15 +111,20 @@ describe('Test video privacy', function () { await servers[0].usersCommand.create({ username: user.username, password: user.password }) anotherUserToken = await servers[0].loginCommand.getAccessToken(user) - await getVideoWithToken(servers[0].url, anotherUserToken, privateVideoUUID, HttpStatusCode.FORBIDDEN_403) + + await servers[0].videosCommand.getWithToken({ + token: anotherUserToken, + id: privateVideoUUID, + expectedStatus: HttpStatusCode.FORBIDDEN_403 + }) }) it('Should be able to watch the internal video with another user', async function () { - await getVideoWithToken(servers[0].url, anotherUserToken, internalVideoUUID, HttpStatusCode.OK_200) + await servers[0].videosCommand.getWithToken({ token: anotherUserToken, id: internalVideoUUID }) }) it('Should be able to watch the private video with the correct user', async function () { - await getVideoWithToken(servers[0].url, servers[0].accessToken, privateVideoUUID, HttpStatusCode.OK_200) + await servers[0].videosCommand.getWithToken({ id: privateVideoUUID }) }) }) @@ -148,7 +137,7 @@ describe('Test video privacy', function () { name: 'unlisted video', privacy: VideoPrivacy.UNLISTED } - await uploadVideo(servers[1].url, servers[1].accessToken, attributes) + await servers[1].videosCommand.upload({ attributes }) // Server 2 has transcoding enabled await waitJobs(servers) @@ -156,32 +145,32 @@ describe('Test video privacy', function () { it('Should not have this unlisted video listed on server 1 and 2', async function () { for (const server of servers) { - const res = await getVideosList(server.url) + const { total, data } = await server.videosCommand.list() - expect(res.body.total).to.equal(0) - expect(res.body.data).to.have.lengthOf(0) + expect(total).to.equal(0) + expect(data).to.have.lengthOf(0) } }) it('Should list my (unlisted) videos', async function () { - const res = await getMyVideos(servers[1].url, servers[1].accessToken, 0, 1) + const { total, data } = await servers[1].videosCommand.listMyVideos() - expect(res.body.total).to.equal(1) - expect(res.body.data).to.have.lengthOf(1) + expect(total).to.equal(1) + expect(data).to.have.lengthOf(1) - unlistedVideo = res.body.data[0] + unlistedVideo = data[0] }) it('Should not be able to get this unlisted video using its id', async function () { - await getVideo(servers[1].url, unlistedVideo.id, 404) + await servers[1].videosCommand.get({ id: unlistedVideo.id, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) it('Should be able to get this unlisted video using its uuid/shortUUID', async function () { for (const server of servers) { for (const id of [ unlistedVideo.uuid, unlistedVideo.shortUUID ]) { - const res = await getVideo(server.url, id) + const video = await server.videosCommand.get({ id }) - expect(res.body.name).to.equal('unlisted video') + expect(video.name).to.equal('unlisted video') } } }) @@ -193,28 +182,28 @@ describe('Test video privacy', function () { name: 'unlisted video', privacy: VideoPrivacy.UNLISTED } - await uploadVideo(servers[0].url, servers[0].accessToken, attributes) + await servers[0].videosCommand.upload({ attributes }) await waitJobs(servers) }) it('Should list my new unlisted video', async function () { - const res = await getMyVideos(servers[0].url, servers[0].accessToken, 0, 3) + const { total, data } = await servers[0].videosCommand.listMyVideos() - expect(res.body.total).to.equal(3) - expect(res.body.data).to.have.lengthOf(3) + expect(total).to.equal(3) + expect(data).to.have.lengthOf(3) - nonFederatedUnlistedVideoUUID = res.body.data[0].uuid + nonFederatedUnlistedVideoUUID = data[0].uuid }) it('Should be able to get non-federated unlisted video from origin', async function () { - const res = await getVideo(servers[0].url, nonFederatedUnlistedVideoUUID) + const video = await servers[0].videosCommand.get({ id: nonFederatedUnlistedVideoUUID }) - expect(res.body.name).to.equal('unlisted video') + expect(video.name).to.equal('unlisted video') }) it('Should not be able to get non-federated unlisted video from federated server', async function () { - await getVideo(servers[1].url, nonFederatedUnlistedVideoUUID, HttpStatusCode.NOT_FOUND_404) + await servers[1].videosCommand.get({ id: nonFederatedUnlistedVideoUUID, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) }) @@ -226,20 +215,20 @@ describe('Test video privacy', function () { now = Date.now() { - const attribute = { + const attributes = { name: 'private video becomes public', privacy: VideoPrivacy.PUBLIC } - await updateVideo(servers[0].url, servers[0].accessToken, privateVideoId, attribute) + await servers[0].videosCommand.update({ id: privateVideoId, attributes }) } { - const attribute = { + const attributes = { name: 'internal video becomes public', privacy: VideoPrivacy.PUBLIC } - await updateVideo(servers[0].url, servers[0].accessToken, internalVideoId, attribute) + await servers[0].videosCommand.update({ id: internalVideoId, attributes }) } await waitJobs(servers) @@ -247,13 +236,12 @@ describe('Test video privacy', function () { it('Should have this new public video listed on server 1 and 2', async function () { for (const server of servers) { - const res = await getVideosList(server.url) - expect(res.body.total).to.equal(2) - expect(res.body.data).to.have.lengthOf(2) + const { total, data } = await server.videosCommand.list() + expect(total).to.equal(2) + expect(data).to.have.lengthOf(2) - const videos: Video[] = res.body.data - const privateVideo = videos.find(v => v.name === 'private video becomes public') - const internalVideo = videos.find(v => v.name === 'internal video becomes public') + const privateVideo = data.find(v => v.name === 'private video becomes public') + const internalVideo = data.find(v => v.name === 'internal video becomes public') expect(privateVideo).to.not.be.undefined expect(internalVideo).to.not.be.undefined @@ -270,27 +258,25 @@ describe('Test video privacy', function () { it('Should set these videos as private and internal', async function () { this.timeout(10000) - await updateVideo(servers[0].url, servers[0].accessToken, internalVideoId, { privacy: VideoPrivacy.PRIVATE }) - await updateVideo(servers[0].url, servers[0].accessToken, privateVideoId, { privacy: VideoPrivacy.INTERNAL }) + await servers[0].videosCommand.update({ id: internalVideoId, attributes: { privacy: VideoPrivacy.PRIVATE } }) + await servers[0].videosCommand.update({ id: privateVideoId, attributes: { privacy: VideoPrivacy.INTERNAL } }) await waitJobs(servers) for (const server of servers) { - const res = await getVideosList(server.url) + const { total, data } = await server.videosCommand.list() - expect(res.body.total).to.equal(0) - expect(res.body.data).to.have.lengthOf(0) + expect(total).to.equal(0) + expect(data).to.have.lengthOf(0) } { - const res = await getMyVideos(servers[0].url, servers[0].accessToken, 0, 5) - const videos = res.body.data - - expect(res.body.total).to.equal(3) - expect(videos).to.have.lengthOf(3) + const { total, data } = await servers[0].videosCommand.listMyVideos() + expect(total).to.equal(3) + expect(data).to.have.lengthOf(3) - const privateVideo = videos.find(v => v.name === 'private video becomes public') - const internalVideo = videos.find(v => v.name === 'internal video becomes public') + const privateVideo = data.find(v => v.name === 'private video becomes public') + const internalVideo = data.find(v => v.name === 'internal video becomes public') expect(privateVideo).to.not.be.undefined expect(internalVideo).to.not.be.undefined diff --git a/server/tests/api/videos/video-schedule-update.ts b/server/tests/api/videos/video-schedule-update.ts index 204f43611..635ae6ff1 100644 --- a/server/tests/api/videos/video-schedule-update.ts +++ b/server/tests/api/videos/video-schedule-update.ts @@ -1,22 +1,17 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ -import * as chai from 'chai' import 'mocha' -import { VideoPrivacy } from '../../../../shared/models/videos' +import * as chai from 'chai' import { cleanupTests, doubleFollow, flushAndRunMultipleServers, - getMyVideos, - getVideosList, - getVideoWithToken, ServerInfo, setAccessTokensToServers, - updateVideo, - uploadVideo, - wait -} from '../../../../shared/extra-utils' -import { waitJobs } from '../../../../shared/extra-utils/server/jobs' + wait, + waitJobs +} from '@shared/extra-utils' +import { VideoPrivacy } from '@shared/models' const expect = chai.expect @@ -45,35 +40,34 @@ describe('Test video update scheduler', function () { it('Should upload a video and schedule an update in 10 seconds', async function () { this.timeout(10000) - const videoAttributes = { + const attributes = { name: 'video 1', privacy: VideoPrivacy.PRIVATE, scheduleUpdate: { updateAt: in10Seconds().toISOString(), - privacy: VideoPrivacy.PUBLIC + privacy: VideoPrivacy.PUBLIC as VideoPrivacy.PUBLIC } } - await uploadVideo(servers[0].url, servers[0].accessToken, videoAttributes) + await servers[0].videosCommand.upload({ attributes }) await waitJobs(servers) }) it('Should not list the video (in privacy mode)', async function () { for (const server of servers) { - const res = await getVideosList(server.url) + const { total } = await server.videosCommand.list() - expect(res.body.total).to.equal(0) + expect(total).to.equal(0) } }) it('Should have my scheduled video in my account videos', async function () { - const res = await getMyVideos(servers[0].url, servers[0].accessToken, 0, 5) - expect(res.body.total).to.equal(1) + const { total, data } = await servers[0].videosCommand.listMyVideos() + expect(total).to.equal(1) - const videoFromList = res.body.data[0] - const res2 = await getVideoWithToken(servers[0].url, servers[0].accessToken, videoFromList.uuid) - const videoFromGet = res2.body + const videoFromList = data[0] + const videoFromGet = await servers[0].videosCommand.getWithToken({ id: videoFromList.uuid }) for (const video of [ videoFromList, videoFromGet ]) { expect(video.name).to.equal('video 1') @@ -90,23 +84,23 @@ describe('Test video update scheduler', function () { await waitJobs(servers) for (const server of servers) { - const res = await getVideosList(server.url) + const { total, data } = await server.videosCommand.list() - expect(res.body.total).to.equal(1) - expect(res.body.data[0].name).to.equal('video 1') + expect(total).to.equal(1) + expect(data[0].name).to.equal('video 1') } }) it('Should upload a video without scheduling an update', async function () { this.timeout(10000) - const videoAttributes = { + const attributes = { name: 'video 2', privacy: VideoPrivacy.PRIVATE } - const res = await uploadVideo(servers[0].url, servers[0].accessToken, videoAttributes) - video2UUID = res.body.video.uuid + const { uuid } = await servers[0].videosCommand.upload({ attributes }) + video2UUID = uuid await waitJobs(servers) }) @@ -114,31 +108,31 @@ describe('Test video update scheduler', function () { it('Should update a video by scheduling an update', async function () { this.timeout(10000) - const videoAttributes = { + const attributes = { name: 'video 2 updated', scheduleUpdate: { updateAt: in10Seconds().toISOString(), - privacy: VideoPrivacy.PUBLIC + privacy: VideoPrivacy.PUBLIC as VideoPrivacy.PUBLIC } } - await updateVideo(servers[0].url, servers[0].accessToken, video2UUID, videoAttributes) + await servers[0].videosCommand.update({ id: video2UUID, attributes }) await waitJobs(servers) }) it('Should not display the updated video', async function () { for (const server of servers) { - const res = await getVideosList(server.url) + const { total } = await server.videosCommand.list() - expect(res.body.total).to.equal(1) + expect(total).to.equal(1) } }) it('Should have my scheduled updated video in my account videos', async function () { - const res = await getMyVideos(servers[0].url, servers[0].accessToken, 0, 5) - expect(res.body.total).to.equal(2) + const { total, data } = await servers[0].videosCommand.listMyVideos() + expect(total).to.equal(2) - const video = res.body.data.find(v => v.uuid === video2UUID) + const video = data.find(v => v.uuid === video2UUID) expect(video).not.to.be.undefined expect(video.name).to.equal('video 2 updated') @@ -155,11 +149,10 @@ describe('Test video update scheduler', function () { await waitJobs(servers) for (const server of servers) { - const res = await getVideosList(server.url) - - expect(res.body.total).to.equal(2) + const { total, data } = await server.videosCommand.list() + expect(total).to.equal(2) - const video = res.body.data.find(v => v.uuid === video2UUID) + const video = data.find(v => v.uuid === video2UUID) expect(video).not.to.be.undefined expect(video.name).to.equal('video 2 updated') } diff --git a/server/tests/api/videos/video-transcoder.ts b/server/tests/api/videos/video-transcoder.ts index f16b22bae..b41c68283 100644 --- a/server/tests/api/videos/video-transcoder.ts +++ b/server/tests/api/videos/video-transcoder.ts @@ -2,11 +2,9 @@ import 'mocha' import * as chai from 'chai' -import { FfprobeData } from 'fluent-ffmpeg' import { omit } from 'lodash' import { join } from 'path' -import { VIDEO_TRANSCODING_FPS } from '../../../../server/initializers/constants' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '@shared/core-utils' import { buildAbsoluteFixturePath, cleanupTests, @@ -14,19 +12,14 @@ import { flushAndRunMultipleServers, generateHighBitrateVideo, generateVideoWithFramerate, - getMyVideos, - getVideo, - getVideoFileMetadataUrl, - getVideosList, makeGetRequest, ServerInfo, setAccessTokensToServers, - uploadVideo, - uploadVideoAndGetId, waitJobs, webtorrentAdd -} from '../../../../shared/extra-utils' -import { getMaxBitrate, VideoDetails, VideoResolution, VideoState } from '../../../../shared/models/videos' +} from '@shared/extra-utils' +import { getMaxBitrate, VideoResolution, VideoState } from '@shared/models' +import { VIDEO_TRANSCODING_FPS } from '../../../../server/initializers/constants' import { canDoQuickTranscode, getAudioStream, @@ -84,21 +77,20 @@ describe('Test video transcoding', function () { it('Should not transcode video on server 1', async function () { this.timeout(60_000) - const videoAttributes = { + const attributes = { name: 'my super name for server 1', description: 'my super description for server 1', fixture: 'video_short.webm' } - await uploadVideo(servers[0].url, servers[0].accessToken, videoAttributes) + await servers[0].videosCommand.upload({ attributes }) await waitJobs(servers) for (const server of servers) { - const res = await getVideosList(server.url) - const video = res.body.data[0] + const { data } = await server.videosCommand.list() + const video = data[0] - const res2 = await getVideo(server.url, video.id) - const videoDetails = res2.body + const videoDetails = await server.videosCommand.get({ id: video.id }) expect(videoDetails.files).to.have.lengthOf(1) const magnetUri = videoDetails.files[0].magnetUri @@ -114,21 +106,20 @@ describe('Test video transcoding', function () { it('Should transcode video on server 2', async function () { this.timeout(120_000) - const videoAttributes = { + const attributes = { name: 'my super name for server 2', description: 'my super description for server 2', fixture: 'video_short.webm' } - await uploadVideo(servers[1].url, servers[1].accessToken, videoAttributes) + await servers[1].videosCommand.upload({ attributes }) await waitJobs(servers) for (const server of servers) { - const res = await getVideosList(server.url) + const { data } = await server.videosCommand.list() - const video = res.body.data.find(v => v.name === videoAttributes.name) - const res2 = await getVideo(server.url, video.id) - const videoDetails = res2.body + const video = data.find(v => v.name === attributes.name) + const videoDetails = await server.videosCommand.get({ id: video.id }) expect(videoDetails.files).to.have.lengthOf(4) @@ -147,47 +138,50 @@ describe('Test video transcoding', function () { { // Upload the video, but wait transcoding - const videoAttributes = { + const attributes = { name: 'waiting video', fixture: 'video_short1.webm', waitTranscoding: true } - const resVideo = await uploadVideo(servers[1].url, servers[1].accessToken, videoAttributes) - const videoId = resVideo.body.video.uuid + const { uuid } = await servers[1].videosCommand.upload({ attributes }) + const videoId = uuid // Should be in transcode state - const { body } = await getVideo(servers[1].url, videoId) + const body = await servers[1].videosCommand.get({ id: videoId }) expect(body.name).to.equal('waiting video') expect(body.state.id).to.equal(VideoState.TO_TRANSCODE) expect(body.state.label).to.equal('To transcode') expect(body.waitTranscoding).to.be.true - // Should have my video - const resMyVideos = await getMyVideos(servers[1].url, servers[1].accessToken, 0, 10) - const videoToFindInMine = resMyVideos.body.data.find(v => v.name === videoAttributes.name) - expect(videoToFindInMine).not.to.be.undefined - expect(videoToFindInMine.state.id).to.equal(VideoState.TO_TRANSCODE) - expect(videoToFindInMine.state.label).to.equal('To transcode') - expect(videoToFindInMine.waitTranscoding).to.be.true + { + // Should have my video + const { data } = await servers[1].videosCommand.listMyVideos() + const videoToFindInMine = data.find(v => v.name === attributes.name) + expect(videoToFindInMine).not.to.be.undefined + expect(videoToFindInMine.state.id).to.equal(VideoState.TO_TRANSCODE) + expect(videoToFindInMine.state.label).to.equal('To transcode') + expect(videoToFindInMine.waitTranscoding).to.be.true + } - // Should not list this video - const resVideos = await getVideosList(servers[1].url) - const videoToFindInList = resVideos.body.data.find(v => v.name === videoAttributes.name) - expect(videoToFindInList).to.be.undefined + { + // Should not list this video + const { data } = await servers[1].videosCommand.list() + const videoToFindInList = data.find(v => v.name === attributes.name) + expect(videoToFindInList).to.be.undefined + } // Server 1 should not have the video yet - await getVideo(servers[0].url, videoId, HttpStatusCode.NOT_FOUND_404) + await servers[0].videosCommand.get({ id: videoId, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) } await waitJobs(servers) for (const server of servers) { - const res = await getVideosList(server.url) - const videoToFind = res.body.data.find(v => v.name === 'waiting video') + const { data } = await server.videosCommand.list() + const videoToFind = data.find(v => v.name === 'waiting video') expect(videoToFind).not.to.be.undefined - const res2 = await getVideo(server.url, videoToFind.id) - const videoDetails: VideoDetails = res2.body + const videoDetails = await server.videosCommand.get({ id: videoToFind.id }) expect(videoDetails.state.id).to.equal(VideoState.PUBLISHED) expect(videoDetails.state.label).to.equal('Published') @@ -208,22 +202,20 @@ describe('Test video transcoding', function () { } for (const fixture of [ 'video_short.mkv', 'video_short.avi' ]) { - const videoAttributes = { + const attributes = { name: fixture, fixture } - await uploadVideo(servers[1].url, servers[1].accessToken, videoAttributes) + await servers[1].videosCommand.upload({ attributes }) await waitJobs(servers) for (const server of servers) { - const res = await getVideosList(server.url) - - const video = res.body.data.find(v => v.name === videoAttributes.name) - const res2 = await getVideo(server.url, video.id) - const videoDetails = res2.body + const { data } = await server.videosCommand.list() + const video = data.find(v => v.name === attributes.name) + const videoDetails = await server.videosCommand.get({ id: video.id }) expect(videoDetails.files).to.have.lengthOf(4) const magnetUri = videoDetails.files[0].magnetUri @@ -235,22 +227,20 @@ describe('Test video transcoding', function () { it('Should transcode a 4k video', async function () { this.timeout(200_000) - const videoAttributes = { + const attributes = { name: '4k video', fixture: 'video_short_4k.mp4' } - const resUpload = await uploadVideo(servers[1].url, servers[1].accessToken, videoAttributes) - video4k = resUpload.body.video.uuid + const { uuid } = await servers[1].videosCommand.upload({ attributes }) + video4k = uuid await waitJobs(servers) const resolutions = [ 240, 360, 480, 720, 1080, 1440, 2160 ] for (const server of servers) { - const res = await getVideo(server.url, video4k) - const videoDetails: VideoDetails = res.body - + const videoDetails = await server.videosCommand.get({ id: video4k }) expect(videoDetails.files).to.have.lengthOf(resolutions.length) for (const r of resolutions) { @@ -266,20 +256,19 @@ describe('Test video transcoding', function () { it('Should transcode high bit rate mp3 to proper bit rate', async function () { this.timeout(60_000) - const videoAttributes = { + const attributes = { name: 'mp3_256k', fixture: 'video_short_mp3_256k.mp4' } - await uploadVideo(servers[1].url, servers[1].accessToken, videoAttributes) + await servers[1].videosCommand.upload({ attributes }) await waitJobs(servers) for (const server of servers) { - const res = await getVideosList(server.url) + const { data } = await server.videosCommand.list() - const video = res.body.data.find(v => v.name === videoAttributes.name) - const res2 = await getVideo(server.url, video.id) - const videoDetails: VideoDetails = res2.body + const video = data.find(v => v.name === attributes.name) + const videoDetails = await server.videosCommand.get({ id: video.id }) expect(videoDetails.files).to.have.lengthOf(4) @@ -298,20 +287,19 @@ describe('Test video transcoding', function () { it('Should transcode video with no audio and have no audio itself', async function () { this.timeout(60_000) - const videoAttributes = { + const attributes = { name: 'no_audio', fixture: 'video_short_no_audio.mp4' } - await uploadVideo(servers[1].url, servers[1].accessToken, videoAttributes) + await servers[1].videosCommand.upload({ attributes }) await waitJobs(servers) for (const server of servers) { - const res = await getVideosList(server.url) + const { data } = await server.videosCommand.list() - const video = res.body.data.find(v => v.name === videoAttributes.name) - const res2 = await getVideo(server.url, video.id) - const videoDetails: VideoDetails = res2.body + const video = data.find(v => v.name === attributes.name) + const videoDetails = await server.videosCommand.get({ id: video.id }) expect(videoDetails.files).to.have.lengthOf(4) const path = servers[1].serversCommand.buildDirectory(join('videos', video.uuid + '-240.mp4')) @@ -323,24 +311,23 @@ describe('Test video transcoding', function () { it('Should leave the audio untouched, but properly transcode the video', async function () { this.timeout(60_000) - const videoAttributes = { + const attributes = { name: 'untouched_audio', fixture: 'video_short.mp4' } - await uploadVideo(servers[1].url, servers[1].accessToken, videoAttributes) + await servers[1].videosCommand.upload({ attributes }) await waitJobs(servers) for (const server of servers) { - const res = await getVideosList(server.url) + const { data } = await server.videosCommand.list() - const video = res.body.data.find(v => v.name === videoAttributes.name) - const res2 = await getVideo(server.url, video.id) - const videoDetails: VideoDetails = res2.body + const video = data.find(v => v.name === attributes.name) + const videoDetails = await server.videosCommand.get({ id: video.id }) expect(videoDetails.files).to.have.lengthOf(4) - const fixturePath = buildAbsoluteFixturePath(videoAttributes.fixture) + const fixturePath = buildAbsoluteFixturePath(attributes.fixture) const fixtureVideoProbe = await getAudioStream(fixturePath) const path = servers[1].serversCommand.buildDirectory(join('videos', video.uuid + '-240.mp4')) @@ -384,17 +371,16 @@ describe('Test video transcoding', function () { it('Should merge an audio file with the preview file', async function () { this.timeout(60_000) - const videoAttributesArg = { name: 'audio_with_preview', previewfile: 'preview.jpg', fixture: 'sample.ogg' } - await uploadVideo(servers[1].url, servers[1].accessToken, videoAttributesArg, HttpStatusCode.OK_200, mode) + const attributes = { name: 'audio_with_preview', previewfile: 'preview.jpg', fixture: 'sample.ogg' } + await servers[1].videosCommand.upload({ attributes, mode }) await waitJobs(servers) for (const server of servers) { - const res = await getVideosList(server.url) + const { data } = await server.videosCommand.list() - const video = res.body.data.find(v => v.name === 'audio_with_preview') - const res2 = await getVideo(server.url, video.id) - const videoDetails: VideoDetails = res2.body + const video = data.find(v => v.name === 'audio_with_preview') + const videoDetails = await server.videosCommand.get({ id: video.id }) expect(videoDetails.files).to.have.lengthOf(1) @@ -409,17 +395,16 @@ describe('Test video transcoding', function () { it('Should upload an audio file and choose a default background image', async function () { this.timeout(60_000) - const videoAttributesArg = { name: 'audio_without_preview', fixture: 'sample.ogg' } - await uploadVideo(servers[1].url, servers[1].accessToken, videoAttributesArg, HttpStatusCode.OK_200, mode) + const attributes = { name: 'audio_without_preview', fixture: 'sample.ogg' } + await servers[1].videosCommand.upload({ attributes, mode }) await waitJobs(servers) for (const server of servers) { - const res = await getVideosList(server.url) + const { data } = await server.videosCommand.list() - const video = res.body.data.find(v => v.name === 'audio_without_preview') - const res2 = await getVideo(server.url, video.id) - const videoDetails = res2.body + const video = data.find(v => v.name === 'audio_without_preview') + const videoDetails = await server.videosCommand.get({ id: video.id }) expect(videoDetails.files).to.have.lengthOf(1) @@ -448,14 +433,13 @@ describe('Test video transcoding', function () { } }) - const videoAttributesArg = { name: 'audio_with_preview', previewfile: 'preview.jpg', fixture: 'sample.ogg' } - const resVideo = await uploadVideo(servers[1].url, servers[1].accessToken, videoAttributesArg, HttpStatusCode.OK_200, mode) + const attributes = { name: 'audio_with_preview', previewfile: 'preview.jpg', fixture: 'sample.ogg' } + const { id } = await servers[1].videosCommand.upload({ attributes, mode }) await waitJobs(servers) for (const server of servers) { - const res2 = await getVideo(server.url, resVideo.body.video.id) - const videoDetails: VideoDetails = res2.body + const videoDetails = await server.videosCommand.get({ id }) for (const files of [ videoDetails.files, videoDetails.streamingPlaylists[0].files ]) { expect(files).to.have.lengthOf(2) @@ -481,21 +465,20 @@ describe('Test video transcoding', function () { it('Should transcode a 60 FPS video', async function () { this.timeout(60_000) - const videoAttributes = { + const attributes = { name: 'my super 30fps name for server 2', description: 'my super 30fps description for server 2', fixture: '60fps_720p_small.mp4' } - await uploadVideo(servers[1].url, servers[1].accessToken, videoAttributes) + await servers[1].videosCommand.upload({ attributes }) await waitJobs(servers) for (const server of servers) { - const res = await getVideosList(server.url) + const { data } = await server.videosCommand.list() - const video = res.body.data.find(v => v.name === videoAttributes.name) - const res2 = await getVideo(server.url, video.id) - const videoDetails: VideoDetails = res2.body + const video = data.find(v => v.name === attributes.name) + const videoDetails = await server.videosCommand.get({ id: video.id }) expect(videoDetails.files).to.have.lengthOf(4) expect(videoDetails.files[0].fps).to.be.above(58).and.below(62) @@ -529,20 +512,20 @@ describe('Test video transcoding', function () { expect(fps).to.be.equal(59) } - const videoAttributes = { + const attributes = { name: '59fps video', description: '59fps video', fixture: tempFixturePath } - await uploadVideo(servers[1].url, servers[1].accessToken, videoAttributes) + await servers[1].videosCommand.upload({ attributes }) await waitJobs(servers) for (const server of servers) { - const res = await getVideosList(server.url) + const { data } = await server.videosCommand.list() - const video = res.body.data.find(v => v.name === videoAttributes.name) + const video = data.find(v => v.name === attributes.name) { const path = servers[1].serversCommand.buildDirectory(join('videos', video.uuid + '-240.mp4')) @@ -572,20 +555,20 @@ describe('Test video transcoding', function () { expect(bitrate).to.be.above(getMaxBitrate(VideoResolution.H_1080P, 25, VIDEO_TRANSCODING_FPS)) } - const videoAttributes = { + const attributes = { name: 'high bitrate video', description: 'high bitrate video', fixture: tempFixturePath } - await uploadVideo(servers[1].url, servers[1].accessToken, videoAttributes) + await servers[1].videosCommand.upload({ attributes }) await waitJobs(servers) for (const server of servers) { - const res = await getVideosList(server.url) + const { data } = await server.videosCommand.list() - const video = res.body.data.find(v => v.name === videoAttributes.name) + const video = data.find(v => v.name === attributes.name) for (const resolution of [ '240', '360', '480', '720', '1080' ]) { const path = servers[1].serversCommand.buildDirectory(join('videos', video.uuid + '-' + resolution + '.mp4')) @@ -621,19 +604,18 @@ describe('Test video transcoding', function () { } await servers[1].configCommand.updateCustomSubConfig({ newConfig }) - const videoAttributes = { + const attributes = { name: 'low bitrate', fixture: 'low-bitrate.mp4' } - const resUpload = await uploadVideo(servers[1].url, servers[1].accessToken, videoAttributes) - const videoUUID = resUpload.body.video.uuid + const { uuid } = await servers[1].videosCommand.upload({ attributes }) await waitJobs(servers) const resolutions = [ 240, 360, 480, 720, 1080 ] for (const r of resolutions) { - const path = `videos/${videoUUID}-${r}.mp4` + const path = `videos/${uuid}-${r}.mp4` const size = await servers[1].serversCommand.getServerFileSize(path) expect(size, `${path} not below ${60_000}`).to.be.below(60_000) } @@ -645,7 +627,7 @@ describe('Test video transcoding', function () { it('Should provide valid ffprobe data', async function () { this.timeout(160_000) - const videoUUID = (await uploadVideoAndGetId({ server: servers[1], videoName: 'ffprobe data' })).uuid + const videoUUID = (await servers[1].videosCommand.quickUpload({ name: 'ffprobe data' })).uuid await waitJobs(servers) { @@ -679,8 +661,7 @@ describe('Test video transcoding', function () { } for (const server of servers) { - const res2 = await getVideo(server.url, videoUUID) - const videoDetails: VideoDetails = res2.body + const videoDetails = await server.videosCommand.get({ id: videoUUID }) const videoFiles = videoDetails.files .concat(videoDetails.streamingPlaylists[0].files) @@ -692,8 +673,7 @@ describe('Test video transcoding', function () { expect(file.metadataUrl).to.contain(servers[1].url) expect(file.metadataUrl).to.contain(videoUUID) - const res3 = await getVideoFileMetadataUrl(file.metadataUrl) - const metadata: FfprobeData = res3.body + const metadata = await server.videosCommand.getFileMetadata({ url: file.metadataUrl }) expect(metadata).to.have.nested.property('format.size') } } diff --git a/server/tests/api/videos/videos-filter.ts b/server/tests/api/videos/videos-filter.ts index 4aa00cfc4..4a5a83ee6 100644 --- a/server/tests/api/videos/videos-filter.ts +++ b/server/tests/api/videos/videos-filter.ts @@ -1,21 +1,17 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ import 'mocha' -import * as chai from 'chai' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' +import { expect } from 'chai' +import { HttpStatusCode } from '@shared/core-utils' import { cleanupTests, doubleFollow, flushAndRunMultipleServers, makeGetRequest, ServerInfo, - setAccessTokensToServers, - uploadVideo -} from '../../../../shared/extra-utils' -import { UserRole } from '../../../../shared/models/users' -import { Video, VideoPrivacy } from '../../../../shared/models/videos' - -const expect = chai.expect + setAccessTokensToServers +} from '@shared/extra-utils' +import { UserRole, Video, VideoPrivacy } from '@shared/models' async function getVideosNames (server: ServerInfo, token: string, filter: string, statusCodeExpected = HttpStatusCode.OK_200) { const paths = [ @@ -62,16 +58,16 @@ describe('Test videos filter', function () { await server.usersCommand.create({ username: moderator.username, password: moderator.password, role: UserRole.MODERATOR }) server['moderatorAccessToken'] = await server.loginCommand.getAccessToken(moderator) - await uploadVideo(server.url, server.accessToken, { name: 'public ' + server.serverNumber }) + await server.videosCommand.upload({ attributes: { name: 'public ' + server.serverNumber } }) { const attributes = { name: 'unlisted ' + server.serverNumber, privacy: VideoPrivacy.UNLISTED } - await uploadVideo(server.url, server.accessToken, attributes) + await server.videosCommand.upload({ attributes }) } { const attributes = { name: 'private ' + server.serverNumber, privacy: VideoPrivacy.PRIVATE } - await uploadVideo(server.url, server.accessToken, attributes) + await server.videosCommand.upload({ attributes }) } } diff --git a/server/tests/api/videos/videos-history.ts b/server/tests/api/videos/videos-history.ts index aa0623f7d..8614078f1 100644 --- a/server/tests/api/videos/videos-history.ts +++ b/server/tests/api/videos/videos-history.ts @@ -6,17 +6,14 @@ import { HttpStatusCode } from '@shared/core-utils' import { cleanupTests, flushAndRunServer, - getVideosListWithToken, - getVideoWithToken, HistoryCommand, killallServers, reRunServer, ServerInfo, setAccessTokensToServers, - uploadVideo, wait } from '@shared/extra-utils' -import { Video, VideoDetails } from '@shared/models' +import { Video } from '@shared/models' const expect = chai.expect @@ -39,18 +36,18 @@ describe('Test videos history', function () { command = server.historyCommand { - const res = await uploadVideo(server.url, server.accessToken, { name: 'video 1' }) - video1UUID = res.body.video.uuid + const { uuid } = await server.videosCommand.upload({ attributes: { name: 'video 1' } }) + video1UUID = uuid } { - const res = await uploadVideo(server.url, server.accessToken, { name: 'video 2' }) - video2UUID = res.body.video.uuid + const { uuid } = await server.videosCommand.upload({ attributes: { name: 'video 2' } }) + video2UUID = uuid } { - const res = await uploadVideo(server.url, server.accessToken, { name: 'video 3' }) - video3UUID = res.body.video.uuid + const { uuid } = await server.videosCommand.upload({ attributes: { name: 'video 3' } }) + video3UUID = uuid } const user = { @@ -62,12 +59,10 @@ describe('Test videos history', function () { }) it('Should get videos, without watching history', async function () { - const res = await getVideosListWithToken(server.url, server.accessToken) - const videos: Video[] = res.body.data + const { data } = await server.videosCommand.listWithToken() - for (const video of videos) { - const resDetail = await getVideoWithToken(server.url, server.accessToken, video.id) - const videoDetails: VideoDetails = resDetail.body + for (const video of data) { + const videoDetails = await server.videosCommand.getWithToken({ id: video.id }) expect(video.userHistory).to.be.undefined expect(videoDetails.userHistory).to.be.undefined @@ -83,8 +78,8 @@ describe('Test videos history', function () { const videosOfVideos: Video[][] = [] { - const res = await getVideosListWithToken(server.url, server.accessToken) - videosOfVideos.push(res.body.data) + const { data } = await server.videosCommand.listWithToken() + videosOfVideos.push(data) } { @@ -107,24 +102,21 @@ describe('Test videos history', function () { } { - const resDetail = await getVideoWithToken(server.url, server.accessToken, video1UUID) - const videoDetails: VideoDetails = resDetail.body + const videoDetails = await server.videosCommand.getWithToken({ id: video1UUID }) expect(videoDetails.userHistory).to.not.be.undefined expect(videoDetails.userHistory.currentTime).to.equal(3) } { - const resDetail = await getVideoWithToken(server.url, server.accessToken, video2UUID) - const videoDetails: VideoDetails = resDetail.body + const videoDetails = await server.videosCommand.getWithToken({ id: video2UUID }) expect(videoDetails.userHistory).to.not.be.undefined expect(videoDetails.userHistory.currentTime).to.equal(8) } { - const resDetail = await getVideoWithToken(server.url, server.accessToken, video3UUID) - const videoDetails: VideoDetails = resDetail.body + const videoDetails = await server.videosCommand.getWithToken({ id: video3UUID }) expect(videoDetails.userHistory).to.be.undefined } diff --git a/server/tests/api/videos/videos-overview.ts b/server/tests/api/videos/videos-overview.ts index a2da2eaef..969393842 100644 --- a/server/tests/api/videos/videos-overview.ts +++ b/server/tests/api/videos/videos-overview.ts @@ -2,7 +2,7 @@ import 'mocha' import * as chai from 'chai' -import { cleanupTests, flushAndRunServer, ServerInfo, setAccessTokensToServers, uploadVideo, wait } from '@shared/extra-utils' +import { cleanupTests, flushAndRunServer, ServerInfo, setAccessTokensToServers, wait } from '@shared/extra-utils' import { VideosOverview } from '@shared/models' const expect = chai.expect @@ -35,10 +35,12 @@ describe('Test a videos overview', function () { await wait(3000) - await uploadVideo(server.url, server.accessToken, { - name: 'video 0', - category: 3, - tags: [ 'coucou1', 'coucou2' ] + await server.videosCommand.upload({ + attributes: { + name: 'video 0', + category: 3, + tags: [ 'coucou1', 'coucou2' ] + } }) const body = await server.overviewsCommand.getVideos({ page: 1 }) @@ -51,10 +53,12 @@ describe('Test a videos overview', function () { { for (let i = 1; i < 6; i++) { - await uploadVideo(server.url, server.accessToken, { - name: 'video ' + i, - category: 3, - tags: [ 'coucou1', 'coucou2' ] + await server.videosCommand.upload({ + attributes: { + name: 'video ' + i, + category: 3, + tags: [ 'coucou1', 'coucou2' ] + } }) } diff --git a/server/tests/api/videos/videos-views-cleaner.ts b/server/tests/api/videos/videos-views-cleaner.ts index b6cde6b50..7ded1bf38 100644 --- a/server/tests/api/videos/videos-views-cleaner.ts +++ b/server/tests/api/videos/videos-views-cleaner.ts @@ -10,8 +10,6 @@ import { reRunServer, ServerInfo, setAccessTokensToServers, - uploadVideoAndGetId, - viewVideo, wait, waitJobs } from '../../../../shared/extra-utils' @@ -32,15 +30,15 @@ describe('Test video views cleaner', function () { await doubleFollow(servers[0], servers[1]) - videoIdServer1 = (await uploadVideoAndGetId({ server: servers[0], videoName: 'video server 1' })).uuid - videoIdServer2 = (await uploadVideoAndGetId({ server: servers[1], videoName: 'video server 2' })).uuid + videoIdServer1 = (await servers[0].videosCommand.quickUpload({ name: 'video server 1' })).uuid + videoIdServer2 = (await servers[1].videosCommand.quickUpload({ name: 'video server 2' })).uuid await waitJobs(servers) - await viewVideo(servers[0].url, videoIdServer1) - await viewVideo(servers[1].url, videoIdServer1) - await viewVideo(servers[0].url, videoIdServer2) - await viewVideo(servers[1].url, videoIdServer2) + await servers[0].videosCommand.view({ id: videoIdServer1 }) + await servers[1].videosCommand.view({ id: videoIdServer1 }) + await servers[0].videosCommand.view({ id: videoIdServer2 }) + await servers[1].videosCommand.view({ id: videoIdServer2 }) await waitJobs(servers) }) diff --git a/server/tests/cli/create-import-video-file-job.ts b/server/tests/cli/create-import-video-file-job.ts index 8a23a94de..b1d9da242 100644 --- a/server/tests/cli/create-import-video-file-job.ts +++ b/server/tests/cli/create-import-video-file-job.ts @@ -2,19 +2,8 @@ import 'mocha' import * as chai from 'chai' -import { VideoFile } from '@shared/models/videos/video-file.model' -import { - cleanupTests, - doubleFollow, - flushAndRunMultipleServers, - getVideo, - getVideosList, - ServerInfo, - setAccessTokensToServers, - uploadVideo -} from '../../../shared/extra-utils' -import { waitJobs } from '../../../shared/extra-utils/server/jobs' -import { VideoDetails } from '../../../shared/models/videos' +import { cleanupTests, doubleFollow, flushAndRunMultipleServers, ServerInfo, setAccessTokensToServers, waitJobs } from '@shared/extra-utils' +import { VideoFile } from '@shared/models' const expect = chai.expect @@ -45,10 +34,15 @@ describe('Test create import video jobs', function () { await doubleFollow(servers[0], servers[1]) // Upload two videos for our needs - const res1 = await uploadVideo(servers[0].url, servers[0].accessToken, { name: 'video1' }) - video1UUID = res1.body.video.uuid - const res2 = await uploadVideo(servers[1].url, servers[1].accessToken, { name: 'video2' }) - video2UUID = res2.body.video.uuid + { + const { uuid } = await servers[0].videosCommand.upload({ attributes: { name: 'video1' } }) + video1UUID = uuid + } + + { + const { uuid } = await servers[1].videosCommand.upload({ attributes: { name: 'video2' } }) + video2UUID = uuid + } // Transcoding await waitJobs(servers) @@ -61,14 +55,14 @@ describe('Test create import video jobs', function () { await waitJobs(servers) for (const server of servers) { - const { data: videos } = (await getVideosList(server.url)).body + const { data: videos } = await server.videosCommand.list() expect(videos).to.have.lengthOf(2) const video = videos.find(({ uuid }) => uuid === video1UUID) - const videoDetail: VideoDetails = (await getVideo(server.url, video.uuid)).body + const videoDetails = await server.videosCommand.get({ id: video.uuid }) - expect(videoDetail.files).to.have.lengthOf(2) - const [ originalVideo, transcodedVideo ] = videoDetail.files + expect(videoDetails.files).to.have.lengthOf(2) + const [ originalVideo, transcodedVideo ] = videoDetails.files assertVideoProperties(originalVideo, 720, 'webm', 218910) assertVideoProperties(transcodedVideo, 480, 'webm', 69217) } @@ -81,14 +75,14 @@ describe('Test create import video jobs', function () { await waitJobs(servers) for (const server of servers) { - const { data: videos } = (await getVideosList(server.url)).body + const { data: videos } = await server.videosCommand.list() expect(videos).to.have.lengthOf(2) const video = videos.find(({ uuid }) => uuid === video2UUID) - const videoDetail: VideoDetails = (await getVideo(server.url, video.uuid)).body + const videoDetails = await server.videosCommand.get({ id: video.uuid }) - expect(videoDetail.files).to.have.lengthOf(4) - const [ originalVideo, transcodedVideo420, transcodedVideo320, transcodedVideo240 ] = videoDetail.files + expect(videoDetails.files).to.have.lengthOf(4) + const [ originalVideo, transcodedVideo420, transcodedVideo320, transcodedVideo240 ] = videoDetails.files assertVideoProperties(originalVideo, 720, 'ogv', 140849) assertVideoProperties(transcodedVideo420, 480, 'mp4') assertVideoProperties(transcodedVideo320, 360, 'mp4') @@ -103,14 +97,14 @@ describe('Test create import video jobs', function () { await waitJobs(servers) for (const server of servers) { - const { data: videos } = (await getVideosList(server.url)).body + const { data: videos } = await server.videosCommand.list() expect(videos).to.have.lengthOf(2) const video = videos.find(({ uuid }) => uuid === video1UUID) - const videoDetail: VideoDetails = (await getVideo(server.url, video.uuid)).body + const videoDetails = await server.videosCommand.get({ id: video.uuid }) - expect(videoDetail.files).to.have.lengthOf(2) - const [ video720, video480 ] = videoDetail.files + expect(videoDetails.files).to.have.lengthOf(2) + const [ video720, video480 ] = videoDetails.files assertVideoProperties(video720, 720, 'webm', 942961) assertVideoProperties(video480, 480, 'webm', 69217) } diff --git a/server/tests/cli/create-transcoding-job.ts b/server/tests/cli/create-transcoding-job.ts index e3211882d..f629306e6 100644 --- a/server/tests/cli/create-transcoding-job.ts +++ b/server/tests/cli/create-transcoding-job.ts @@ -6,14 +6,10 @@ import { cleanupTests, doubleFollow, flushAndRunMultipleServers, - getVideo, - getVideosList, ServerInfo, setAccessTokensToServers, - uploadVideo + waitJobs } from '../../../shared/extra-utils' -import { waitJobs } from '../../../shared/extra-utils/server/jobs' -import { VideoDetails } from '../../../shared/models/videos' const expect = chai.expect @@ -51,8 +47,8 @@ describe('Test create transcoding jobs', function () { await doubleFollow(servers[0], servers[1]) for (let i = 1; i <= 5; i++) { - const res = await uploadVideo(servers[0].url, servers[0].accessToken, { name: 'video' + i }) - videosUUID.push(res.body.video.uuid) + const { uuid } = await servers[0].videosCommand.upload({ attributes: { name: 'video' + i } }) + videosUUID.push(uuid) } await waitJobs(servers) @@ -62,13 +58,11 @@ describe('Test create transcoding jobs', function () { this.timeout(30000) for (const server of servers) { - const res = await getVideosList(server.url) - const videos = res.body.data - expect(videos).to.have.lengthOf(videosUUID.length) + const { data } = await server.videosCommand.list() + expect(data).to.have.lengthOf(videosUUID.length) - for (const video of videos) { - const res2 = await getVideo(server.url, video.uuid) - const videoDetail: VideoDetails = res2.body + for (const video of data) { + const videoDetail = await server.videosCommand.get({ id: video.uuid }) expect(videoDetail.files).to.have.lengthOf(1) expect(videoDetail.streamingPlaylists).to.have.lengthOf(0) } @@ -82,14 +76,12 @@ describe('Test create transcoding jobs', function () { await waitJobs(servers) for (const server of servers) { - const res = await getVideosList(server.url) - const videos = res.body.data + const { data } = await server.videosCommand.list() let infoHashes: { [id: number]: string } - for (const video of videos) { - const res2 = await getVideo(server.url, video.uuid) - const videoDetail: VideoDetails = res2.body + for (const video of data) { + const videoDetail = await server.videosCommand.get({ id: video.uuid }) if (video.uuid === videosUUID[1]) { expect(videoDetail.files).to.have.lengthOf(4) @@ -123,18 +115,16 @@ describe('Test create transcoding jobs', function () { await waitJobs(servers) for (const server of servers) { - const res = await getVideosList(server.url) - const videos = res.body.data - expect(videos).to.have.lengthOf(videosUUID.length) + const { data } = await server.videosCommand.list() + expect(data).to.have.lengthOf(videosUUID.length) - const res2 = await getVideo(server.url, videosUUID[0]) - const videoDetail: VideoDetails = res2.body + const videoDetails = await server.videosCommand.get({ id: videosUUID[0] }) - expect(videoDetail.files).to.have.lengthOf(2) - expect(videoDetail.files[0].resolution.id).to.equal(720) - expect(videoDetail.files[1].resolution.id).to.equal(480) + expect(videoDetails.files).to.have.lengthOf(2) + expect(videoDetails.files[0].resolution.id).to.equal(720) + expect(videoDetails.files[1].resolution.id).to.equal(480) - expect(videoDetail.streamingPlaylists).to.have.lengthOf(0) + expect(videoDetails.streamingPlaylists).to.have.lengthOf(0) } }) @@ -146,13 +136,12 @@ describe('Test create transcoding jobs', function () { await waitJobs(servers) for (const server of servers) { - const res = await getVideo(server.url, videosUUID[2]) - const videoDetail: VideoDetails = res.body + const videoDetails = await server.videosCommand.get({ id: videosUUID[2] }) - expect(videoDetail.files).to.have.lengthOf(1) - expect(videoDetail.streamingPlaylists).to.have.lengthOf(1) + expect(videoDetails.files).to.have.lengthOf(1) + expect(videoDetails.streamingPlaylists).to.have.lengthOf(1) - const files = videoDetail.streamingPlaylists[0].files + const files = videoDetails.streamingPlaylists[0].files expect(files).to.have.lengthOf(1) expect(files[0].resolution.id).to.equal(480) } @@ -166,10 +155,9 @@ describe('Test create transcoding jobs', function () { await waitJobs(servers) for (const server of servers) { - const res = await getVideo(server.url, videosUUID[2]) - const videoDetail: VideoDetails = res.body + const videoDetails = await server.videosCommand.get({ id: videosUUID[2] }) - const files = videoDetail.streamingPlaylists[0].files + const files = videoDetails.streamingPlaylists[0].files expect(files).to.have.lengthOf(1) expect(files[0].resolution.id).to.equal(480) } @@ -183,13 +171,12 @@ describe('Test create transcoding jobs', function () { await waitJobs(servers) for (const server of servers) { - const res = await getVideo(server.url, videosUUID[3]) - const videoDetail: VideoDetails = res.body + const videoDetails = await server.videosCommand.get({ id: videosUUID[3] }) - expect(videoDetail.files).to.have.lengthOf(1) - expect(videoDetail.streamingPlaylists).to.have.lengthOf(1) + expect(videoDetails.files).to.have.lengthOf(1) + expect(videoDetails.streamingPlaylists).to.have.lengthOf(1) - const files = videoDetail.streamingPlaylists[0].files + const files = videoDetails.streamingPlaylists[0].files expect(files).to.have.lengthOf(4) } }) @@ -205,12 +192,11 @@ describe('Test create transcoding jobs', function () { await waitJobs(servers) for (const server of servers) { - const res = await getVideo(server.url, videosUUID[4]) - const videoDetail: VideoDetails = res.body + const videoDetails = await server.videosCommand.get({ id: videosUUID[4] }) - expect(videoDetail.files).to.have.lengthOf(4) - expect(videoDetail.streamingPlaylists).to.have.lengthOf(1) - expect(videoDetail.streamingPlaylists[0].files).to.have.lengthOf(4) + expect(videoDetails.files).to.have.lengthOf(4) + expect(videoDetails.streamingPlaylists).to.have.lengthOf(1) + expect(videoDetails.streamingPlaylists[0].files).to.have.lengthOf(4) } }) diff --git a/server/tests/cli/optimize-old-videos.ts b/server/tests/cli/optimize-old-videos.ts index e369a3305..ef8603a33 100644 --- a/server/tests/cli/optimize-old-videos.ts +++ b/server/tests/cli/optimize-old-videos.ts @@ -8,16 +8,12 @@ import { doubleFollow, flushAndRunMultipleServers, generateHighBitrateVideo, - getVideo, - getVideosList, ServerInfo, setAccessTokensToServers, - uploadVideo, - viewVideo, - wait -} from '../../../shared/extra-utils' -import { waitJobs } from '../../../shared/extra-utils/server/jobs' -import { getMaxBitrate, Video, VideoDetails, VideoResolution } from '../../../shared/models/videos' + wait, + waitJobs +} from '@shared/extra-utils' +import { getMaxBitrate, VideoResolution } from '@shared/models' import { getVideoFileBitrate, getVideoFileFPS, getVideoFileResolution } from '../../helpers/ffprobe-utils' import { VIDEO_TRANSCODING_FPS } from '../../initializers/constants' @@ -45,8 +41,8 @@ describe('Test optimize old videos', function () { } // Upload two videos for our needs - await uploadVideo(servers[0].url, servers[0].accessToken, { name: 'video1', fixture: tempFixturePath }) - await uploadVideo(servers[0].url, servers[0].accessToken, { name: 'video2', fixture: tempFixturePath }) + await servers[0].videosCommand.upload({ attributes: { name: 'video1', fixture: tempFixturePath } }) + await servers[0].videosCommand.upload({ attributes: { name: 'video2', fixture: tempFixturePath } }) await waitJobs(servers) }) @@ -55,14 +51,12 @@ describe('Test optimize old videos', function () { this.timeout(30000) for (const server of servers) { - const res = await getVideosList(server.url) - const videos = res.body.data - expect(videos).to.have.lengthOf(2) - - for (const video of videos) { - const res2 = await getVideo(server.url, video.uuid) - const videoDetail: VideoDetails = res2.body - expect(videoDetail.files).to.have.lengthOf(1) + const { data } = await server.videosCommand.list() + expect(data).to.have.lengthOf(2) + + for (const video of data) { + const videoDetails = await server.videosCommand.get({ id: video.uuid }) + expect(videoDetails.files).to.have.lengthOf(1) } } }) @@ -74,24 +68,21 @@ describe('Test optimize old videos', function () { await waitJobs(servers) for (const server of servers) { - const res = await getVideosList(server.url) - const videos: Video[] = res.body.data - - expect(videos).to.have.lengthOf(2) + const { data } = await server.videosCommand.list() + expect(data).to.have.lengthOf(2) - for (const video of videos) { - await viewVideo(server.url, video.uuid) + for (const video of data) { + await server.videosCommand.view({ id: video.uuid }) // Refresh video await waitJobs(servers) await wait(5000) await waitJobs(servers) - const res2 = await getVideo(server.url, video.uuid) - const videosDetails: VideoDetails = res2.body + const videoDetails = await server.videosCommand.get({ id: video.uuid }) - expect(videosDetails.files).to.have.lengthOf(1) - const file = videosDetails.files[0] + expect(videoDetails.files).to.have.lengthOf(1) + const file = videoDetails.files[0] expect(file.size).to.be.below(8000000) diff --git a/server/tests/cli/peertube.ts b/server/tests/cli/peertube.ts index a0c149ac0..fe5f63191 100644 --- a/server/tests/cli/peertube.ts +++ b/server/tests/cli/peertube.ts @@ -2,7 +2,6 @@ import 'mocha' import { expect } from 'chai' -import { Video, VideoDetails } from '../../../shared' import { areHttpImportTestsDisabled, buildAbsoluteFixturePath, @@ -10,15 +9,10 @@ import { CLICommand, doubleFollow, flushAndRunServer, - getLocalIdByUUID, - getVideo, - getVideosList, ImportsCommand, - removeVideo, ServerInfo, setAccessTokensToServers, testHelloWorldRegisteredSettings, - uploadVideoAndGetId, waitJobs } from '../../../shared/extra-utils' @@ -109,14 +103,10 @@ describe('Test CLI wrapper', function () { }) it('Should have the video uploaded', async function () { - const res = await getVideosList(server.url) - - expect(res.body.total).to.equal(1) - - const videos: Video[] = res.body.data - - const video: VideoDetails = (await getVideo(server.url, videos[0].uuid)).body + const { total, data } = await server.videosCommand.list() + expect(total).to.equal(1) + const video = await server.videosCommand.get({ id: data[0].uuid }) expect(video.name).to.equal('test upload') expect(video.support).to.equal('support_text') expect(video.channel.name).to.equal('user_channel') @@ -138,21 +128,19 @@ describe('Test CLI wrapper', function () { await waitJobs([ server ]) - const res = await getVideosList(server.url) - - expect(res.body.total).to.equal(2) + const { total, data } = await server.videosCommand.list() + expect(total).to.equal(2) - const videos: Video[] = res.body.data - const video = videos.find(v => v.name === 'small video - youtube') + const video = data.find(v => v.name === 'small video - youtube') expect(video).to.not.be.undefined - const videoDetails: VideoDetails = (await getVideo(server.url, video.id)).body + const videoDetails = await server.videosCommand.get({ id: video.id }) expect(videoDetails.channel.name).to.equal('user_channel') expect(videoDetails.support).to.equal('super support text') expect(videoDetails.nsfw).to.be.false // So we can reimport it - await removeVideo(server.url, userAccessToken, video.id) + await server.videosCommand.remove({ token: userAccessToken, id: video.id }) }) it('Should import and override some imported attributes', async function () { @@ -167,14 +155,13 @@ describe('Test CLI wrapper', function () { await waitJobs([ server ]) { - const res = await getVideosList(server.url) - expect(res.body.total).to.equal(2) + const { total, data } = await server.videosCommand.list() + expect(total).to.equal(2) - const videos: Video[] = res.body.data - const video = videos.find(v => v.name === 'toto') + const video = data.find(v => v.name === 'toto') expect(video).to.not.be.undefined - const videoDetails: VideoDetails = (await getVideo(server.url, video.id)).body + const videoDetails = await server.videosCommand.get({ id: video.id }) expect(videoDetails.channel.name).to.equal('user_channel') expect(videoDetails.support).to.equal('support') expect(videoDetails.nsfw).to.be.true @@ -238,10 +225,10 @@ describe('Test CLI wrapper', function () { servers = [ server, anotherServer ] await waitJobs(servers) - const uuid = (await uploadVideoAndGetId({ server: anotherServer, videoName: 'super video' })).uuid + const { uuid } = await anotherServer.videosCommand.quickUpload({ name: 'super video' }) await waitJobs(servers) - video1Server2 = await getLocalIdByUUID(server.url, uuid) + video1Server2 = await server.videosCommand.getId({ uuid }) }) it('Should add a redundancy', async function () { diff --git a/server/tests/cli/prune-storage.ts b/server/tests/cli/prune-storage.ts index b45049964..a4556312b 100644 --- a/server/tests/cli/prune-storage.ts +++ b/server/tests/cli/prune-storage.ts @@ -16,7 +16,6 @@ import { ServerInfo, setAccessTokensToServers, setDefaultVideoChannel, - uploadVideo, wait, waitJobs } from '@shared/extra-utils' @@ -69,8 +68,8 @@ describe('Test prune storage scripts', function () { await setDefaultVideoChannel(servers) for (const server of servers) { - await uploadVideo(server.url, server.accessToken, { name: 'video 1' }) - await uploadVideo(server.url, server.accessToken, { name: 'video 2' }) + await server.videosCommand.upload({ attributes: { name: 'video 1' } }) + await server.videosCommand.upload({ attributes: { name: 'video 2' } }) await server.usersCommand.updateMyAvatar({ fixture: 'avatar.png' }) diff --git a/server/tests/cli/regenerate-thumbnails.ts b/server/tests/cli/regenerate-thumbnails.ts index 68a4711b6..d59520783 100644 --- a/server/tests/cli/regenerate-thumbnails.ts +++ b/server/tests/cli/regenerate-thumbnails.ts @@ -2,29 +2,30 @@ import 'mocha' import { expect } from 'chai' import { writeFile } from 'fs-extra' import { basename, join } from 'path' -import { Video, VideoDetails } from '@shared/models' +import { HttpStatusCode } from '@shared/core-utils' +import { Video } from '@shared/models' import { cleanupTests, doubleFollow, flushAndRunMultipleServers, - getVideo, makeRawRequest, ServerInfo, setAccessTokensToServers, - uploadVideoAndGetId, waitJobs } from '../../../shared/extra-utils' -import { HttpStatusCode } from '@shared/core-utils' async function testThumbnail (server: ServerInfo, videoId: number | string) { - const res = await getVideo(server.url, videoId) - const video: VideoDetails = res.body + const video = await server.videosCommand.get({ id: videoId }) - const res1 = await makeRawRequest(join(server.url, video.thumbnailPath), HttpStatusCode.OK_200) - expect(res1.body).to.not.have.lengthOf(0) + const requests = [ + makeRawRequest(join(server.url, video.thumbnailPath), HttpStatusCode.OK_200), + makeRawRequest(join(server.url, video.thumbnailPath), HttpStatusCode.OK_200) + ] - const res2 = await makeRawRequest(join(server.url, video.thumbnailPath), HttpStatusCode.OK_200) - expect(res2.body).to.not.have.lengthOf(0) + for (const req of requests) { + const res = await req + expect(res.body).to.not.have.lengthOf(0) + } } describe('Test regenerate thumbnails script', function () { @@ -46,20 +47,20 @@ describe('Test regenerate thumbnails script', function () { await doubleFollow(servers[0], servers[1]) { - const videoUUID1 = (await uploadVideoAndGetId({ server: servers[0], videoName: 'video 1' })).uuid - video1 = await (getVideo(servers[0].url, videoUUID1).then(res => res.body)) + const videoUUID1 = (await servers[0].videosCommand.quickUpload({ name: 'video 1' })).uuid + video1 = await servers[0].videosCommand.get({ id: videoUUID1 }) thumbnail1Path = join(servers[0].serversCommand.buildDirectory('thumbnails'), basename(video1.thumbnailPath)) - const videoUUID2 = (await uploadVideoAndGetId({ server: servers[0], videoName: 'video 2' })).uuid - video2 = await (getVideo(servers[0].url, videoUUID2).then(res => res.body)) + const videoUUID2 = (await servers[0].videosCommand.quickUpload({ name: 'video 2' })).uuid + video2 = await servers[0].videosCommand.get({ id: videoUUID2 }) } { - const videoUUID = (await uploadVideoAndGetId({ server: servers[1], videoName: 'video 3' })).uuid + const videoUUID = (await servers[1].videosCommand.quickUpload({ name: 'video 3' })).uuid await waitJobs(servers) - remoteVideo = await (getVideo(servers[0].url, videoUUID).then(res => res.body)) + remoteVideo = await servers[0].videosCommand.get({ id: videoUUID }) thumbnailRemotePath = join(servers[0].serversCommand.buildDirectory('thumbnails'), basename(remoteVideo.thumbnailPath)) } diff --git a/server/tests/cli/update-host.ts b/server/tests/cli/update-host.ts index b857fcf28..d90b4a64d 100644 --- a/server/tests/cli/update-host.ts +++ b/server/tests/cli/update-host.ts @@ -5,18 +5,14 @@ import { expect } from 'chai' import { cleanupTests, flushAndRunServer, - getVideo, - getVideosList, killallServers, makeActivityPubGetRequest, parseTorrentVideo, reRunServer, ServerInfo, setAccessTokensToServers, - uploadVideo, waitJobs } from '@shared/extra-utils' -import { VideoDetails } from '@shared/models' describe('Test update host scripts', function () { let server: ServerInfo @@ -34,10 +30,8 @@ describe('Test update host scripts', function () { await setAccessTokensToServers([ server ]) // Upload two videos for our needs - const videoAttributes = {} - const resVideo1 = await uploadVideo(server.url, server.accessToken, videoAttributes) - const video1UUID = resVideo1.body.video.uuid - await uploadVideo(server.url, server.accessToken, videoAttributes) + const { uuid: video1UUID } = await server.videosCommand.upload() + await server.videosCommand.upload() // Create a user await server.usersCommand.create({ username: 'toto', password: 'coucou' }) @@ -68,16 +62,15 @@ describe('Test update host scripts', function () { }) it('Should have updated videos url', async function () { - const res = await getVideosList(server.url) - expect(res.body.total).to.equal(2) + const { total, data } = await server.videosCommand.list() + expect(total).to.equal(2) - for (const video of res.body.data) { + for (const video of data) { const { body } = await makeActivityPubGetRequest(server.url, '/videos/watch/' + video.uuid) expect(body.id).to.equal('http://localhost:9002/videos/watch/' + video.uuid) - const res = await getVideo(server.url, video.uuid) - const videoDetails: VideoDetails = res.body + const videoDetails = await server.videosCommand.get({ id: video.uuid }) expect(videoDetails.trackerUrls[0]).to.include(server.host) expect(videoDetails.streamingPlaylists[0].playlistUrl).to.include(server.host) @@ -111,13 +104,11 @@ describe('Test update host scripts', function () { it('Should have updated torrent hosts', async function () { this.timeout(30000) - const res = await getVideosList(server.url) - const videos = res.body.data - expect(videos).to.have.lengthOf(2) + const { data } = await server.videosCommand.list() + expect(data).to.have.lengthOf(2) - for (const video of videos) { - const res2 = await getVideo(server.url, video.id) - const videoDetails: VideoDetails = res2.body + for (const video of data) { + const videoDetails = await server.videosCommand.get({ id: video.id }) expect(videoDetails.files).to.have.lengthOf(4) diff --git a/server/tests/client.ts b/server/tests/client.ts index 96403da37..e91d4c671 100644 --- a/server/tests/client.ts +++ b/server/tests/client.ts @@ -9,13 +9,11 @@ import { cleanupTests, doubleFollow, flushAndRunMultipleServers, - getVideosList, makeGetRequest, makeHTMLRequest, ServerInfo, setAccessTokensToServers, setDefaultVideoChannel, - uploadVideo, waitJobs } from '../../shared/extra-utils' @@ -68,36 +66,41 @@ describe('Test a client controllers', function () { // Video - const videoAttributes = { name: videoName, description: videoDescription } - await uploadVideo(servers[0].url, servers[0].accessToken, videoAttributes) + { + const attributes = { name: videoName, description: videoDescription } + await servers[0].videosCommand.upload({ attributes }) - const resVideosRequest = await getVideosList(servers[0].url) - const videos = resVideosRequest.body.data - expect(videos.length).to.equal(1) + const { data } = await servers[0].videosCommand.list() + expect(data.length).to.equal(1) - const video = videos[0] - servers[0].video = video - videoIds = [ video.id, video.uuid, video.shortUUID ] + const video = data[0] + servers[0].video = video + videoIds = [ video.id, video.uuid, video.shortUUID ] + } // Playlist - const attributes = { - displayName: playlistName, - description: playlistDescription, - privacy: VideoPlaylistPrivacy.PUBLIC, - videoChannelId: servers[0].videoChannel.id - } + { + const attributes = { + displayName: playlistName, + description: playlistDescription, + privacy: VideoPlaylistPrivacy.PUBLIC, + videoChannelId: servers[0].videoChannel.id + } - playlist = await servers[0].playlistsCommand.create({ attributes }) - playlistIds = [ playlist.id, playlist.shortUUID, playlist.uuid ] + playlist = await servers[0].playlistsCommand.create({ attributes }) + playlistIds = [ playlist.id, playlist.shortUUID, playlist.uuid ] - await servers[0].playlistsCommand.addElement({ playlistId: playlist.shortUUID, attributes: { videoId: video.id } }) + await servers[0].playlistsCommand.addElement({ playlistId: playlist.shortUUID, attributes: { videoId: servers[0].video.id } }) + } // Account - await servers[0].usersCommand.updateMe({ description: 'my account description' }) + { + await servers[0].usersCommand.updateMe({ description: 'my account description' }) - account = await servers[0].accountsCommand.get({ accountName: `${servers[0].user.username}@${servers[0].host}` }) + account = await servers[0].accountsCommand.get({ accountName: `${servers[0].user.username}@${servers[0].host}` }) + } await waitJobs(servers) }) diff --git a/server/tests/external-plugins/auth-ldap.ts b/server/tests/external-plugins/auth-ldap.ts index d99b3badc..b626ab2bb 100644 --- a/server/tests/external-plugins/auth-ldap.ts +++ b/server/tests/external-plugins/auth-ldap.ts @@ -3,7 +3,7 @@ import 'mocha' import { expect } from 'chai' import { HttpStatusCode } from '@shared/core-utils' -import { cleanupTests, flushAndRunServer, ServerInfo, setAccessTokensToServers, uploadVideo } from '@shared/extra-utils' +import { cleanupTests, flushAndRunServer, ServerInfo, setAccessTokensToServers } from '@shared/extra-utils' describe('Official plugin auth-ldap', function () { let server: ServerInfo @@ -77,7 +77,7 @@ describe('Official plugin auth-ldap', function () { }) it('Should upload a video', async function () { - await uploadVideo(server.url, accessToken, { name: 'my super video' }) + await server.videosCommand.upload({ token: accessToken, attributes: { name: 'my super video' } }) }) it('Should not be able to login if the user is banned', async function () { diff --git a/server/tests/external-plugins/auto-block-videos.ts b/server/tests/external-plugins/auto-block-videos.ts index f4b55522a..1cce15a2f 100644 --- a/server/tests/external-plugins/auto-block-videos.ts +++ b/server/tests/external-plugins/auto-block-videos.ts @@ -2,27 +2,23 @@ import 'mocha' import { expect } from 'chai' -import { Video } from '@shared/models' -import { - doubleFollow, - getVideosList, - MockBlocklist, - setAccessTokensToServers, - uploadVideoAndGetId, - wait -} from '../../../shared/extra-utils' import { cleanupTests, + doubleFollow, flushAndRunMultipleServers, killallServers, + MockBlocklist, reRunServer, - ServerInfo -} from '../../../shared/extra-utils/server/servers' + ServerInfo, + setAccessTokensToServers, + wait +} from '@shared/extra-utils' +import { Video } from '@shared/models' async function check (server: ServerInfo, videoUUID: string, exists = true) { - const res = await getVideosList(server.url) + const { data } = await server.videosCommand.list() - const video = res.body.data.find(v => v.uuid === videoUUID) + const video = data.find(v => v.uuid === videoUUID) if (exists) expect(video).to.not.be.undefined else expect(video).to.be.undefined @@ -48,19 +44,19 @@ describe('Official plugin auto-block videos', function () { blocklistServer = new MockBlocklist() port = await blocklistServer.initialize() - await uploadVideoAndGetId({ server: servers[0], videoName: 'video server 1' }) - await uploadVideoAndGetId({ server: servers[1], videoName: 'video server 2' }) - await uploadVideoAndGetId({ server: servers[1], videoName: 'video 2 server 2' }) - await uploadVideoAndGetId({ server: servers[1], videoName: 'video 3 server 2' }) + await await servers[0].videosCommand.quickUpload({ name: 'video server 1' }) + await await servers[1].videosCommand.quickUpload({ name: 'video server 2' }) + await await servers[1].videosCommand.quickUpload({ name: 'video 2 server 2' }) + await await servers[1].videosCommand.quickUpload({ name: 'video 3 server 2' }) { - const res = await getVideosList(servers[0].url) - server1Videos = res.body.data.map(v => Object.assign(v, { url: servers[0].url + '/videos/watch/' + v.uuid })) + const { data } = await servers[0].videosCommand.list() + server1Videos = data.map(v => Object.assign(v, { url: servers[0].url + '/videos/watch/' + v.uuid })) } { - const res = await getVideosList(servers[1].url) - server2Videos = res.body.data.map(v => Object.assign(v, { url: servers[1].url + '/videos/watch/' + v.uuid })) + const { data } = await servers[1].videosCommand.list() + server2Videos = data.map(v => Object.assign(v, { url: servers[1].url + '/videos/watch/' + v.uuid })) } await doubleFollow(servers[0], servers[1]) diff --git a/server/tests/external-plugins/auto-mute.ts b/server/tests/external-plugins/auto-mute.ts index 844023b83..81a96744e 100644 --- a/server/tests/external-plugins/auto-mute.ts +++ b/server/tests/external-plugins/auto-mute.ts @@ -7,14 +7,12 @@ import { cleanupTests, doubleFollow, flushAndRunMultipleServers, - getVideosList, killallServers, makeGetRequest, MockBlocklist, reRunServer, ServerInfo, setAccessTokensToServers, - uploadVideoAndGetId, wait } from '@shared/extra-utils' @@ -37,8 +35,8 @@ describe('Official plugin auto-mute', function () { blocklistServer = new MockBlocklist() port = await blocklistServer.initialize() - await uploadVideoAndGetId({ server: servers[0], videoName: 'video server 1' }) - await uploadVideoAndGetId({ server: servers[1], videoName: 'video server 2' }) + await await servers[0].videosCommand.quickUpload({ name: 'video server 1' }) + await await servers[1].videosCommand.quickUpload({ name: 'video server 2' }) await doubleFollow(servers[0], servers[1]) }) @@ -66,8 +64,8 @@ describe('Official plugin auto-mute', function () { await wait(2000) - const res = await getVideosList(servers[0].url) - expect(res.body.total).to.equal(1) + const { total } = await servers[0].videosCommand.list() + expect(total).to.equal(1) }) it('Should remove a server blocklist', async function () { @@ -84,8 +82,8 @@ describe('Official plugin auto-mute', function () { await wait(2000) - const res = await getVideosList(servers[0].url) - expect(res.body.total).to.equal(2) + const { total } = await servers[0].videosCommand.list() + expect(total).to.equal(2) }) it('Should add an account blocklist', async function () { @@ -101,8 +99,8 @@ describe('Official plugin auto-mute', function () { await wait(2000) - const res = await getVideosList(servers[0].url) - expect(res.body.total).to.equal(1) + const { total } = await servers[0].videosCommand.list() + expect(total).to.equal(1) }) it('Should remove an account blocklist', async function () { @@ -119,8 +117,8 @@ describe('Official plugin auto-mute', function () { await wait(2000) - const res = await getVideosList(servers[0].url) - expect(res.body.total).to.equal(2) + const { total } = await servers[0].videosCommand.list() + expect(total).to.equal(2) }) it('Should auto mute an account, manually unmute it and do not remute it automatically', async function () { @@ -140,15 +138,15 @@ describe('Official plugin auto-mute', function () { await wait(2000) { - const res = await getVideosList(servers[0].url) - expect(res.body.total).to.equal(1) + const { total } = await servers[0].videosCommand.list() + expect(total).to.equal(1) } await servers[0].blocklistCommand.removeFromServerBlocklist({ account }) { - const res = await getVideosList(servers[0].url) - expect(res.body.total).to.equal(2) + const { total } = await servers[0].videosCommand.list() + expect(total).to.equal(2) } await killallServers([ servers[0] ]) @@ -156,8 +154,8 @@ describe('Official plugin auto-mute', function () { await wait(2000) { - const res = await getVideosList(servers[0].url) - expect(res.body.total).to.equal(2) + const { total } = await servers[0].videosCommand.list() + expect(total).to.equal(2) } }) @@ -215,8 +213,8 @@ describe('Official plugin auto-mute', function () { await wait(2000) for (const server of servers) { - const res = await getVideosList(server.url) - expect(res.body.total).to.equal(1) + const { total } = await server.videosCommand.list() + expect(total).to.equal(1) } }) diff --git a/server/tests/feeds/feeds.ts b/server/tests/feeds/feeds.ts index 18ce8f7c5..c66cdde1b 100644 --- a/server/tests/feeds/feeds.ts +++ b/server/tests/feeds/feeds.ts @@ -11,8 +11,6 @@ import { flushAndRunServer, ServerInfo, setAccessTokensToServers, - uploadVideo, - uploadVideoAndGetId, waitJobs } from '@shared/extra-utils' import { VideoPrivacy } from '@shared/models' @@ -68,28 +66,26 @@ describe('Test syndication feeds', () => { } { - await uploadVideo(servers[0].url, userAccessToken, { name: 'user video' }) + await servers[0].videosCommand.upload({ token: userAccessToken, attributes: { name: 'user video' } }) } { - const videoAttributes = { + const attributes = { name: 'my super name for server 1', description: 'my super description for server 1', fixture: 'video_short.webm' } - const res = await uploadVideo(servers[0].url, servers[0].accessToken, videoAttributes) - const videoId = res.body.video.id + const { id } = await servers[0].videosCommand.upload({ attributes }) - await servers[0].commentsCommand.createThread({ videoId, text: 'super comment 1' }) - await servers[0].commentsCommand.createThread({ videoId, text: 'super comment 2' }) + await servers[0].commentsCommand.createThread({ videoId: id, text: 'super comment 1' }) + await servers[0].commentsCommand.createThread({ videoId: id, text: 'super comment 2' }) } { - const videoAttributes = { name: 'unlisted video', privacy: VideoPrivacy.UNLISTED } - const res = await uploadVideo(servers[0].url, servers[0].accessToken, videoAttributes) - const videoId = res.body.video.id + const attributes = { name: 'unlisted video', privacy: VideoPrivacy.UNLISTED } + const { id } = await servers[0].videosCommand.upload({ attributes }) - await servers[0].commentsCommand.createThread({ videoId, text: 'comment on unlisted video' }) + await servers[0].commentsCommand.createThread({ videoId: id, text: 'comment on unlisted video' }) } await waitJobs(servers) @@ -218,7 +214,7 @@ describe('Test syndication feeds', () => { it('Should correctly have videos feed with HLS only', async function () { this.timeout(120000) - await uploadVideo(serverHLSOnly.url, serverHLSOnly.accessToken, { name: 'hls only video' }) + await serverHLSOnly.videosCommand.upload({ attributes: { name: 'hls only video' } }) await waitJobs([ serverHLSOnly ]) @@ -265,7 +261,7 @@ describe('Test syndication feeds', () => { await servers[1].blocklistCommand.removeFromServerBlocklist({ account: remoteHandle }) { - const videoUUID = (await uploadVideoAndGetId({ server: servers[1], videoName: 'server 2' })).uuid + const videoUUID = (await servers[1].videosCommand.quickUpload({ name: 'server 2' })).uuid await waitJobs(servers) await servers[0].commentsCommand.createThread({ videoId: videoUUID, text: 'super comment' }) await waitJobs(servers) diff --git a/server/tests/misc-endpoints.ts b/server/tests/misc-endpoints.ts index 84bdcaabf..b5b10bd5e 100644 --- a/server/tests/misc-endpoints.ts +++ b/server/tests/misc-endpoints.ts @@ -3,15 +3,8 @@ import 'mocha' import * as chai from 'chai' import { HttpStatusCode } from '@shared/core-utils' -import { - cleanupTests, - flushAndRunServer, - makeGetRequest, - ServerInfo, - setAccessTokensToServers, - uploadVideo -} from '../../shared/extra-utils' -import { VideoPrivacy } from '../../shared/models/videos' +import { cleanupTests, flushAndRunServer, makeGetRequest, ServerInfo, setAccessTokensToServers } from '@shared/extra-utils' +import { VideoPrivacy } from '@shared/models' const expect = chai.expect @@ -165,9 +158,9 @@ describe('Test misc endpoints', function () { it('Should add videos, channel and accounts and get sitemap', async function () { this.timeout(35000) - await uploadVideo(server.url, server.accessToken, { name: 'video 1', nsfw: false }) - await uploadVideo(server.url, server.accessToken, { name: 'video 2', nsfw: false }) - await uploadVideo(server.url, server.accessToken, { name: 'video 3', privacy: VideoPrivacy.PRIVATE }) + await server.videosCommand.upload({ attributes: { name: 'video 1', nsfw: false } }) + await server.videosCommand.upload({ attributes: { name: 'video 2', nsfw: false } }) + await server.videosCommand.upload({ attributes: { name: 'video 3', privacy: VideoPrivacy.PRIVATE } }) await server.channelsCommand.create({ attributes: { name: 'channel1', displayName: 'channel 1' } }) await server.channelsCommand.create({ attributes: { name: 'channel2', displayName: 'channel 2' } }) diff --git a/server/tests/plugins/action-hooks.ts b/server/tests/plugins/action-hooks.ts index b156f6b60..9e12c8aa7 100644 --- a/server/tests/plugins/action-hooks.ts +++ b/server/tests/plugins/action-hooks.ts @@ -9,10 +9,7 @@ import { reRunServer, ServerInfo, setAccessTokensToServers, - setDefaultVideoChannel, - updateVideo, - uploadVideo, - viewVideo + setDefaultVideoChannel } from '@shared/extra-utils' import { ServerHookName, VideoPlaylistPrivacy, VideoPrivacy } from '@shared/models' @@ -52,20 +49,20 @@ describe('Test plugin action hooks', function () { describe('Videos hooks', function () { it('Should run action:api.video.uploaded', async function () { - const res = await uploadVideo(servers[0].url, servers[0].accessToken, { name: 'video' }) - videoUUID = res.body.video.uuid + const { uuid } = await servers[0].videosCommand.upload({ attributes: { name: 'video' } }) + videoUUID = uuid await checkHook('action:api.video.uploaded') }) it('Should run action:api.video.updated', async function () { - await updateVideo(servers[0].url, servers[0].accessToken, videoUUID, { name: 'video updated' }) + await servers[0].videosCommand.update({ id: videoUUID, attributes: { name: 'video updated' } }) await checkHook('action:api.video.updated') }) it('Should run action:api.video.viewed', async function () { - await viewVideo(servers[0].url, videoUUID) + await servers[0].videosCommand.view({ id: videoUUID }) await checkHook('action:api.video.viewed') }) @@ -170,8 +167,8 @@ describe('Test plugin action hooks', function () { } { - const res = await uploadVideo(servers[0].url, servers[0].accessToken, { name: 'my super name' }) - videoId = res.body.video.id + const { id } = await servers[0].videosCommand.upload({ attributes: { name: 'my super name' } }) + videoId = id } }) diff --git a/server/tests/plugins/filter-hooks.ts b/server/tests/plugins/filter-hooks.ts index c82025f6a..e82aa3bfb 100644 --- a/server/tests/plugins/filter-hooks.ts +++ b/server/tests/plugins/filter-hooks.ts @@ -7,22 +7,12 @@ import { cleanupTests, doubleFollow, flushAndRunMultipleServers, - getAccountVideos, - getMyVideos, - getVideo, - getVideoChannelVideos, - getVideosList, - getVideosListPagination, - getVideoWithToken, ImportsCommand, makeRawRequest, PluginsCommand, ServerInfo, setAccessTokensToServers, setDefaultVideoChannel, - updateVideo, - uploadVideo, - uploadVideoAndGetId, waitJobs } from '@shared/extra-utils' import { VideoDetails, VideoImportState, VideoPlaylist, VideoPlaylistPrivacy, VideoPrivacy } from '@shared/models' @@ -46,11 +36,11 @@ describe('Test plugin filter hooks', function () { await servers[0].pluginsCommand.install({ path: PluginsCommand.getPluginTestPath('-filter-translations') }) for (let i = 0; i < 10; i++) { - await uploadVideo(servers[0].url, servers[0].accessToken, { name: 'default video ' + i }) + await servers[0].videosCommand.upload({ attributes: { name: 'default video ' + i } }) } - const res = await getVideosList(servers[0].url) - videoUUID = res.body.data[0].uuid + const { data } = await servers[0].videosCommand.list() + videoUUID = data[0].uuid await servers[0].configCommand.updateCustomSubConfig({ newConfig: { @@ -67,69 +57,68 @@ describe('Test plugin filter hooks', function () { }) it('Should run filter:api.videos.list.params', async function () { - const res = await getVideosListPagination(servers[0].url, 0, 2) + const { data } = await servers[0].videosCommand.list({ start: 0, count: 2 }) // 2 plugins do +1 to the count parameter - expect(res.body.data).to.have.lengthOf(4) + expect(data).to.have.lengthOf(4) }) it('Should run filter:api.videos.list.result', async function () { - const res = await getVideosListPagination(servers[0].url, 0, 0) + const { total } = await servers[0].videosCommand.list({ start: 0, count: 0 }) // Plugin do +1 to the total result - expect(res.body.total).to.equal(11) + expect(total).to.equal(11) }) it('Should run filter:api.accounts.videos.list.params', async function () { - const res = await getAccountVideos(servers[0].url, servers[0].accessToken, 'root', 0, 2) + const { data } = await servers[0].videosCommand.listByAccount({ accountName: 'root', start: 0, count: 2 }) // 1 plugin do +1 to the count parameter - expect(res.body.data).to.have.lengthOf(3) + expect(data).to.have.lengthOf(3) }) it('Should run filter:api.accounts.videos.list.result', async function () { - const res = await getAccountVideos(servers[0].url, servers[0].accessToken, 'root', 0, 2) + const { total } = await servers[0].videosCommand.listByAccount({ accountName: 'root', start: 0, count: 2 }) // Plugin do +2 to the total result - expect(res.body.total).to.equal(12) + expect(total).to.equal(12) }) it('Should run filter:api.video-channels.videos.list.params', async function () { - const res = await getVideoChannelVideos(servers[0].url, servers[0].accessToken, 'root_channel', 0, 2) + const { data } = await servers[0].videosCommand.listByChannel({ videoChannelName: 'root_channel', start: 0, count: 2 }) // 1 plugin do +3 to the count parameter - expect(res.body.data).to.have.lengthOf(5) + expect(data).to.have.lengthOf(5) }) it('Should run filter:api.video-channels.videos.list.result', async function () { - const res = await getVideoChannelVideos(servers[0].url, servers[0].accessToken, 'root_channel', 0, 2) + const { total } = await servers[0].videosCommand.listByChannel({ videoChannelName: 'root_channel', start: 0, count: 2 }) // Plugin do +3 to the total result - expect(res.body.total).to.equal(13) + expect(total).to.equal(13) }) it('Should run filter:api.user.me.videos.list.params', async function () { - const res = await getMyVideos(servers[0].url, servers[0].accessToken, 0, 2) + const { data } = await servers[0].videosCommand.listMyVideos({ start: 0, count: 2 }) // 1 plugin do +4 to the count parameter - expect(res.body.data).to.have.lengthOf(6) + expect(data).to.have.lengthOf(6) }) it('Should run filter:api.user.me.videos.list.result', async function () { - const res = await getMyVideos(servers[0].url, servers[0].accessToken, 0, 2) + const { total } = await servers[0].videosCommand.listMyVideos({ start: 0, count: 2 }) // Plugin do +4 to the total result - expect(res.body.total).to.equal(14) + expect(total).to.equal(14) }) it('Should run filter:api.video.get.result', async function () { - const res = await getVideo(servers[0].url, videoUUID) - - expect(res.body.name).to.contain('<3') + const video = await servers[0].videosCommand.get({ id: videoUUID }) + expect(video.name).to.contain('<3') }) it('Should run filter:api.video.upload.accept.result', async function () { - await uploadVideo(servers[0].url, servers[0].accessToken, { name: 'video with bad word' }, HttpStatusCode.FORBIDDEN_403) + await servers[0].videosCommand.upload({ attributes: { name: 'video with bad word' }, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) it('Should run filter:api.live-video.create.accept.result', async function () { @@ -270,14 +259,13 @@ describe('Test plugin filter hooks', function () { describe('Should run filter:video.auto-blacklist.result', function () { async function checkIsBlacklisted (id: number | string, value: boolean) { - const res = await getVideoWithToken(servers[0].url, servers[0].accessToken, id) - const video: VideoDetails = res.body + const video = await servers[0].videosCommand.getWithToken({ id }) expect(video.blacklisted).to.equal(value) } it('Should blacklist on upload', async function () { - const res = await uploadVideo(servers[0].url, servers[0].accessToken, { name: 'video please blacklist me' }) - await checkIsBlacklisted(res.body.video.uuid, true) + const { uuid } = await servers[0].videosCommand.upload({ attributes: { name: 'video please blacklist me' } }) + await checkIsBlacklisted(uuid, true) }) it('Should blacklist on import', async function () { @@ -293,36 +281,34 @@ describe('Test plugin filter hooks', function () { }) it('Should blacklist on update', async function () { - const res = await uploadVideo(servers[0].url, servers[0].accessToken, { name: 'video' }) - const videoId = res.body.video.uuid - await checkIsBlacklisted(videoId, false) + const { uuid } = await servers[0].videosCommand.upload({ attributes: { name: 'video' } }) + await checkIsBlacklisted(uuid, false) - await updateVideo(servers[0].url, servers[0].accessToken, videoId, { name: 'please blacklist me' }) - await checkIsBlacklisted(videoId, true) + await servers[0].videosCommand.update({ id: uuid, attributes: { name: 'please blacklist me' } }) + await checkIsBlacklisted(uuid, true) }) it('Should blacklist on remote upload', async function () { this.timeout(120000) - const res = await uploadVideo(servers[1].url, servers[1].accessToken, { name: 'remote please blacklist me' }) + const { uuid } = await servers[1].videosCommand.upload({ attributes: { name: 'remote please blacklist me' } }) await waitJobs(servers) - await checkIsBlacklisted(res.body.video.uuid, true) + await checkIsBlacklisted(uuid, true) }) it('Should blacklist on remote update', async function () { this.timeout(120000) - const res = await uploadVideo(servers[1].url, servers[1].accessToken, { name: 'video' }) + const { uuid } = await servers[1].videosCommand.upload({ attributes: { name: 'video' } }) await waitJobs(servers) - const videoId = res.body.video.uuid - await checkIsBlacklisted(videoId, false) + await checkIsBlacklisted(uuid, false) - await updateVideo(servers[1].url, servers[1].accessToken, videoId, { name: 'please blacklist me' }) + await servers[1].videosCommand.update({ id: uuid, attributes: { name: 'please blacklist me' } }) await waitJobs(servers) - await checkIsBlacklisted(videoId, true) + await checkIsBlacklisted(uuid, true) }) }) @@ -370,15 +356,14 @@ describe('Test plugin filter hooks', function () { const uuids: string[] = [] for (const name of [ 'bad torrent', 'bad file', 'bad playlist file' ]) { - const uuid = (await uploadVideoAndGetId({ server: servers[0], videoName: name })).uuid + const uuid = (await servers[0].videosCommand.quickUpload({ name: name })).uuid uuids.push(uuid) } await waitJobs(servers) for (const uuid of uuids) { - const res = await getVideo(servers[0].url, uuid) - downloadVideos.push(res.body) + downloadVideos.push(await servers[0].videosCommand.get({ id: uuid })) } }) @@ -428,9 +413,8 @@ describe('Test plugin filter hooks', function () { for (const name of [ 'bad embed', 'good embed' ]) { { - const uuid = (await uploadVideoAndGetId({ server: servers[0], videoName: name })).uuid - const res = await getVideo(servers[0].url, uuid) - embedVideos.push(res.body) + const uuid = (await servers[0].videosCommand.quickUpload({ name: name })).uuid + embedVideos.push(await servers[0].videosCommand.get({ id: uuid })) } { diff --git a/server/tests/plugins/plugin-helpers.ts b/server/tests/plugins/plugin-helpers.ts index cbb6887eb..509aba13d 100644 --- a/server/tests/plugins/plugin-helpers.ts +++ b/server/tests/plugins/plugin-helpers.ts @@ -8,15 +8,11 @@ import { cleanupTests, doubleFollow, flushAndRunMultipleServers, - getVideo, - getVideosList, makeGetRequest, makePostBodyRequest, PluginsCommand, ServerInfo, setAccessTokensToServers, - uploadVideoAndGetId, - viewVideo, waitJobs } from '@shared/extra-utils' @@ -144,59 +140,54 @@ describe('Test plugin helpers', function () { this.timeout(60000) { - const res = await uploadVideoAndGetId({ server: servers[0], videoName: 'video server 1' }) + const res = await await servers[0].videosCommand.quickUpload({ name: 'video server 1' }) videoUUIDServer1 = res.uuid } { - await uploadVideoAndGetId({ server: servers[1], videoName: 'video server 2' }) + await await servers[1].videosCommand.quickUpload({ name: 'video server 2' }) } await waitJobs(servers) - const res = await getVideosList(servers[0].url) - const videos = res.body.data + const { data } = await servers[0].videosCommand.list() - expect(videos).to.have.lengthOf(2) + expect(data).to.have.lengthOf(2) }) it('Should mute server 2', async function () { this.timeout(10000) await postCommand(servers[0], 'blockServer', { hostToBlock: `localhost:${servers[1].port}` }) - const res = await getVideosList(servers[0].url) - const videos = res.body.data + const { data } = await servers[0].videosCommand.list() - expect(videos).to.have.lengthOf(1) - expect(videos[0].name).to.equal('video server 1') + expect(data).to.have.lengthOf(1) + expect(data[0].name).to.equal('video server 1') }) it('Should unmute server 2', async function () { await postCommand(servers[0], 'unblockServer', { hostToUnblock: `localhost:${servers[1].port}` }) - const res = await getVideosList(servers[0].url) - const videos = res.body.data + const { data } = await servers[0].videosCommand.list() - expect(videos).to.have.lengthOf(2) + expect(data).to.have.lengthOf(2) }) it('Should mute account of server 2', async function () { await postCommand(servers[0], 'blockAccount', { handleToBlock: `root@localhost:${servers[1].port}` }) - const res = await getVideosList(servers[0].url) - const videos = res.body.data + const { data } = await servers[0].videosCommand.list() - expect(videos).to.have.lengthOf(1) - expect(videos[0].name).to.equal('video server 1') + expect(data).to.have.lengthOf(1) + expect(data[0].name).to.equal('video server 1') }) it('Should unmute account of server 2', async function () { await postCommand(servers[0], 'unblockAccount', { handleToUnblock: `root@localhost:${servers[1].port}` }) - const res = await getVideosList(servers[0].url) - const videos = res.body.data + const { data } = await servers[0].videosCommand.list() - expect(videos).to.have.lengthOf(2) + expect(data).to.have.lengthOf(2) }) it('Should blacklist video', async function () { @@ -207,11 +198,10 @@ describe('Test plugin helpers', function () { await waitJobs(servers) for (const server of servers) { - const res = await getVideosList(server.url) - const videos = res.body.data + const { data } = await server.videosCommand.list() - expect(videos).to.have.lengthOf(1) - expect(videos[0].name).to.equal('video server 2') + expect(data).to.have.lengthOf(1) + expect(data[0].name).to.equal('video server 2') } }) @@ -223,10 +213,9 @@ describe('Test plugin helpers', function () { await waitJobs(servers) for (const server of servers) { - const res = await getVideosList(server.url) - const videos = res.body.data + const { data } = await server.videosCommand.list() - expect(videos).to.have.lengthOf(2) + expect(data).to.have.lengthOf(2) } }) }) @@ -235,7 +224,7 @@ describe('Test plugin helpers', function () { let videoUUID: string before(async () => { - const res = await uploadVideoAndGetId({ server: servers[0], videoName: 'video1' }) + const res = await await servers[0].videosCommand.quickUpload({ name: 'video1' }) videoUUID = res.uuid }) @@ -243,15 +232,15 @@ describe('Test plugin helpers', function () { this.timeout(40000) // Should not throw -> video exists - await getVideo(servers[0].url, videoUUID) + await servers[0].videosCommand.get({ id: videoUUID }) // Should delete the video - await viewVideo(servers[0].url, videoUUID) + await servers[0].videosCommand.view({ id: videoUUID }) await servers[0].serversCommand.waitUntilLog('Video deleted by plugin four.') try { // Should throw because the video should have been deleted - await getVideo(servers[0].url, videoUUID) + await servers[0].videosCommand.get({ id: videoUUID }) throw new Error('Video exists') } catch (err) { if (err.message.includes('exists')) throw err diff --git a/server/tests/plugins/plugin-transcoding.ts b/server/tests/plugins/plugin-transcoding.ts index 4839e8792..a3613293a 100644 --- a/server/tests/plugins/plugin-transcoding.ts +++ b/server/tests/plugins/plugin-transcoding.ts @@ -7,16 +7,14 @@ import { getAudioStream, getVideoFileFPS, getVideoStreamFromFile } from '@server import { cleanupTests, flushAndRunServer, - getVideo, PluginsCommand, ServerInfo, setAccessTokensToServers, setDefaultVideoChannel, testFfmpegStreamError, - uploadVideoAndGetId, waitJobs } from '@shared/extra-utils' -import { VideoDetails, VideoPrivacy } from '@shared/models' +import { VideoPrivacy } from '@shared/models' async function createLiveWrapper (server: ServerInfo) { const liveAttributes = { @@ -81,8 +79,7 @@ describe('Test transcoding plugins', function () { describe('When using a plugin adding profiles to existing encoders', function () { async function checkVideoFPS (uuid: string, type: 'above' | 'below', fps: number) { - const res = await getVideo(server.url, uuid) - const video = res.body as VideoDetails + const video = await server.videosCommand.get({ id: uuid }) const files = video.files.concat(...video.streamingPlaylists.map(p => p.files)) for (const file of files) { @@ -119,7 +116,7 @@ describe('Test transcoding plugins', function () { it('Should not use the plugin profile if not chosen by the admin', async function () { this.timeout(240000) - const videoUUID = (await uploadVideoAndGetId({ server, videoName: 'video' })).uuid + const videoUUID = (await server.videosCommand.quickUpload({ name: 'video' })).uuid await waitJobs([ server ]) await checkVideoFPS(videoUUID, 'above', 20) @@ -130,7 +127,7 @@ describe('Test transcoding plugins', function () { await updateConf(server, 'low-vod', 'default') - const videoUUID = (await uploadVideoAndGetId({ server, videoName: 'video' })).uuid + const videoUUID = (await server.videosCommand.quickUpload({ name: 'video' })).uuid await waitJobs([ server ]) await checkVideoFPS(videoUUID, 'below', 12) @@ -141,7 +138,7 @@ describe('Test transcoding plugins', function () { await updateConf(server, 'input-options-vod', 'default') - const videoUUID = (await uploadVideoAndGetId({ server, videoName: 'video' })).uuid + const videoUUID = (await server.videosCommand.quickUpload({ name: 'video' })).uuid await waitJobs([ server ]) await checkVideoFPS(videoUUID, 'below', 6) @@ -152,13 +149,11 @@ describe('Test transcoding plugins', function () { await updateConf(server, 'bad-scale-vod', 'default') - const videoUUID = (await uploadVideoAndGetId({ server, videoName: 'video' })).uuid + const videoUUID = (await server.videosCommand.quickUpload({ name: 'video' })).uuid await waitJobs([ server ]) // Transcoding failed - const res = await getVideo(server.url, videoUUID) - const video: VideoDetails = res.body - + const video = await server.videosCommand.get({ id: videoUUID }) expect(video.files).to.have.lengthOf(1) expect(video.streamingPlaylists).to.have.lengthOf(0) }) @@ -224,7 +219,7 @@ describe('Test transcoding plugins', function () { expect(config.transcoding.availableProfiles).to.deep.equal([ 'default' ]) expect(config.live.transcoding.availableProfiles).to.deep.equal([ 'default' ]) - const videoUUID = (await uploadVideoAndGetId({ server, videoName: 'video' })).uuid + const videoUUID = (await server.videosCommand.quickUpload({ name: 'video' })).uuid await waitJobs([ server ]) await checkVideoFPS(videoUUID, 'above', 20) @@ -243,7 +238,7 @@ describe('Test transcoding plugins', function () { it('Should use the new vod encoders', async function () { this.timeout(240000) - const videoUUID = (await uploadVideoAndGetId({ server, videoName: 'video', fixture: 'video_short_240p.mp4' })).uuid + const videoUUID = (await server.videosCommand.quickUpload({ name: 'video', fixture: 'video_short_240p.mp4' })).uuid await waitJobs([ server ]) const path = server.serversCommand.buildDirectory(join('videos', videoUUID + '-240.mp4')) diff --git a/server/tests/plugins/video-constants.ts b/server/tests/plugins/video-constants.ts index 4a05af042..641e37fbb 100644 --- a/server/tests/plugins/video-constants.ts +++ b/server/tests/plugins/video-constants.ts @@ -3,20 +3,8 @@ import 'mocha' import * as chai from 'chai' import { HttpStatusCode } from '@shared/core-utils' -import { - cleanupTests, - flushAndRunServer, - getVideo, - getVideoCategories, - getVideoLanguages, - getVideoLicences, - getVideoPrivacies, - PluginsCommand, - ServerInfo, - setAccessTokensToServers, - uploadVideo -} from '@shared/extra-utils' -import { VideoDetails, VideoPlaylistPrivacy } from '@shared/models' +import { cleanupTests, flushAndRunServer, PluginsCommand, ServerInfo, setAccessTokensToServers } from '@shared/extra-utils' +import { VideoPlaylistPrivacy } from '@shared/models' const expect = chai.expect @@ -33,8 +21,7 @@ describe('Test plugin altering video constants', function () { }) it('Should have updated languages', async function () { - const res = await getVideoLanguages(server.url) - const languages = res.body + const languages = await server.videosCommand.getLanguages() expect(languages['en']).to.not.exist expect(languages['fr']).to.not.exist @@ -45,8 +32,7 @@ describe('Test plugin altering video constants', function () { }) it('Should have updated categories', async function () { - const res = await getVideoCategories(server.url) - const categories = res.body + const categories = await server.videosCommand.getCategories() expect(categories[1]).to.not.exist expect(categories[2]).to.not.exist @@ -56,8 +42,7 @@ describe('Test plugin altering video constants', function () { }) it('Should have updated licences', async function () { - const res = await getVideoLicences(server.url) - const licences = res.body + const licences = await server.videosCommand.getLicences() expect(licences[1]).to.not.exist expect(licences[7]).to.not.exist @@ -67,8 +52,7 @@ describe('Test plugin altering video constants', function () { }) it('Should have updated video privacies', async function () { - const res = await getVideoPrivacies(server.url) - const privacies = res.body + const privacies = await server.videosCommand.getPrivacies() expect(privacies[1]).to.exist expect(privacies[2]).to.not.exist @@ -85,8 +69,8 @@ describe('Test plugin altering video constants', function () { }) it('Should not be able to create a video with this privacy', async function () { - const attrs = { name: 'video', privacy: 2 } - await uploadVideo(server.url, server.accessToken, attrs, HttpStatusCode.BAD_REQUEST_400) + const attributes = { name: 'video', privacy: 2 } + await server.videosCommand.upload({ attributes, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) it('Should not be able to create a video with this privacy', async function () { @@ -95,12 +79,10 @@ describe('Test plugin altering video constants', function () { }) it('Should be able to upload a video with these values', async function () { - const attrs = { name: 'video', category: 42, licence: 42, language: 'al_bhed2' } - const resUpload = await uploadVideo(server.url, server.accessToken, attrs) + const attributes = { name: 'video', category: 42, licence: 42, language: 'al_bhed2' } + const { uuid } = await server.videosCommand.upload({ attributes }) - const res = await getVideo(server.url, resUpload.body.video.uuid) - - const video: VideoDetails = res.body + const video = await server.videosCommand.get({ id: uuid }) expect(video.language.label).to.equal('Al Bhed 2') expect(video.licence.label).to.equal('Best licence') expect(video.category.label).to.equal('Best category') @@ -110,8 +92,7 @@ describe('Test plugin altering video constants', function () { await server.pluginsCommand.uninstall({ npmName: 'peertube-plugin-test-video-constants' }) { - const res = await getVideoLanguages(server.url) - const languages = res.body + const languages = await server.videosCommand.getLanguages() expect(languages['en']).to.equal('English') expect(languages['fr']).to.equal('French') @@ -122,8 +103,7 @@ describe('Test plugin altering video constants', function () { } { - const res = await getVideoCategories(server.url) - const categories = res.body + const categories = await server.videosCommand.getCategories() expect(categories[1]).to.equal('Music') expect(categories[2]).to.equal('Films') @@ -133,8 +113,7 @@ describe('Test plugin altering video constants', function () { } { - const res = await getVideoLicences(server.url) - const licences = res.body + const licences = await server.videosCommand.getLicences() expect(licences[1]).to.equal('Attribution') expect(licences[7]).to.equal('Public Domain Dedication') @@ -144,8 +123,7 @@ describe('Test plugin altering video constants', function () { } { - const res = await getVideoPrivacies(server.url) - const privacies = res.body + const privacies = await server.videosCommand.getPrivacies() expect(privacies[1]).to.exist expect(privacies[2]).to.exist diff --git a/server/tools/cli.ts b/server/tools/cli.ts index 17c2e8c74..163ed62d1 100644 --- a/server/tools/cli.ts +++ b/server/tools/cli.ts @@ -16,7 +16,7 @@ const version = require('../../../package.json').version async function getAdminTokenOrDie (server: ServerInfo, username: string, password: string) { const token = await server.loginCommand.getAccessToken(username, password) - const me = await server.usersCommand.getMyUserInformation({ token }) + const me = await server.usersCommand.getMyInfo({ token }) if (me.role !== UserRole.ADMINISTRATOR) { console.error('You must be an administrator.') diff --git a/server/tools/peertube-import-videos.ts b/server/tools/peertube-import-videos.ts index 0a4d6fa6e..fc76735b9 100644 --- a/server/tools/peertube-import-videos.ts +++ b/server/tools/peertube-import-videos.ts @@ -9,7 +9,6 @@ import { join } from 'path' import * as prompt from 'prompt' import { promisify } from 'util' import { YoutubeDL } from '@server/helpers/youtube-dl' -import { getVideoCategories, uploadVideo } from '../../shared/extra-utils/index' import { sha256 } from '../helpers/core-utils' import { doRequestAndSaveToFile } from '../helpers/requests' import { CONSTRAINTS_FIELDS } from '../initializers/constants' @@ -21,6 +20,7 @@ import { getLogger, getServerCredentials } from './cli' +import { ServerInfo } from '@shared/extra-utils' const processOptions = { maxBuffer: Infinity @@ -200,7 +200,10 @@ async function uploadVideoOnPeerTube (parameters: { }) { const { youtubeDL, videoInfo, videoPath, cwd, url, username, password } = parameters - const category = await getCategory(videoInfo.categories, url) + const server = buildServer(url) + await assignToken(server, username, password) + + const category = await getCategory(server, videoInfo.categories) const licence = getLicence(videoInfo.license) let tags = [] if (Array.isArray(videoInfo.tags)) { @@ -232,29 +235,28 @@ async function uploadVideoOnPeerTube (parameters: { tags } - const server = buildServer(url) - await assignToken(server, username, password) + const baseAttributes = await buildVideoAttributesFromCommander(server, program, defaultAttributes) - const videoAttributes = await buildVideoAttributesFromCommander(server, program, defaultAttributes) + const attributes = { + ...baseAttributes, - Object.assign(videoAttributes, { originallyPublishedAt: originallyPublishedAt ? originallyPublishedAt.toISOString() : null, thumbnailfile, previewfile: thumbnailfile, fixture: videoPath - }) + } - log.info('\nUploading on PeerTube video "%s".', videoAttributes.name) + log.info('\nUploading on PeerTube video "%s".', attributes.name) try { - await uploadVideo(url, server.accessToken, videoAttributes) + await server.videosCommand.upload({ attributes }) } catch (err) { if (err.message.indexOf('401') !== -1) { log.info('Got 401 Unauthorized, token may have expired, renewing token and retry.') server.accessToken = await server.loginCommand.getAccessToken(username, password) - await uploadVideo(url, server.accessToken, videoAttributes) + await server.videosCommand.upload({ attributes }) } else { exitError(err.message) } @@ -263,20 +265,19 @@ async function uploadVideoOnPeerTube (parameters: { await remove(videoPath) if (thumbnailfile) await remove(thumbnailfile) - log.warn('Uploaded video "%s"!\n', videoAttributes.name) + log.warn('Uploaded video "%s"!\n', attributes.name) } /* ---------------------------------------------------------- */ -async function getCategory (categories: string[], url: string) { +async function getCategory (server: ServerInfo, categories: string[]) { if (!categories) return undefined const categoryString = categories[0] if (categoryString === 'News & Politics') return 11 - const res = await getVideoCategories(url) - const categoriesServer = res.body + const categoriesServer = await server.videosCommand.getCategories() for (const key of Object.keys(categoriesServer)) { const categoryServer = categoriesServer[key] diff --git a/server/tools/peertube-upload.ts b/server/tools/peertube-upload.ts index c94b05857..597137e4c 100644 --- a/server/tools/peertube-upload.ts +++ b/server/tools/peertube-upload.ts @@ -4,7 +4,6 @@ registerTSPaths() import { program } from 'commander' import { access, constants } from 'fs-extra' import { isAbsolute } from 'path' -import { uploadVideo } from '../../shared/extra-utils/' import { assignToken, buildCommonVideoOptions, buildServer, buildVideoAttributesFromCommander, getServerCredentials } from './cli' let command = program @@ -52,16 +51,18 @@ async function run (url: string, username: string, password: string) { console.log('Uploading %s video...', options.videoName) - const videoAttributes = await buildVideoAttributesFromCommander(server, program) + const baseAttributes = await buildVideoAttributesFromCommander(server, program) + + const attributes = { + ...baseAttributes, - Object.assign(videoAttributes, { fixture: options.file, thumbnailfile: options.thumbnail, previewfile: options.preview - }) + } try { - await uploadVideo(url, server.accessToken, videoAttributes) + await server.videosCommand.upload({ attributes }) console.log(`Video ${options.videoName} uploaded.`) process.exit(0) } catch (err) { diff --git a/shared/extra-utils/miscs/webtorrent.ts b/shared/extra-utils/miscs/webtorrent.ts index 82548946d..63e648309 100644 --- a/shared/extra-utils/miscs/webtorrent.ts +++ b/shared/extra-utils/miscs/webtorrent.ts @@ -1,4 +1,8 @@ +import { readFile } from 'fs-extra' +import * as parseTorrent from 'parse-torrent' +import { join } from 'path' import * as WebTorrent from 'webtorrent' +import { ServerInfo } from '../server' let webtorrent: WebTorrent.Instance @@ -11,6 +15,16 @@ function webtorrentAdd (torrent: string, refreshWebTorrent = false) { return new Promise(res => webtorrent.add(torrent, res)) } +async function parseTorrentVideo (server: ServerInfo, videoUUID: string, resolution: number) { + const torrentName = videoUUID + '-' + resolution + '.torrent' + const torrentPath = server.serversCommand.buildDirectory(join('torrents', torrentName)) + + const data = await readFile(torrentPath) + + return parseTorrent(data) +} + export { - webtorrentAdd + webtorrentAdd, + parseTorrentVideo } diff --git a/shared/extra-utils/requests/requests.ts b/shared/extra-utils/requests/requests.ts index c5ee63e05..3f1ac6650 100644 --- a/shared/extra-utils/requests/requests.ts +++ b/shared/extra-utils/requests/requests.ts @@ -67,11 +67,17 @@ function makeUploadRequest (options: { method?: 'POST' | 'PUT' path: string token?: string + fields: { [ fieldName: string ]: any } attaches?: { [ attachName: string ]: any | any[] } + + headers?: { [ name: string ]: string } + statusCodeExpected?: HttpStatusCode }) { - if (!options.statusCodeExpected) options.statusCodeExpected = HttpStatusCode.BAD_REQUEST_400 + if (options.statusCodeExpected === undefined) { + options.statusCodeExpected = HttpStatusCode.BAD_REQUEST_400 + } let req: request.Test if (options.method === 'PUT') { @@ -84,6 +90,10 @@ function makeUploadRequest (options: { if (options.token) req.set('Authorization', 'Bearer ' + options.token) + Object.keys(options.headers || {}).forEach(name => { + req.set(name, options.headers[name]) + }) + Object.keys(options.fields).forEach(field => { const value = options.fields[field] @@ -107,7 +117,11 @@ function makeUploadRequest (options: { } }) - return req.expect(options.statusCodeExpected) + if (options.statusCodeExpected) { + req.expect(options.statusCodeExpected) + } + + return req } function makePostBodyRequest (options: { @@ -115,7 +129,9 @@ function makePostBodyRequest (options: { path: string token?: string fields?: { [ fieldName: string ]: any } + headers?: { [ name: string ]: string } type?: string + xForwardedFor?: string statusCodeExpected?: HttpStatusCode }) { if (!options.fields) options.fields = {} @@ -126,8 +142,13 @@ function makePostBodyRequest (options: { .set('Accept', 'application/json') if (options.token) req.set('Authorization', 'Bearer ' + options.token) + if (options.xForwardedFor) req.set('X-Forwarded-For', options.xForwardedFor) if (options.type) req.type(options.type) + Object.keys(options.headers || {}).forEach(name => { + req.set(name, options.headers[name]) + }) + return req.send(options.fields) .expect(options.statusCodeExpected) } diff --git a/shared/extra-utils/server/servers.ts b/shared/extra-utils/server/servers.ts index b6d597c5d..fda5c3d6d 100644 --- a/shared/extra-utils/server/servers.ts +++ b/shared/extra-utils/server/servers.ts @@ -27,7 +27,8 @@ import { LiveCommand, PlaylistsCommand, ServicesCommand, - StreamingPlaylistsCommand + StreamingPlaylistsCommand, + VideosCommand } from '../videos' import { CommentsCommand } from '../videos/comments-command' import { ConfigCommand } from './config-command' @@ -128,6 +129,7 @@ interface ServerInfo { serversCommand?: ServersCommand loginCommand?: LoginCommand usersCommand?: UsersCommand + videosCommand?: VideosCommand } function flushAndRunMultipleServers (totalServers: number, configOverride?: Object) { @@ -361,6 +363,7 @@ function assignCommands (server: ServerInfo) { server.serversCommand = new ServersCommand(server) server.loginCommand = new LoginCommand(server) server.usersCommand = new UsersCommand(server) + server.videosCommand = new VideosCommand(server) } async function reRunServer (server: ServerInfo, configOverride?: any) { diff --git a/shared/extra-utils/shared/abstract-command.ts b/shared/extra-utils/shared/abstract-command.ts index af9ecd926..5fddcf639 100644 --- a/shared/extra-utils/shared/abstract-command.ts +++ b/shared/extra-utils/shared/abstract-command.ts @@ -1,5 +1,4 @@ import { isAbsolute, join } from 'path' -import { HttpStatusCode } from '@shared/core-utils' import { root } from '../miscs/tests' import { makeDeleteRequest, @@ -38,22 +37,12 @@ interface InternalGetCommandOptions extends InternalCommonCommandOptions { abstract class AbstractCommand { - private expectedStatus: HttpStatusCode - constructor ( protected server: ServerInfo ) { } - setServer (server: ServerInfo) { - this.server = server - } - - setExpectedStatus (status: HttpStatusCode) { - this.expectedStatus = status - } - protected getRequestBody (options: InternalGetCommandOptions) { return unwrapBody(this.getRequest(options)) } @@ -111,43 +100,51 @@ abstract class AbstractCommand { protected postBodyRequest (options: InternalCommonCommandOptions & { fields?: { [ fieldName: string ]: any } + headers?: { [ name: string ]: string } type?: string + xForwardedFor?: string }) { - const { type, fields } = options + const { type, fields, xForwardedFor, headers } = options return makePostBodyRequest({ ...this.buildCommonRequestOptions(options), fields, - type + xForwardedFor, + type, + headers }) } protected postUploadRequest (options: InternalCommonCommandOptions & { fields?: { [ fieldName: string ]: any } - attaches?: any + attaches?: { [ fieldName: string ]: any } + headers?: { [ name: string ]: string } }) { - const { fields, attaches } = options + const { fields, attaches, headers } = options return makeUploadRequest({ ...this.buildCommonRequestOptions(options), method: 'POST', fields, - attaches + attaches, + headers }) } protected putUploadRequest (options: InternalCommonCommandOptions & { fields?: { [ fieldName: string ]: any } - attaches?: any + attaches?: { [ fieldName: string ]: any } + headers?: { [ name: string ]: string } }) { - const { fields, attaches } = options + const { fields, attaches, headers } = options return makeUploadRequest({ ...this.buildCommonRequestOptions(options), method: 'PUT', + headers, fields, attaches }) @@ -172,7 +169,7 @@ abstract class AbstractCommand { }) } - private buildCommonRequestOptions (options: InternalCommonCommandOptions) { + protected buildCommonRequestOptions (options: InternalCommonCommandOptions) { const { url, path } = options return { @@ -184,7 +181,7 @@ abstract class AbstractCommand { } } - private buildCommonRequestToken (options: Pick) { + protected buildCommonRequestToken (options: Pick) { const { token } = options const fallbackToken = options.implicitToken @@ -194,10 +191,10 @@ abstract class AbstractCommand { return token !== undefined ? token : fallbackToken } - private buildStatusCodeExpected (options: Pick) { + protected buildStatusCodeExpected (options: Pick) { const { expectedStatus, defaultExpectedStatus } = options - return expectedStatus ?? this.expectedStatus ?? defaultExpectedStatus + return expectedStatus !== undefined ? expectedStatus : defaultExpectedStatus } } diff --git a/shared/extra-utils/videos/index.ts b/shared/extra-utils/videos/index.ts index 652d82842..26e663f46 100644 --- a/shared/extra-utils/videos/index.ts +++ b/shared/extra-utils/videos/index.ts @@ -15,4 +15,5 @@ export * from './services-command' export * from './streaming-playlists-command' export * from './streaming-playlists' export * from './comments-command' +export * from './videos-command' export * from './videos' diff --git a/shared/extra-utils/videos/live-command.ts b/shared/extra-utils/videos/live-command.ts index a494e60fa..5adf601cc 100644 --- a/shared/extra-utils/videos/live-command.ts +++ b/shared/extra-utils/videos/live-command.ts @@ -9,7 +9,6 @@ import { wait } from '../miscs' import { unwrapBody } from '../requests' import { AbstractCommand, OverrideCommandOptions } from '../shared' import { sendRTMPStream, testFfmpegStreamError } from './live' -import { getVideoWithToken } from './videos' export class LiveCommand extends AbstractCommand { @@ -124,8 +123,7 @@ export class LiveCommand extends AbstractCommand { let video: VideoDetails do { - const res = await getVideoWithToken(this.server.url, options.token ?? this.server.accessToken, options.videoId) - video = res.body + video = await this.server.videosCommand.getWithToken({ token: options.token, id: options.videoId }) await wait(500) } while (video.isLive === true && video.state.id !== VideoState.PUBLISHED) @@ -149,8 +147,7 @@ export class LiveCommand extends AbstractCommand { let video: VideoDetails do { - const res = await getVideoWithToken(this.server.url, options.token ?? this.server.accessToken, options.videoId) - video = res.body + video = await this.server.videosCommand.getWithToken({ token: options.token, id: options.videoId }) await wait(500) } while (video.state.id !== options.state) diff --git a/shared/extra-utils/videos/playlists-command.ts b/shared/extra-utils/videos/playlists-command.ts index f77decc1a..75c8f2433 100644 --- a/shared/extra-utils/videos/playlists-command.ts +++ b/shared/extra-utils/videos/playlists-command.ts @@ -1,23 +1,22 @@ import { omit, pick } from 'lodash' +import { HttpStatusCode } from '@shared/core-utils' import { BooleanBothQuery, ResultList, VideoExistInPlaylist, VideoPlaylist, + VideoPlaylistCreate, VideoPlaylistCreateResult, VideoPlaylistElement, + VideoPlaylistElementCreate, VideoPlaylistElementCreateResult, - VideoPlaylistReorder + VideoPlaylistElementUpdate, + VideoPlaylistReorder, + VideoPlaylistType, + VideoPlaylistUpdate } from '@shared/models' -import { HttpStatusCode } from '../../core-utils/miscs/http-error-codes' -import { VideoPlaylistCreate } from '../../models/videos/playlist/video-playlist-create.model' -import { VideoPlaylistElementCreate } from '../../models/videos/playlist/video-playlist-element-create.model' -import { VideoPlaylistElementUpdate } from '../../models/videos/playlist/video-playlist-element-update.model' -import { VideoPlaylistType } from '../../models/videos/playlist/video-playlist-type.model' -import { VideoPlaylistUpdate } from '../../models/videos/playlist/video-playlist-update.model' import { unwrapBody } from '../requests' import { AbstractCommand, OverrideCommandOptions } from '../shared' -import { videoUUIDToId } from './videos' export class PlaylistsCommand extends AbstractCommand { @@ -185,7 +184,7 @@ export class PlaylistsCommand extends AbstractCommand { const attributes = { ...options.attributes, - videoId: await videoUUIDToId(this.server.url, options.attributes.videoId) + videoId: await this.server.videosCommand.getId({ ...options, uuid: options.attributes.videoId }) } const path = '/api/v1/video-playlists/' + options.playlistId + '/videos' diff --git a/shared/extra-utils/videos/videos-command.ts b/shared/extra-utils/videos/videos-command.ts new file mode 100644 index 000000000..574705474 --- /dev/null +++ b/shared/extra-utils/videos/videos-command.ts @@ -0,0 +1,583 @@ +/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/no-floating-promises */ + +import { expect } from 'chai' +import { createReadStream, stat } from 'fs-extra' +import got, { Response as GotResponse } from 'got' +import { omit, pick } from 'lodash' +import validator from 'validator' +import { buildUUID } from '@server/helpers/uuid' +import { loadLanguages } from '@server/initializers/constants' +import { HttpStatusCode } from '@shared/core-utils' +import { + ResultList, + UserVideoRateType, + Video, + VideoCreate, + VideoCreateResult, + VideoDetails, + VideoFileMetadata, + VideoPrivacy, + VideosCommonQuery, + VideosWithSearchCommonQuery +} from '@shared/models' +import { buildAbsoluteFixturePath, wait } from '../miscs' +import { unwrapBody } from '../requests' +import { ServerInfo, waitJobs } from '../server' +import { AbstractCommand, OverrideCommandOptions } from '../shared' + +export type VideoEdit = Partial> & { + fixture?: string + thumbnailfile?: string + previewfile?: string +} + +export class VideosCommand extends AbstractCommand { + + constructor (server: ServerInfo) { + super(server) + + loadLanguages() + } + + getCategories (options: OverrideCommandOptions = {}) { + const path = '/api/v1/videos/categories' + + return this.getRequestBody<{ [id: number]: string }>({ + ...options, + path, + + implicitToken: false, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } + + getLicences (options: OverrideCommandOptions = {}) { + const path = '/api/v1/videos/licences' + + return this.getRequestBody<{ [id: number]: string }>({ + ...options, + path, + + implicitToken: false, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } + + getLanguages (options: OverrideCommandOptions = {}) { + const path = '/api/v1/videos/languages' + + return this.getRequestBody<{ [id: string]: string }>({ + ...options, + path, + + implicitToken: false, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } + + getPrivacies (options: OverrideCommandOptions = {}) { + const path = '/api/v1/videos/privacies' + + return this.getRequestBody<{ [id in VideoPrivacy]: string }>({ + ...options, + path, + + implicitToken: false, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } + + // --------------------------------------------------------------------------- + + getDescription (options: OverrideCommandOptions & { + descriptionPath: string + }) { + return this.getRequestBody<{ description: string }>({ + ...options, + path: options.descriptionPath, + + implicitToken: false, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } + + getFileMetadata (options: OverrideCommandOptions & { + url: string + }) { + return unwrapBody(this.getRawRequest({ + ...options, + + url: options.url, + implicitToken: false, + defaultExpectedStatus: HttpStatusCode.OK_200 + })) + } + + // --------------------------------------------------------------------------- + + view (options: OverrideCommandOptions & { + id: number | string + xForwardedFor?: string + }) { + const { id, xForwardedFor } = options + const path = '/api/v1/videos/' + id + '/views' + + return this.postBodyRequest({ + ...options, + + path, + xForwardedFor, + implicitToken: false, + defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 + }) + } + + rate (options: OverrideCommandOptions & { + id: number | string + rating: UserVideoRateType + }) { + const { id, rating } = options + const path = '/api/v1/videos/' + id + '/rate' + + return this.putBodyRequest({ + ...options, + + path, + fields: { rating }, + implicitToken: true, + defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 + }) + } + + // --------------------------------------------------------------------------- + + get (options: OverrideCommandOptions & { + id: number | string + }) { + const path = '/api/v1/videos/' + options.id + + return this.getRequestBody({ + ...options, + + path, + implicitToken: false, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } + + getWithToken (options: OverrideCommandOptions & { + id: number | string + }) { + return this.get({ + ...options, + + token: this.buildCommonRequestToken({ ...options, implicitToken: true }) + }) + } + + async getId (options: OverrideCommandOptions & { + uuid: number | string + }) { + const { uuid } = options + + if (validator.isUUID('' + uuid) === false) return uuid as number + + const { id } = await this.get({ ...options, id: uuid }) + + return id + } + + // --------------------------------------------------------------------------- + + listMyVideos (options: OverrideCommandOptions & { + start?: number + count?: number + sort?: string + search?: string + isLive?: boolean + } = {}) { + const path = '/api/v1/users/me/videos' + + return this.getRequestBody>({ + ...options, + + path, + query: pick(options, [ 'start', 'count', 'sort', 'search', 'isLive' ]), + implicitToken: true, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } + + // --------------------------------------------------------------------------- + + list (options: OverrideCommandOptions & VideosCommonQuery = {}) { + const path = '/api/v1/videos' + + const query = this.buildListQuery(options) + + return this.getRequestBody>({ + ...options, + + path, + query: { sort: 'name', ...query }, + implicitToken: false, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } + + listWithToken (options: OverrideCommandOptions & VideosCommonQuery = {}) { + return this.list({ + ...options, + + token: this.buildCommonRequestToken({ ...options, implicitToken: true }) + }) + } + + listByAccount (options: OverrideCommandOptions & VideosWithSearchCommonQuery & { + accountName: string + }) { + const { accountName, search } = options + const path = '/api/v1/accounts/' + accountName + '/videos' + + return this.getRequestBody>({ + ...options, + + path, + query: { search, ...this.buildListQuery(options) }, + implicitToken: true, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } + + listByChannel (options: OverrideCommandOptions & VideosWithSearchCommonQuery & { + videoChannelName: string + }) { + const { videoChannelName } = options + const path = '/api/v1/video-channels/' + videoChannelName + '/videos' + + return this.getRequestBody>({ + ...options, + + path, + query: this.buildListQuery(options), + implicitToken: true, + defaultExpectedStatus: HttpStatusCode.OK_200 + }) + } + + // --------------------------------------------------------------------------- + + update (options: OverrideCommandOptions & { + id: number | string + attributes?: VideoEdit + }) { + const { id, attributes = {} } = options + const path = '/api/v1/videos/' + id + + // Upload request + if (attributes.thumbnailfile || attributes.previewfile) { + const attaches: any = {} + if (attributes.thumbnailfile) attaches.thumbnailfile = attributes.thumbnailfile + if (attributes.previewfile) attaches.previewfile = attributes.previewfile + + return this.putUploadRequest({ + ...options, + + path, + fields: options.attributes, + attaches: { + thumbnailfile: attributes.thumbnailfile, + previewfile: attributes.previewfile + }, + implicitToken: true, + defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 + }) + } + + return this.putBodyRequest({ + ...options, + + path, + fields: options.attributes, + implicitToken: true, + defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 + }) + } + + remove (options: OverrideCommandOptions & { + id: number | string + }) { + const path = '/api/v1/videos/' + options.id + + return this.deleteRequest({ + ...options, + + path, + implicitToken: true, + defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 + }) + } + + async removeAll () { + const { data } = await this.list() + + for (const v of data) { + await this.remove({ id: v.id }) + } + } + + // --------------------------------------------------------------------------- + + async upload (options: OverrideCommandOptions & { + attributes?: VideoEdit + mode?: 'legacy' | 'resumable' // default legacy + } = {}) { + const { mode = 'legacy', expectedStatus } = options + let defaultChannelId = 1 + + try { + const { videoChannels } = await this.server.usersCommand.getMyInfo({ token: options.token }) + defaultChannelId = videoChannels[0].id + } catch (e) { /* empty */ } + + // Override default attributes + const attributes = { + name: 'my super video', + category: 5, + licence: 4, + language: 'zh', + channelId: defaultChannelId, + nsfw: true, + waitTranscoding: false, + description: 'my super description', + support: 'my super support text', + tags: [ 'tag' ], + privacy: VideoPrivacy.PUBLIC, + commentsEnabled: true, + downloadEnabled: true, + fixture: 'video_short.webm', + + ...options.attributes + } + + const res = mode === 'legacy' + ? await this.buildLegacyUpload({ ...options, attributes }) + : await this.buildResumeUpload({ ...options, attributes }) + + // Wait torrent generation + if (expectedStatus === HttpStatusCode.OK_200) { + let video: VideoDetails + + do { + video = await this.getWithToken({ ...options, id: video.uuid }) + + await wait(50) + } while (!video.files[0].torrentUrl) + } + + return res + } + + async buildLegacyUpload (options: OverrideCommandOptions & { + attributes: VideoEdit + }): Promise { + const path = '/api/v1/videos/upload' + + return unwrapBody<{ video: VideoCreateResult }>(this.postUploadRequest({ + ...options, + + path, + fields: this.buildUploadFields(options.attributes), + attaches: this.buildUploadAttaches(options.attributes), + implicitToken: true, + defaultExpectedStatus: HttpStatusCode.OK_200 + })).then(body => body.video || body as any) + } + + async buildResumeUpload (options: OverrideCommandOptions & { + attributes: VideoEdit + }) { + const { attributes, expectedStatus } = options + + let size = 0 + let videoFilePath: string + let mimetype = 'video/mp4' + + if (attributes.fixture) { + videoFilePath = buildAbsoluteFixturePath(attributes.fixture) + size = (await stat(videoFilePath)).size + + if (videoFilePath.endsWith('.mkv')) { + mimetype = 'video/x-matroska' + } else if (videoFilePath.endsWith('.webm')) { + mimetype = 'video/webm' + } + } + + const initializeSessionRes = await this.prepareResumableUpload({ ...options, attributes, size, mimetype }) + const initStatus = initializeSessionRes.status + + if (videoFilePath && initStatus === HttpStatusCode.CREATED_201) { + const locationHeader = initializeSessionRes.header['location'] + expect(locationHeader).to.not.be.undefined + + const pathUploadId = locationHeader.split('?')[1] + + const result = await this.sendResumableChunks({ ...options, pathUploadId, videoFilePath, size }) + + return result.body.video + } + + const expectedInitStatus = expectedStatus === HttpStatusCode.OK_200 + ? HttpStatusCode.CREATED_201 + : expectedStatus + + expect(initStatus).to.equal(expectedInitStatus) + + return initializeSessionRes.body.video as VideoCreateResult + } + + async prepareResumableUpload (options: OverrideCommandOptions & { + attributes: VideoEdit + size: number + mimetype: string + }) { + const { attributes, size, mimetype } = options + + const path = '/api/v1/videos/upload-resumable' + + return this.postUploadRequest({ + ...options, + + path, + headers: { + 'X-Upload-Content-Type': mimetype, + 'X-Upload-Content-Length': size.toString() + }, + fields: { filename: attributes.fixture, ...this.buildUploadFields(options.attributes) }, + implicitToken: true, + defaultExpectedStatus: null + }) + } + + sendResumableChunks (options: OverrideCommandOptions & { + pathUploadId: string + videoFilePath: string + size: number + contentLength?: number + contentRangeBuilder?: (start: number, chunk: any) => string + }) { + const { pathUploadId, videoFilePath, size, contentLength, contentRangeBuilder, expectedStatus = HttpStatusCode.OK_200 } = options + + const path = '/api/v1/videos/upload-resumable' + let start = 0 + + const token = this.buildCommonRequestToken({ ...options, implicitToken: true }) + const url = this.server.url + + const readable = createReadStream(videoFilePath, { highWaterMark: 8 * 1024 }) + return new Promise>((resolve, reject) => { + readable.on('data', async function onData (chunk) { + readable.pause() + + const headers = { + 'Authorization': 'Bearer ' + token, + 'Content-Type': 'application/octet-stream', + 'Content-Range': contentRangeBuilder + ? contentRangeBuilder(start, chunk) + : `bytes ${start}-${start + chunk.length - 1}/${size}`, + 'Content-Length': contentLength ? contentLength + '' : chunk.length + '' + } + + const res = await got<{ video: VideoCreateResult }>({ + url, + method: 'put', + headers, + path: path + '?' + pathUploadId, + body: chunk, + responseType: 'json', + throwHttpErrors: false + }) + + start += chunk.length + + if (res.statusCode === expectedStatus) { + return resolve(res) + } + + if (res.statusCode !== HttpStatusCode.PERMANENT_REDIRECT_308) { + readable.off('data', onData) + return reject(new Error('Incorrect transient behaviour sending intermediary chunks')) + } + + readable.resume() + }) + }) + } + + quickUpload (options: OverrideCommandOptions & { + name: string + nsfw?: boolean + privacy?: VideoPrivacy + fixture?: string + }) { + const attributes: VideoEdit = { name: options.name } + if (options.nsfw) attributes.nsfw = options.nsfw + if (options.privacy) attributes.privacy = options.privacy + if (options.fixture) attributes.fixture = options.fixture + + return this.upload({ ...options, attributes }) + } + + async randomUpload (options: OverrideCommandOptions & { + wait?: boolean // default true + additionalParams?: VideoEdit & { prefixName: string } + } = {}) { + const { wait = true, additionalParams } = options + const prefixName = additionalParams?.prefixName || '' + const name = prefixName + buildUUID() + + const attributes = { name, additionalParams } + + if (wait) await waitJobs([ this.server ]) + + const result = await this.upload({ ...options, attributes }) + + return { ...result, name } + } + + // --------------------------------------------------------------------------- + + private buildListQuery (options: VideosCommonQuery) { + return pick(options, [ + 'start', + 'count', + 'sort', + 'nsfw', + 'isLive', + 'categoryOneOf', + 'licenceOneOf', + 'languageOneOf', + 'tagsOneOf', + 'tagsAllOf', + 'filter', + 'skipCount' + ]) + } + + private buildUploadFields (attributes: VideoEdit) { + return omit(attributes, [ 'thumbnailfile', 'previewfile' ]) + } + + private buildUploadAttaches (attributes: VideoEdit) { + const attaches: { [ name: string ]: string } = {} + + for (const key of [ 'thumbnailfile', 'previewfile' ]) { + if (attributes[key]) attaches[key] = buildAbsoluteFixturePath(attributes[key]) + } + + if (attributes.fixture) attaches.videofile = buildAbsoluteFixturePath(attributes.fixture) + + return attaches + } +} diff --git a/shared/extra-utils/videos/videos.ts b/shared/extra-utils/videos/videos.ts index 5e20f8010..19f0df8b8 100644 --- a/shared/extra-utils/videos/videos.ts +++ b/shared/extra-utils/videos/videos.ts @@ -1,306 +1,16 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/no-floating-promises */ import { expect } from 'chai' -import { createReadStream, pathExists, readdir, readFile, stat } from 'fs-extra' -import got, { Response as GotResponse } from 'got/dist/source' -import * as parseTorrent from 'parse-torrent' +import { pathExists, readdir } from 'fs-extra' import { join } from 'path' -import * as request from 'supertest' -import validator from 'validator' import { getLowercaseExtension } from '@server/helpers/core-utils' -import { buildUUID } from '@server/helpers/uuid' import { HttpStatusCode } from '@shared/core-utils' -import { BooleanBothQuery, VideosCommonQuery } from '@shared/models' -import { loadLanguages, VIDEO_CATEGORIES, VIDEO_LANGUAGES, VIDEO_LICENCES, VIDEO_PRIVACIES } from '../../../server/initializers/constants' -import { VideoDetails, VideoPrivacy } from '../../models/videos' -import { buildAbsoluteFixturePath, dateIsValid, testImage, wait, webtorrentAdd } from '../miscs' -import { makeGetRequest, makePutBodyRequest, makeRawRequest, makeUploadRequest } from '../requests/requests' -import { waitJobs } from '../server/jobs' +import { VIDEO_CATEGORIES, VIDEO_LANGUAGES, VIDEO_LICENCES, VIDEO_PRIVACIES } from '../../../server/initializers/constants' +import { dateIsValid, testImage, webtorrentAdd } from '../miscs' +import { makeRawRequest } from '../requests/requests' +import { waitJobs } from '../server' import { ServerInfo } from '../server/servers' -import { xxxgetMyUserInformation } from '../users' - -loadLanguages() - -type VideoAttributes = { - name?: string - category?: number - licence?: number - language?: string - nsfw?: boolean - commentsEnabled?: boolean - downloadEnabled?: boolean - waitTranscoding?: boolean - description?: string - originallyPublishedAt?: string - tags?: string[] - channelId?: number - privacy?: VideoPrivacy - fixture?: string - support?: string - thumbnailfile?: string - previewfile?: string - scheduleUpdate?: { - updateAt: string - privacy?: VideoPrivacy - } -} - -function getVideoCategories (url: string) { - const path = '/api/v1/videos/categories' - - return makeGetRequest({ - url, - path, - statusCodeExpected: HttpStatusCode.OK_200 - }) -} - -function getVideoLicences (url: string) { - const path = '/api/v1/videos/licences' - - return makeGetRequest({ - url, - path, - statusCodeExpected: HttpStatusCode.OK_200 - }) -} - -function getVideoLanguages (url: string) { - const path = '/api/v1/videos/languages' - - return makeGetRequest({ - url, - path, - statusCodeExpected: HttpStatusCode.OK_200 - }) -} - -function getVideoPrivacies (url: string) { - const path = '/api/v1/videos/privacies' - - return makeGetRequest({ - url, - path, - statusCodeExpected: HttpStatusCode.OK_200 - }) -} - -function getVideo (url: string, id: number | string, expectedStatus = HttpStatusCode.OK_200) { - const path = '/api/v1/videos/' + id - - return request(url) - .get(path) - .set('Accept', 'application/json') - .expect(expectedStatus) -} - -async function getVideoIdFromUUID (url: string, uuid: string) { - const res = await getVideo(url, uuid) - - return res.body.id -} - -function getVideoFileMetadataUrl (url: string) { - return request(url) - .get('/') - .set('Accept', 'application/json') - .expect(HttpStatusCode.OK_200) - .expect('Content-Type', /json/) -} - -function viewVideo (url: string, id: number | string, expectedStatus = HttpStatusCode.NO_CONTENT_204, xForwardedFor?: string) { - const path = '/api/v1/videos/' + id + '/views' - - const req = request(url) - .post(path) - .set('Accept', 'application/json') - - if (xForwardedFor) { - req.set('X-Forwarded-For', xForwardedFor) - } - - return req.expect(expectedStatus) -} - -function getVideoWithToken (url: string, token: string, id: number | string, expectedStatus = HttpStatusCode.OK_200) { - const path = '/api/v1/videos/' + id - - return request(url) - .get(path) - .set('Authorization', 'Bearer ' + token) - .set('Accept', 'application/json') - .expect(expectedStatus) -} - -function getVideoDescription (url: string, descriptionPath: string) { - return request(url) - .get(descriptionPath) - .set('Accept', 'application/json') - .expect(HttpStatusCode.OK_200) - .expect('Content-Type', /json/) -} - -function getVideosList (url: string) { - const path = '/api/v1/videos' - - return request(url) - .get(path) - .query({ sort: 'name' }) - .set('Accept', 'application/json') - .expect(HttpStatusCode.OK_200) - .expect('Content-Type', /json/) -} - -function getVideosListWithToken (url: string, token: string, query: { nsfw?: BooleanBothQuery } = {}) { - const path = '/api/v1/videos' - - return request(url) - .get(path) - .set('Authorization', 'Bearer ' + token) - .query({ sort: 'name', ...query }) - .set('Accept', 'application/json') - .expect(HttpStatusCode.OK_200) - .expect('Content-Type', /json/) -} - -function getLocalVideos (url: string) { - const path = '/api/v1/videos' - - return request(url) - .get(path) - .query({ sort: 'name', filter: 'local' }) - .set('Accept', 'application/json') - .expect(HttpStatusCode.OK_200) - .expect('Content-Type', /json/) -} - -function getMyVideos (url: string, accessToken: string, start: number, count: number, sort?: string, search?: string) { - const path = '/api/v1/users/me/videos' - - const req = request(url) - .get(path) - .query({ start: start }) - .query({ count: count }) - .query({ search: search }) - - if (sort) req.query({ sort }) - - return req.set('Accept', 'application/json') - .set('Authorization', 'Bearer ' + accessToken) - .expect(HttpStatusCode.OK_200) - .expect('Content-Type', /json/) -} - -function getMyVideosWithFilter (url: string, accessToken: string, query: { isLive?: boolean }) { - const path = '/api/v1/users/me/videos' - - return makeGetRequest({ - url, - path, - token: accessToken, - query, - statusCodeExpected: HttpStatusCode.OK_200 - }) -} - -function getAccountVideos ( - url: string, - accessToken: string, - accountName: string, - start: number, - count: number, - sort?: string, - query: { - nsfw?: BooleanBothQuery - search?: string - } = {} -) { - const path = '/api/v1/accounts/' + accountName + '/videos' - - return makeGetRequest({ - url, - path, - query: { ...query, start, count, sort }, - token: accessToken, - statusCodeExpected: HttpStatusCode.OK_200 - }) -} - -function getVideoChannelVideos ( - url: string, - accessToken: string, - videoChannelName: string, - start: number, - count: number, - sort?: string, - query: { nsfw?: BooleanBothQuery } = {} -) { - const path = '/api/v1/video-channels/' + videoChannelName + '/videos' - - return makeGetRequest({ - url, - path, - query: { ...query, start, count, sort }, - token: accessToken, - statusCodeExpected: HttpStatusCode.OK_200 - }) -} - -function getVideosListPagination (url: string, start: number, count: number, sort?: string, skipCount?: boolean) { - const path = '/api/v1/videos' - - const req = request(url) - .get(path) - .query({ start: start }) - .query({ count: count }) - - if (sort) req.query({ sort }) - if (skipCount) req.query({ skipCount }) - - return req.set('Accept', 'application/json') - .expect(HttpStatusCode.OK_200) - .expect('Content-Type', /json/) -} - -function getVideosListSort (url: string, sort: string) { - const path = '/api/v1/videos' - - return request(url) - .get(path) - .query({ sort: sort }) - .set('Accept', 'application/json') - .expect(HttpStatusCode.OK_200) - .expect('Content-Type', /json/) -} - -function getVideosWithFilters (url: string, query: VideosCommonQuery) { - const path = '/api/v1/videos' - - return request(url) - .get(path) - .query(query) - .set('Accept', 'application/json') - .expect(HttpStatusCode.OK_200) - .expect('Content-Type', /json/) -} - -function removeVideo (url: string, token: string, id: number | string, expectedStatus = HttpStatusCode.NO_CONTENT_204) { - const path = '/api/v1/videos' - - return request(url) - .delete(path + '/' + id) - .set('Accept', 'application/json') - .set('Authorization', 'Bearer ' + token) - .expect(expectedStatus) -} - -async function removeAllVideos (server: ServerInfo) { - const resVideos = await getVideosList(server.url) - - for (const v of resVideos.body.data) { - await removeVideo(server.url, server.accessToken, v.id) - } -} +import { VideoEdit } from './videos-command' async function checkVideoFilesWereRemoved ( videoUUID: string, @@ -329,280 +39,20 @@ async function checkVideoFilesWereRemoved ( } } -async function uploadVideo ( - url: string, - accessToken: string, - videoAttributesArg: VideoAttributes, - specialStatus = HttpStatusCode.OK_200, - mode: 'legacy' | 'resumable' = 'legacy' -) { - let defaultChannelId = '1' - - try { - const res = await xxxgetMyUserInformation(url, accessToken) - defaultChannelId = res.body.videoChannels[0].id - } catch (e) { /* empty */ } - - // Override default attributes - const attributes = Object.assign({ - name: 'my super video', - category: 5, - licence: 4, - language: 'zh', - channelId: defaultChannelId, - nsfw: true, - waitTranscoding: false, - description: 'my super description', - support: 'my super support text', - tags: [ 'tag' ], - privacy: VideoPrivacy.PUBLIC, - commentsEnabled: true, - downloadEnabled: true, - fixture: 'video_short.webm' - }, videoAttributesArg) - - const res = mode === 'legacy' - ? await buildLegacyUpload(url, accessToken, attributes, specialStatus) - : await buildResumeUpload(url, accessToken, attributes, specialStatus) - - // Wait torrent generation - if (specialStatus === HttpStatusCode.OK_200) { - let video: VideoDetails - do { - const resVideo = await getVideoWithToken(url, accessToken, res.body.video.uuid) - video = resVideo.body - - await wait(50) - } while (!video.files[0].torrentUrl) - } - - return res -} - function checkUploadVideoParam ( - url: string, + server: ServerInfo, token: string, - attributes: Partial, - specialStatus = HttpStatusCode.OK_200, + attributes: Partial, + expectedStatus = HttpStatusCode.OK_200, mode: 'legacy' | 'resumable' = 'legacy' ) { return mode === 'legacy' - ? buildLegacyUpload(url, token, attributes, specialStatus) - : buildResumeUpload(url, token, attributes, specialStatus) -} - -async function buildLegacyUpload (url: string, token: string, attributes: VideoAttributes, specialStatus = HttpStatusCode.OK_200) { - const path = '/api/v1/videos/upload' - const req = request(url) - .post(path) - .set('Accept', 'application/json') - .set('Authorization', 'Bearer ' + token) - - buildUploadReq(req, attributes) - - if (attributes.fixture !== undefined) { - req.attach('videofile', buildAbsoluteFixturePath(attributes.fixture)) - } - - return req.expect(specialStatus) -} - -async function buildResumeUpload (url: string, token: string, attributes: VideoAttributes, specialStatus = HttpStatusCode.OK_200) { - let size = 0 - let videoFilePath: string - let mimetype = 'video/mp4' - - if (attributes.fixture) { - videoFilePath = buildAbsoluteFixturePath(attributes.fixture) - size = (await stat(videoFilePath)).size - - if (videoFilePath.endsWith('.mkv')) { - mimetype = 'video/x-matroska' - } else if (videoFilePath.endsWith('.webm')) { - mimetype = 'video/webm' - } - } - - const initializeSessionRes = await prepareResumableUpload({ url, token, attributes, size, mimetype }) - const initStatus = initializeSessionRes.status - - if (videoFilePath && initStatus === HttpStatusCode.CREATED_201) { - const locationHeader = initializeSessionRes.header['location'] - expect(locationHeader).to.not.be.undefined - - const pathUploadId = locationHeader.split('?')[1] - - return sendResumableChunks({ url, token, pathUploadId, videoFilePath, size, specialStatus }) - } - - const expectedInitStatus = specialStatus === HttpStatusCode.OK_200 - ? HttpStatusCode.CREATED_201 - : specialStatus - - expect(initStatus).to.equal(expectedInitStatus) - - return initializeSessionRes -} - -async function prepareResumableUpload (options: { - url: string - token: string - attributes: VideoAttributes - size: number - mimetype: string -}) { - const { url, token, attributes, size, mimetype } = options - - const path = '/api/v1/videos/upload-resumable' - - const req = request(url) - .post(path) - .set('Authorization', 'Bearer ' + token) - .set('X-Upload-Content-Type', mimetype) - .set('X-Upload-Content-Length', size.toString()) - - buildUploadReq(req, attributes) - - if (attributes.fixture) { - req.field('filename', attributes.fixture) - } - - return req -} - -function sendResumableChunks (options: { - url: string - token: string - pathUploadId: string - videoFilePath: string - size: number - specialStatus?: HttpStatusCode - contentLength?: number - contentRangeBuilder?: (start: number, chunk: any) => string -}) { - const { url, token, pathUploadId, videoFilePath, size, specialStatus, contentLength, contentRangeBuilder } = options - - const expectedStatus = specialStatus || HttpStatusCode.OK_200 - - const path = '/api/v1/videos/upload-resumable' - let start = 0 - - const readable = createReadStream(videoFilePath, { highWaterMark: 8 * 1024 }) - return new Promise((resolve, reject) => { - readable.on('data', async function onData (chunk) { - readable.pause() - - const headers = { - 'Authorization': 'Bearer ' + token, - 'Content-Type': 'application/octet-stream', - 'Content-Range': contentRangeBuilder - ? contentRangeBuilder(start, chunk) - : `bytes ${start}-${start + chunk.length - 1}/${size}`, - 'Content-Length': contentLength ? contentLength + '' : chunk.length + '' - } - - const res = await got({ - url, - method: 'put', - headers, - path: path + '?' + pathUploadId, - body: chunk, - responseType: 'json', - throwHttpErrors: false - }) - - start += chunk.length - - if (res.statusCode === expectedStatus) { - return resolve(res) - } - - if (res.statusCode !== HttpStatusCode.PERMANENT_REDIRECT_308) { - readable.off('data', onData) - return reject(new Error('Incorrect transient behaviour sending intermediary chunks')) - } - - readable.resume() - }) - }) -} - -function updateVideo ( - url: string, - accessToken: string, - id: number | string, - attributes: VideoAttributes, - statusCodeExpected = HttpStatusCode.NO_CONTENT_204 -) { - const path = '/api/v1/videos/' + id - const body = {} - - if (attributes.name) body['name'] = attributes.name - if (attributes.category) body['category'] = attributes.category - if (attributes.licence) body['licence'] = attributes.licence - if (attributes.language) body['language'] = attributes.language - if (attributes.nsfw !== undefined) body['nsfw'] = JSON.stringify(attributes.nsfw) - if (attributes.commentsEnabled !== undefined) body['commentsEnabled'] = JSON.stringify(attributes.commentsEnabled) - if (attributes.downloadEnabled !== undefined) body['downloadEnabled'] = JSON.stringify(attributes.downloadEnabled) - if (attributes.originallyPublishedAt !== undefined) body['originallyPublishedAt'] = attributes.originallyPublishedAt - if (attributes.description) body['description'] = attributes.description - if (attributes.tags) body['tags'] = attributes.tags - if (attributes.privacy) body['privacy'] = attributes.privacy - if (attributes.channelId) body['channelId'] = attributes.channelId - if (attributes.scheduleUpdate) body['scheduleUpdate'] = attributes.scheduleUpdate - - // Upload request - if (attributes.thumbnailfile || attributes.previewfile) { - const attaches: any = {} - if (attributes.thumbnailfile) attaches.thumbnailfile = attributes.thumbnailfile - if (attributes.previewfile) attaches.previewfile = attributes.previewfile - - return makeUploadRequest({ - url, - method: 'PUT', - path, - token: accessToken, - fields: body, - attaches, - statusCodeExpected - }) - } - - return makePutBodyRequest({ - url, - path, - fields: body, - token: accessToken, - statusCodeExpected - }) -} - -function rateVideo (url: string, accessToken: string, id: number | string, rating: string, specialStatus = HttpStatusCode.NO_CONTENT_204) { - const path = '/api/v1/videos/' + id + '/rate' - - return request(url) - .put(path) - .set('Accept', 'application/json') - .set('Authorization', 'Bearer ' + accessToken) - .send({ rating }) - .expect(specialStatus) -} - -function parseTorrentVideo (server: ServerInfo, videoUUID: string, resolution: number) { - return new Promise((res, rej) => { - const torrentName = videoUUID + '-' + resolution + '.torrent' - const torrentPath = server.serversCommand.buildDirectory(join('torrents', torrentName)) - - readFile(torrentPath, (err, data) => { - if (err) return rej(err) - - return res(parseTorrent(data)) - }) - }) + ? server.videosCommand.buildLegacyUpload({ token, attributes, expectedStatus }) + : server.videosCommand.buildResumeUpload({ token, attributes, expectedStatus }) } async function completeVideoCheck ( - url: string, + server: ServerInfo, video: any, attributes: { name: string @@ -644,7 +94,7 @@ async function completeVideoCheck ( if (!attributes.likes) attributes.likes = 0 if (!attributes.dislikes) attributes.dislikes = 0 - const host = new URL(url).host + const host = new URL(server.url).host const originHost = attributes.account.host expect(video.name).to.equal(attributes.name) @@ -681,8 +131,7 @@ async function completeVideoCheck ( expect(video.originallyPublishedAt).to.be.null } - const res = await getVideo(url, video.uuid) - const videoDetails: VideoDetails = res.body + const videoDetails = await server.videosCommand.get({ id: video.uuid }) expect(videoDetails.files).to.have.lengthOf(attributes.files.length) expect(videoDetails.tags).to.deep.equal(attributes.tags) @@ -738,148 +187,33 @@ async function completeVideoCheck ( } expect(videoDetails.thumbnailPath).to.exist - await testImage(url, attributes.thumbnailfile || attributes.fixture, videoDetails.thumbnailPath) + await testImage(server.url, attributes.thumbnailfile || attributes.fixture, videoDetails.thumbnailPath) if (attributes.previewfile) { expect(videoDetails.previewPath).to.exist - await testImage(url, attributes.previewfile, videoDetails.previewPath) + await testImage(server.url, attributes.previewfile, videoDetails.previewPath) } } -async function videoUUIDToId (url: string, id: number | string) { - if (validator.isUUID('' + id) === false) return id - - const res = await getVideo(url, id) - return res.body.id -} - -async function uploadVideoAndGetId (options: { - server: ServerInfo - videoName: string - nsfw?: boolean - privacy?: VideoPrivacy - token?: string - fixture?: string -}) { - const videoAttrs: any = { name: options.videoName } - if (options.nsfw) videoAttrs.nsfw = options.nsfw - if (options.privacy) videoAttrs.privacy = options.privacy - if (options.fixture) videoAttrs.fixture = options.fixture - - const res = await uploadVideo(options.server.url, options.token || options.server.accessToken, videoAttrs) - - return res.body.video as { id: number, uuid: string, shortUUID: string } -} - -async function getLocalIdByUUID (url: string, uuid: string) { - const res = await getVideo(url, uuid) - - return res.body.id -} - // serverNumber starts from 1 -async function uploadRandomVideoOnServers (servers: ServerInfo[], serverNumber: number, additionalParams: any = {}) { +async function uploadRandomVideoOnServers ( + servers: ServerInfo[], + serverNumber: number, + additionalParams?: VideoEdit & { prefixName?: string } +) { const server = servers.find(s => s.serverNumber === serverNumber) - const res = await uploadRandomVideo(server, false, additionalParams) + const res = await server.videosCommand.randomUpload({ wait: false, ...additionalParams }) await waitJobs(servers) return res } -async function uploadRandomVideo (server: ServerInfo, wait = true, additionalParams: any = {}) { - const prefixName = additionalParams.prefixName || '' - const name = prefixName + buildUUID() - - const data = Object.assign({ name }, additionalParams) - const res = await uploadVideo(server.url, server.accessToken, data) - - if (wait) await waitJobs([ server ]) - - return { uuid: res.body.video.uuid, name } -} - // --------------------------------------------------------------------------- export { - getVideoDescription, - getVideoCategories, - uploadRandomVideo, - getVideoLicences, - videoUUIDToId, - getVideoPrivacies, - getVideoLanguages, - getMyVideos, - getAccountVideos, - getVideoChannelVideos, - getVideo, - getVideoFileMetadataUrl, - getVideoWithToken, - getVideosList, - removeAllVideos, checkUploadVideoParam, - getVideosListPagination, - getVideosListSort, - removeVideo, - getVideosListWithToken, - uploadVideo, - sendResumableChunks, - getVideosWithFilters, - uploadRandomVideoOnServers, - updateVideo, - rateVideo, - viewVideo, - parseTorrentVideo, - getLocalVideos, completeVideoCheck, - checkVideoFilesWereRemoved, - getMyVideosWithFilter, - uploadVideoAndGetId, - getLocalIdByUUID, - getVideoIdFromUUID, - prepareResumableUpload -} - -// --------------------------------------------------------------------------- - -function buildUploadReq (req: request.Test, attributes: VideoAttributes) { - - for (const key of [ 'name', 'support', 'channelId', 'description', 'originallyPublishedAt' ]) { - if (attributes[key] !== undefined) { - req.field(key, attributes[key]) - } - } - - for (const key of [ 'nsfw', 'commentsEnabled', 'downloadEnabled', 'waitTranscoding' ]) { - if (attributes[key] !== undefined) { - req.field(key, JSON.stringify(attributes[key])) - } - } - - for (const key of [ 'language', 'privacy', 'category', 'licence' ]) { - if (attributes[key] !== undefined) { - req.field(key, attributes[key].toString()) - } - } - - const tags = attributes.tags || [] - for (let i = 0; i < tags.length; i++) { - req.field('tags[' + i + ']', attributes.tags[i]) - } - - for (const key of [ 'thumbnailfile', 'previewfile' ]) { - if (attributes[key] !== undefined) { - req.attach(key, buildAbsoluteFixturePath(attributes[key])) - } - } - - if (attributes.scheduleUpdate) { - if (attributes.scheduleUpdate.updateAt) { - req.field('scheduleUpdate[updateAt]', attributes.scheduleUpdate.updateAt) - } - - if (attributes.scheduleUpdate.privacy) { - req.field('scheduleUpdate[privacy]', attributes.scheduleUpdate.privacy) - } - } + uploadRandomVideoOnServers, + checkVideoFilesWereRemoved } diff --git a/shared/models/search/videos-common-query.model.ts b/shared/models/search/videos-common-query.model.ts index bd02489ea..179266338 100644 --- a/shared/models/search/videos-common-query.model.ts +++ b/shared/models/search/videos-common-query.model.ts @@ -21,6 +21,8 @@ export interface VideosCommonQuery { tagsAllOf?: string[] filter?: VideoFilter + + skipCount?: boolean } export interface VideosWithSearchCommonQuery extends VideosCommonQuery { diff --git a/shared/models/videos/video-update.model.ts b/shared/models/videos/video-update.model.ts index e21ccae04..86653b959 100644 --- a/shared/models/videos/video-update.model.ts +++ b/shared/models/videos/video-update.model.ts @@ -1,5 +1,6 @@ import { VideoPrivacy } from './video-privacy.enum' import { VideoScheduleUpdate } from './video-schedule-update.model' + export interface VideoUpdate { name?: string category?: number -- cgit v1.2.3 From 89d241a79c262b9775c233b73cff080043ebb5e6 Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Fri, 16 Jul 2021 09:04:35 +0200 Subject: Shorter server command names --- scripts/benchmark.ts | 14 +- server/tests/api/activitypub/cleaner.ts | 52 ++-- server/tests/api/activitypub/client.ts | 6 +- server/tests/api/activitypub/fetch.ts | 18 +- server/tests/api/activitypub/refresher.ts | 52 ++-- server/tests/api/activitypub/security.ts | 8 +- server/tests/api/check-params/abuses.ts | 28 +-- server/tests/api/check-params/accounts.ts | 2 +- server/tests/api/check-params/blocklist.ts | 4 +- server/tests/api/check-params/bulk.ts | 4 +- server/tests/api/check-params/config.ts | 4 +- server/tests/api/check-params/contact-form.ts | 2 +- server/tests/api/check-params/custom-pages.ts | 4 +- server/tests/api/check-params/debug.ts | 4 +- server/tests/api/check-params/follows.ts | 4 +- server/tests/api/check-params/jobs.ts | 4 +- server/tests/api/check-params/live.ts | 30 +-- server/tests/api/check-params/logs.ts | 4 +- server/tests/api/check-params/plugins.ts | 8 +- server/tests/api/check-params/redundancy.ts | 10 +- server/tests/api/check-params/search.ts | 2 +- server/tests/api/check-params/services.ts | 20 +- server/tests/api/check-params/upload-quota.ts | 30 +-- .../tests/api/check-params/user-subscriptions.ts | 4 +- server/tests/api/check-params/users.ts | 74 +++--- server/tests/api/check-params/video-blacklist.ts | 60 ++--- server/tests/api/check-params/video-captions.ts | 8 +- server/tests/api/check-params/video-channels.ts | 8 +- server/tests/api/check-params/video-comments.ts | 20 +- server/tests/api/check-params/video-imports.ts | 16 +- server/tests/api/check-params/video-playlists.ts | 16 +- server/tests/api/check-params/videos-filter.ts | 8 +- server/tests/api/check-params/videos-history.ts | 2 +- server/tests/api/check-params/videos-overviews.ts | 6 +- server/tests/api/check-params/videos.ts | 34 +-- server/tests/api/live/live-constraints.ts | 24 +- server/tests/api/live/live-permanent.ts | 32 +-- server/tests/api/live/live-save-replay.ts | 52 ++-- server/tests/api/live/live-socket-messages.ts | 38 +-- server/tests/api/live/live-views.ts | 20 +- server/tests/api/live/live.ts | 72 +++--- server/tests/api/moderation/abuses.ts | 96 ++++---- .../tests/api/moderation/blocklist-notification.ts | 46 ++-- server/tests/api/moderation/blocklist.ts | 76 +++--- server/tests/api/moderation/video-blacklist.ts | 58 ++--- .../tests/api/notifications/admin-notifications.ts | 12 +- .../api/notifications/comments-notifications.ts | 92 ++++---- .../api/notifications/moderation-notifications.ts | 118 +++++----- .../tests/api/notifications/notifications-api.ts | 42 ++-- .../tests/api/notifications/user-notifications.ts | 40 ++-- server/tests/api/redundancy/manage-redundancy.ts | 14 +- .../tests/api/redundancy/redundancy-constraints.ts | 24 +- server/tests/api/redundancy/redundancy.ts | 62 ++--- .../search/search-activitypub-video-channels.ts | 32 +-- .../search/search-activitypub-video-playlists.ts | 28 +-- .../tests/api/search/search-activitypub-videos.ts | 14 +- server/tests/api/search/search-channels.ts | 6 +- server/tests/api/search/search-index.ts | 14 +- server/tests/api/search/search-playlists.ts | 20 +- server/tests/api/search/search-videos.ts | 46 ++-- server/tests/api/server/auto-follows.ts | 20 +- server/tests/api/server/bulk.ts | 48 ++-- server/tests/api/server/config.ts | 36 +-- server/tests/api/server/contact-form.ts | 2 +- server/tests/api/server/email.ts | 42 ++-- server/tests/api/server/follow-constraints.ts | 58 ++--- server/tests/api/server/follows-moderation.ts | 18 +- server/tests/api/server/follows.ts | 72 +++--- server/tests/api/server/handle-down.ts | 58 ++--- server/tests/api/server/homepage.ts | 4 +- server/tests/api/server/jobs.ts | 12 +- server/tests/api/server/logs.ts | 28 +-- server/tests/api/server/plugins.ts | 20 +- server/tests/api/server/reverse-proxy.ts | 42 ++-- server/tests/api/server/services.ts | 22 +- server/tests/api/server/stats.ts | 60 ++--- server/tests/api/server/tracker.ts | 4 +- server/tests/api/users/user-subscriptions.ts | 34 +-- server/tests/api/users/users-multiple-servers.ts | 40 ++-- server/tests/api/users/users-verification.ts | 34 +-- server/tests/api/users/users.ts | 262 ++++++++++----------- server/tests/api/videos/audio-only.ts | 8 +- server/tests/api/videos/multiple-servers.ts | 168 ++++++------- server/tests/api/videos/resumable-upload.ts | 18 +- server/tests/api/videos/single-server.ts | 90 +++---- server/tests/api/videos/video-captions.ts | 24 +- server/tests/api/videos/video-change-ownership.ts | 50 ++-- server/tests/api/videos/video-channels.ts | 92 ++++---- server/tests/api/videos/video-comments.ts | 8 +- server/tests/api/videos/video-description.ts | 16 +- server/tests/api/videos/video-hls.ts | 22 +- server/tests/api/videos/video-imports.ts | 44 ++-- server/tests/api/videos/video-nsfw.ts | 52 ++-- .../tests/api/videos/video-playlist-thumbnails.ts | 36 +-- server/tests/api/videos/video-playlists.ts | 184 +++++++-------- server/tests/api/videos/video-privacy.ts | 56 ++--- server/tests/api/videos/video-schedule-update.ts | 20 +- server/tests/api/videos/video-transcoder.ts | 122 +++++----- server/tests/api/videos/videos-filter.ts | 10 +- server/tests/api/videos/videos-history.ts | 30 +-- server/tests/api/videos/videos-overview.ts | 24 +- server/tests/api/videos/videos-views-cleaner.ts | 22 +- server/tests/cli/create-import-video-file-job.ts | 22 +- server/tests/cli/create-transcoding-job.ts | 38 +-- server/tests/cli/optimize-old-videos.ts | 18 +- server/tests/cli/peertube.ts | 28 +-- server/tests/cli/plugins.ts | 10 +- server/tests/cli/prune-storage.ts | 30 +-- server/tests/cli/regenerate-thumbnails.ts | 20 +- server/tests/cli/reset-password.ts | 6 +- server/tests/cli/update-host.ts | 24 +- server/tests/client.ts | 76 +++--- server/tests/external-plugins/auth-ldap.ts | 34 +-- server/tests/external-plugins/auto-block-videos.ts | 22 +- server/tests/external-plugins/auto-mute.ts | 34 +-- server/tests/feeds/feeds.ts | 110 ++++----- server/tests/misc-endpoints.ts | 14 +- server/tests/plugins/action-hooks.ts | 40 ++-- server/tests/plugins/external-auth.ts | 66 +++--- server/tests/plugins/filter-hooks.ts | 160 ++++++------- server/tests/plugins/html-injection.ts | 2 +- server/tests/plugins/id-and-pass-auth.ts | 64 ++--- server/tests/plugins/plugin-helpers.ts | 42 ++-- server/tests/plugins/plugin-router.ts | 4 +- server/tests/plugins/plugin-storage.ts | 12 +- server/tests/plugins/plugin-transcoding.ts | 52 ++-- server/tests/plugins/plugin-unloading.ts | 6 +- server/tests/plugins/translations.ts | 2 +- server/tests/plugins/video-constants.ts | 32 +-- server/tools/cli.ts | 10 +- server/tools/peertube-import-videos.ts | 10 +- server/tools/peertube-plugins.ts | 8 +- server/tools/peertube-redundancy.ts | 10 +- server/tools/peertube-upload.ts | 2 +- server/tools/test-live.ts | 8 +- shared/extra-utils/miscs/checks.ts | 2 +- shared/extra-utils/miscs/webtorrent.ts | 2 +- shared/extra-utils/server/follows.ts | 4 +- shared/extra-utils/server/jobs.ts | 4 +- shared/extra-utils/server/plugins-command.ts | 2 +- shared/extra-utils/server/plugins.ts | 2 +- shared/extra-utils/server/servers-command.ts | 6 +- shared/extra-utils/server/servers.ts | 230 +++++++++--------- shared/extra-utils/users/accounts.ts | 2 +- shared/extra-utils/users/login-command.ts | 12 +- shared/extra-utils/users/login.ts | 2 +- shared/extra-utils/users/notifications.ts | 20 +- shared/extra-utils/users/users-command.ts | 4 +- shared/extra-utils/videos/channels.ts | 4 +- shared/extra-utils/videos/live-command.ts | 8 +- shared/extra-utils/videos/live.ts | 4 +- shared/extra-utils/videos/playlists-command.ts | 2 +- shared/extra-utils/videos/streaming-playlists.ts | 6 +- shared/extra-utils/videos/videos-command.ts | 2 +- shared/extra-utils/videos/videos.ts | 10 +- 155 files changed, 2502 insertions(+), 2502 deletions(-) diff --git a/scripts/benchmark.ts b/scripts/benchmark.ts index d9e4a08ab..1d980063b 100644 --- a/scripts/benchmark.ts +++ b/scripts/benchmark.ts @@ -210,29 +210,29 @@ async function prepare () { } for (let i = 0; i < 10; i++) { - await server.videosCommand.upload({ attributes: { ...attributes, name: 'my super video ' + i } }) + await server.videos.upload({ attributes: { ...attributes, name: 'my super video ' + i } }) } - const { data } = await server.videosCommand.list() + const { data } = await server.videos.list() video = data.find(v => v.name === 'my super video 1') for (let i = 0; i < 10; i++) { const text = 'my super first comment' - const created = await server.commentsCommand.createThread({ videoId: video.id, text }) + const created = await server.comments.createThread({ videoId: video.id, text }) threadId = created.id const text1 = 'my super answer to thread 1' - const child = await server.commentsCommand.addReply({ videoId: video.id, toCommentId: threadId, text: text1 }) + const child = await server.comments.addReply({ videoId: video.id, toCommentId: threadId, text: text1 }) const text2 = 'my super answer to answer of thread 1' - await server.commentsCommand.addReply({ videoId: video.id, toCommentId: child.id, text: text2 }) + await server.comments.addReply({ videoId: video.id, toCommentId: child.id, text: text2 }) const text3 = 'my second answer to thread 1' - await server.commentsCommand.addReply({ videoId: video.id, toCommentId: threadId, text: text3 }) + await server.comments.addReply({ videoId: video.id, toCommentId: threadId, text: text3 }) } for (const caption of [ 'ar', 'fr', 'en', 'zh' ]) { - await server.captionsCommand.createVideoCaption({ + await server.captions.createVideoCaption({ language: caption, videoId: video.id, fixture: 'subtitle-good2.vtt' diff --git a/server/tests/api/activitypub/cleaner.ts b/server/tests/api/activitypub/cleaner.ts index dcf758711..1421824da 100644 --- a/server/tests/api/activitypub/cleaner.ts +++ b/server/tests/api/activitypub/cleaner.ts @@ -46,9 +46,9 @@ describe('Test AP cleaner', function () { // Create 1 comment per video // Update 1 remote URL and 1 local URL on - videoUUID1 = (await servers[0].videosCommand.quickUpload({ name: 'server 1' })).uuid - videoUUID2 = (await servers[1].videosCommand.quickUpload({ name: 'server 2' })).uuid - videoUUID3 = (await servers[2].videosCommand.quickUpload({ name: 'server 3' })).uuid + videoUUID1 = (await servers[0].videos.quickUpload({ name: 'server 1' })).uuid + videoUUID2 = (await servers[1].videos.quickUpload({ name: 'server 2' })).uuid + videoUUID3 = (await servers[2].videos.quickUpload({ name: 'server 3' })).uuid videoUUIDs = [ videoUUID1, videoUUID2, videoUUID3 ] @@ -56,8 +56,8 @@ describe('Test AP cleaner', function () { for (const server of servers) { for (const uuid of videoUUIDs) { - await server.videosCommand.rate({ id: uuid, rating: 'like' }) - await server.commentsCommand.createThread({ videoId: uuid, text: 'comment' }) + await server.videos.rate({ id: uuid, rating: 'like' }) + await server.comments.createThread({ videoId: uuid, text: 'comment' }) } } @@ -67,7 +67,7 @@ describe('Test AP cleaner', function () { it('Should have the correct likes', async function () { for (const server of servers) { for (const uuid of videoUUIDs) { - const video = await server.videosCommand.get({ id: uuid }) + const video = await server.videos.get({ id: uuid }) expect(video.likes).to.equal(3) expect(video.dislikes).to.equal(0) @@ -78,9 +78,9 @@ describe('Test AP cleaner', function () { it('Should destroy server 3 internal likes and correctly clean them', async function () { this.timeout(20000) - await servers[2].sqlCommand.deleteAll('accountVideoRate') + await servers[2].sql.deleteAll('accountVideoRate') for (const uuid of videoUUIDs) { - await servers[2].sqlCommand.setVideoField(uuid, 'likes', '0') + await servers[2].sql.setVideoField(uuid, 'likes', '0') } await wait(5000) @@ -88,14 +88,14 @@ describe('Test AP cleaner', function () { // Updated rates of my video { - const video = await servers[0].videosCommand.get({ id: videoUUID1 }) + const video = await servers[0].videos.get({ id: videoUUID1 }) expect(video.likes).to.equal(2) expect(video.dislikes).to.equal(0) } // Did not update rates of a remote video { - const video = await servers[0].videosCommand.get({ id: videoUUID2 }) + const video = await servers[0].videos.get({ id: videoUUID2 }) expect(video.likes).to.equal(3) expect(video.dislikes).to.equal(0) } @@ -106,7 +106,7 @@ describe('Test AP cleaner', function () { for (const server of servers) { for (const uuid of videoUUIDs) { - await server.videosCommand.rate({ id: uuid, rating: 'dislike' }) + await server.videos.rate({ id: uuid, rating: 'dislike' }) } } @@ -114,7 +114,7 @@ describe('Test AP cleaner', function () { for (const server of servers) { for (const uuid of videoUUIDs) { - const video = await server.videosCommand.get({ id: uuid }) + const video = await server.videos.get({ id: uuid }) expect(video.likes).to.equal(0) expect(video.dislikes).to.equal(3) } @@ -124,10 +124,10 @@ describe('Test AP cleaner', function () { it('Should destroy server 3 internal dislikes and correctly clean them', async function () { this.timeout(20000) - await servers[2].sqlCommand.deleteAll('accountVideoRate') + await servers[2].sql.deleteAll('accountVideoRate') for (const uuid of videoUUIDs) { - await servers[2].sqlCommand.setVideoField(uuid, 'dislikes', '0') + await servers[2].sql.setVideoField(uuid, 'dislikes', '0') } await wait(5000) @@ -135,14 +135,14 @@ describe('Test AP cleaner', function () { // Updated rates of my video { - const video = await servers[0].videosCommand.get({ id: videoUUID1 }) + const video = await servers[0].videos.get({ id: videoUUID1 }) expect(video.likes).to.equal(0) expect(video.dislikes).to.equal(2) } // Did not update rates of a remote video { - const video = await servers[0].videosCommand.get({ id: videoUUID2 }) + const video = await servers[0].videos.get({ id: videoUUID2 }) expect(video.likes).to.equal(0) expect(video.dislikes).to.equal(3) } @@ -151,15 +151,15 @@ describe('Test AP cleaner', function () { it('Should destroy server 3 internal shares and correctly clean them', async function () { this.timeout(20000) - const preCount = await servers[0].sqlCommand.getCount('videoShare') + const preCount = await servers[0].sql.getCount('videoShare') expect(preCount).to.equal(6) - await servers[2].sqlCommand.deleteAll('videoShare') + await servers[2].sql.deleteAll('videoShare') await wait(5000) await waitJobs(servers) // Still 6 because we don't have remote shares on local videos - const postCount = await servers[0].sqlCommand.getCount('videoShare') + const postCount = await servers[0].sql.getCount('videoShare') expect(postCount).to.equal(6) }) @@ -167,17 +167,17 @@ describe('Test AP cleaner', function () { this.timeout(20000) { - const { total } = await servers[0].commentsCommand.listThreads({ videoId: videoUUID1 }) + const { total } = await servers[0].comments.listThreads({ videoId: videoUUID1 }) expect(total).to.equal(3) } - await servers[2].sqlCommand.deleteAll('videoComment') + await servers[2].sql.deleteAll('videoComment') await wait(5000) await waitJobs(servers) { - const { total } = await servers[0].commentsCommand.listThreads({ videoId: videoUUID1 }) + const { total } = await servers[0].comments.listThreads({ videoId: videoUUID1 }) expect(total).to.equal(2) } }) @@ -188,7 +188,7 @@ describe('Test AP cleaner', function () { async function check (like: string, ofServerUrl: string, urlSuffix: string, remote: 'true' | 'false') { const query = `SELECT "videoId", "accountVideoRate".url FROM "accountVideoRate" ` + `INNER JOIN video ON "accountVideoRate"."videoId" = video.id AND remote IS ${remote} WHERE "accountVideoRate"."url" LIKE '${like}'` - const res = await servers[0].sqlCommand.selectQuery(query) + const res = await servers[0].sql.selectQuery(query) for (const rate of res) { const matcher = new RegExp(`^${ofServerUrl}/accounts/root/dislikes/\\d+${urlSuffix}$`) @@ -217,7 +217,7 @@ describe('Test AP cleaner', function () { { const query = `UPDATE "accountVideoRate" SET url = url || 'stan'` - await servers[1].sqlCommand.updateQuery(query) + await servers[1].sql.updateQuery(query) await wait(5000) await waitJobs(servers) @@ -234,7 +234,7 @@ describe('Test AP cleaner', function () { const query = `SELECT "videoId", "videoComment".url, uuid as "videoUUID" FROM "videoComment" ` + `INNER JOIN video ON "videoComment"."videoId" = video.id AND remote IS ${remote} WHERE "videoComment"."url" LIKE '${like}'` - const res = await servers[0].sqlCommand.selectQuery(query) + const res = await servers[0].sql.selectQuery(query) for (const comment of res) { const matcher = new RegExp(`${ofServerUrl}/videos/watch/${comment.videoUUID}/comments/\\d+${urlSuffix}`) @@ -260,7 +260,7 @@ describe('Test AP cleaner', function () { { const query = `UPDATE "videoComment" SET url = url || 'kyle'` - await servers[1].sqlCommand.updateQuery(query) + await servers[1].sql.updateQuery(query) await wait(5000) await waitJobs(servers) diff --git a/server/tests/api/activitypub/client.ts b/server/tests/api/activitypub/client.ts index 0190df04c..5845045a3 100644 --- a/server/tests/api/activitypub/client.ts +++ b/server/tests/api/activitypub/client.ts @@ -68,12 +68,12 @@ describe('Test activitypub', function () { await setDefaultVideoChannel(servers) { - video = await await servers[0].videosCommand.quickUpload({ name: 'video' }) + video = await await servers[0].videos.quickUpload({ name: 'video' }) } { - const attributes = { displayName: 'playlist', privacy: VideoPlaylistPrivacy.PUBLIC, videoChannelId: servers[0].videoChannel.id } - playlist = await servers[0].playlistsCommand.create({ attributes }) + const attributes = { displayName: 'playlist', privacy: VideoPlaylistPrivacy.PUBLIC, videoChannelId: servers[0].store.channel.id } + playlist = await servers[0].playlists.create({ attributes }) } await doubleFollow(servers[0], servers[1]) diff --git a/server/tests/api/activitypub/fetch.ts b/server/tests/api/activitypub/fetch.ts index 5ab4a85d7..34694a773 100644 --- a/server/tests/api/activitypub/fetch.ts +++ b/server/tests/api/activitypub/fetch.ts @@ -21,24 +21,24 @@ describe('Test ActivityPub fetcher', function () { const user = { username: 'user1', password: 'password' } for (const server of servers) { - await server.usersCommand.create({ username: user.username, password: user.password }) + await server.users.create({ username: user.username, password: user.password }) } - const userAccessToken = await servers[0].loginCommand.getAccessToken(user) + const userAccessToken = await servers[0].login.getAccessToken(user) - await servers[0].videosCommand.upload({ attributes: { name: 'video root' } }) - const { uuid } = await servers[0].videosCommand.upload({ attributes: { name: 'bad video root' } }) - await servers[0].videosCommand.upload({ token: userAccessToken, attributes: { name: 'video user' } }) + await servers[0].videos.upload({ attributes: { name: 'video root' } }) + const { uuid } = await servers[0].videos.upload({ attributes: { name: 'bad video root' } }) + await servers[0].videos.upload({ token: userAccessToken, attributes: { name: 'video user' } }) { const to = 'http://localhost:' + servers[0].port + '/accounts/user1' const value = 'http://localhost:' + servers[1].port + '/accounts/user1' - await servers[0].sqlCommand.setActorField(to, 'url', value) + await servers[0].sql.setActorField(to, 'url', value) } { const value = 'http://localhost:' + servers[2].port + '/videos/watch/' + uuid - await servers[0].sqlCommand.setVideoField(uuid, 'url', value) + await servers[0].sql.setVideoField(uuid, 'url', value) } }) @@ -49,7 +49,7 @@ describe('Test ActivityPub fetcher', function () { await waitJobs(servers) { - const { total, data } = await servers[0].videosCommand.list({ sort: 'createdAt' }) + const { total, data } = await servers[0].videos.list({ sort: 'createdAt' }) expect(total).to.equal(3) expect(data[0].name).to.equal('video root') @@ -58,7 +58,7 @@ describe('Test ActivityPub fetcher', function () { } { - const { total, data } = await servers[1].videosCommand.list({ sort: 'createdAt' }) + const { total, data } = await servers[1].videos.list({ sort: 'createdAt' }) expect(total).to.equal(1) expect(data[0].name).to.equal('video root') diff --git a/server/tests/api/activitypub/refresher.ts b/server/tests/api/activitypub/refresher.ts index 5af4b1edb..d2f71e857 100644 --- a/server/tests/api/activitypub/refresher.ts +++ b/server/tests/api/activitypub/refresher.ts @@ -34,28 +34,28 @@ describe('Test AP refresher', function () { await setDefaultVideoChannel(servers) { - videoUUID1 = (await servers[1].videosCommand.quickUpload({ name: 'video1' })).uuid - videoUUID2 = (await servers[1].videosCommand.quickUpload({ name: 'video2' })).uuid - videoUUID3 = (await servers[1].videosCommand.quickUpload({ name: 'video3' })).uuid + videoUUID1 = (await servers[1].videos.quickUpload({ name: 'video1' })).uuid + videoUUID2 = (await servers[1].videos.quickUpload({ name: 'video2' })).uuid + videoUUID3 = (await servers[1].videos.quickUpload({ name: 'video3' })).uuid } { - const token1 = await servers[1].usersCommand.generateUserAndToken('user1') - await servers[1].videosCommand.upload({ token: token1, attributes: { name: 'video4' } }) + const token1 = await servers[1].users.generateUserAndToken('user1') + await servers[1].videos.upload({ token: token1, attributes: { name: 'video4' } }) - const token2 = await servers[1].usersCommand.generateUserAndToken('user2') - await servers[1].videosCommand.upload({ token: token2, attributes: { name: 'video5' } }) + const token2 = await servers[1].users.generateUserAndToken('user2') + await servers[1].videos.upload({ token: token2, attributes: { name: 'video5' } }) } { - const attributes = { displayName: 'playlist1', privacy: VideoPlaylistPrivacy.PUBLIC, videoChannelId: servers[1].videoChannel.id } - const created = await servers[1].playlistsCommand.create({ attributes }) + const attributes = { displayName: 'playlist1', privacy: VideoPlaylistPrivacy.PUBLIC, videoChannelId: servers[1].store.channel.id } + const created = await servers[1].playlists.create({ attributes }) playlistUUID1 = created.uuid } { - const attributes = { displayName: 'playlist2', privacy: VideoPlaylistPrivacy.PUBLIC, videoChannelId: servers[1].videoChannel.id } - const created = await servers[1].playlistsCommand.create({ attributes }) + const attributes = { displayName: 'playlist2', privacy: VideoPlaylistPrivacy.PUBLIC, videoChannelId: servers[1].store.channel.id } + const created = await servers[1].playlists.create({ attributes }) playlistUUID2 = created.uuid } @@ -70,15 +70,15 @@ describe('Test AP refresher', function () { await wait(10000) // Change UUID so the remote server returns a 404 - await servers[1].sqlCommand.setVideoField(videoUUID1, 'uuid', '304afe4f-39f9-4d49-8ed7-ac57b86b174f') + await servers[1].sql.setVideoField(videoUUID1, 'uuid', '304afe4f-39f9-4d49-8ed7-ac57b86b174f') - await servers[0].videosCommand.get({ id: videoUUID1 }) - await servers[0].videosCommand.get({ id: videoUUID2 }) + await servers[0].videos.get({ id: videoUUID1 }) + await servers[0].videos.get({ id: videoUUID2 }) await waitJobs(servers) - await servers[0].videosCommand.get({ id: videoUUID1, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) - await servers[0].videosCommand.get({ id: videoUUID2 }) + await servers[0].videos.get({ id: videoUUID1, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) + await servers[0].videos.get({ id: videoUUID2 }) }) it('Should not update a remote video if the remote instance is down', async function () { @@ -86,18 +86,18 @@ describe('Test AP refresher', function () { await killallServers([ servers[1] ]) - await servers[1].sqlCommand.setVideoField(videoUUID3, 'uuid', '304afe4f-39f9-4d49-8ed7-ac57b86b174e') + await servers[1].sql.setVideoField(videoUUID3, 'uuid', '304afe4f-39f9-4d49-8ed7-ac57b86b174e') // Video will need a refresh await wait(10000) - await servers[0].videosCommand.get({ id: videoUUID3 }) + await servers[0].videos.get({ id: videoUUID3 }) // The refresh should fail await waitJobs([ servers[0] ]) await reRunServer(servers[1]) - await servers[0].videosCommand.get({ id: videoUUID3 }) + await servers[0].videos.get({ id: videoUUID3 }) }) }) @@ -106,13 +106,13 @@ describe('Test AP refresher', function () { it('Should remove a deleted actor', async function () { this.timeout(60000) - const command = servers[0].accountsCommand + const command = servers[0].accounts await wait(10000) // Change actor name so the remote server returns a 404 const to = 'http://localhost:' + servers[1].port + '/accounts/user2' - await servers[1].sqlCommand.setActorField(to, 'preferredUsername', 'toto') + await servers[1].sql.setActorField(to, 'preferredUsername', 'toto') await command.get({ accountName: 'user1@localhost:' + servers[1].port }) await command.get({ accountName: 'user2@localhost:' + servers[1].port }) @@ -132,15 +132,15 @@ describe('Test AP refresher', function () { await wait(10000) // Change UUID so the remote server returns a 404 - await servers[1].sqlCommand.setPlaylistField(playlistUUID2, 'uuid', '304afe4f-39f9-4d49-8ed7-ac57b86b178e') + await servers[1].sql.setPlaylistField(playlistUUID2, 'uuid', '304afe4f-39f9-4d49-8ed7-ac57b86b178e') - await servers[0].playlistsCommand.get({ playlistId: playlistUUID1 }) - await servers[0].playlistsCommand.get({ playlistId: playlistUUID2 }) + await servers[0].playlists.get({ playlistId: playlistUUID1 }) + await servers[0].playlists.get({ playlistId: playlistUUID2 }) await waitJobs(servers) - await servers[0].playlistsCommand.get({ playlistId: playlistUUID1, expectedStatus: HttpStatusCode.OK_200 }) - await servers[0].playlistsCommand.get({ playlistId: playlistUUID2, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) + await servers[0].playlists.get({ playlistId: playlistUUID1, expectedStatus: HttpStatusCode.OK_200 }) + await servers[0].playlists.get({ playlistId: playlistUUID2, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) }) diff --git a/server/tests/api/activitypub/security.ts b/server/tests/api/activitypub/security.ts index c32940070..ab0eb256e 100644 --- a/server/tests/api/activitypub/security.ts +++ b/server/tests/api/activitypub/security.ts @@ -24,8 +24,8 @@ function setKeysOfServer (onServer: ServerInfo, ofServer: ServerInfo, publicKey: const url = 'http://localhost:' + ofServer.port + '/accounts/peertube' return Promise.all([ - onServer.sqlCommand.setActorField(url, 'publicKey', publicKey), - onServer.sqlCommand.setActorField(url, 'privateKey', privateKey) + onServer.sql.setActorField(url, 'publicKey', publicKey), + onServer.sql.setActorField(url, 'privateKey', privateKey) ]) } @@ -33,8 +33,8 @@ function setUpdatedAtOfServer (onServer: ServerInfo, ofServer: ServerInfo, updat const url = 'http://localhost:' + ofServer.port + '/accounts/peertube' return Promise.all([ - onServer.sqlCommand.setActorField(url, 'createdAt', updatedAt), - onServer.sqlCommand.setActorField(url, 'updatedAt', updatedAt) + onServer.sql.setActorField(url, 'createdAt', updatedAt), + onServer.sql.setActorField(url, 'updatedAt', updatedAt) ]) } diff --git a/server/tests/api/check-params/abuses.ts b/server/tests/api/check-params/abuses.ts index 199cc5599..7a6790ba8 100644 --- a/server/tests/api/check-params/abuses.ts +++ b/server/tests/api/check-params/abuses.ts @@ -39,12 +39,12 @@ describe('Test abuses API validators', function () { await setAccessTokensToServers([ server ]) - userToken = await server.usersCommand.generateUserAndToken('user_1') - userToken2 = await server.usersCommand.generateUserAndToken('user_2') + userToken = await server.users.generateUserAndToken('user_1') + userToken2 = await server.users.generateUserAndToken('user_2') - server.video = await server.videosCommand.upload() + server.store.video = await server.videos.upload() - command = server.abusesCommand + command = server.abuses }) describe('When listing abuses for admins', function () { @@ -224,25 +224,25 @@ describe('Test abuses API validators', function () { }) it('Should fail with a non authenticated user', async function () { - const fields = { video: { id: server.video.id }, reason: 'my super reason' } + const fields = { video: { id: server.store.video.id }, reason: 'my super reason' } await makePostBodyRequest({ url: server.url, path, token: 'hello', fields, statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should fail with a reason too short', async function () { - const fields = { video: { id: server.video.id }, reason: 'h' } + const fields = { video: { id: server.store.video.id }, reason: 'h' } await makePostBodyRequest({ url: server.url, path, token: userToken, fields }) }) it('Should fail with a too big reason', async function () { - const fields = { video: { id: server.video.id }, reason: 'super'.repeat(605) } + const fields = { video: { id: server.store.video.id }, reason: 'super'.repeat(605) } await makePostBodyRequest({ url: server.url, path, token: userToken, fields }) }) it('Should succeed with the correct parameters (basic)', async function () { - const fields: AbuseCreate = { video: { id: server.video.shortUUID }, reason: 'my super reason' } + const fields: AbuseCreate = { video: { id: server.store.video.shortUUID }, reason: 'my super reason' } const res = await makePostBodyRequest({ url: server.url, @@ -255,19 +255,19 @@ describe('Test abuses API validators', function () { }) it('Should fail with a wrong predefined reason', async function () { - const fields = { video: { id: server.video.id }, reason: 'my super reason', predefinedReasons: [ 'wrongPredefinedReason' ] } + const fields = { video: { id: server.store.video.id }, reason: 'my super reason', predefinedReasons: [ 'wrongPredefinedReason' ] } await makePostBodyRequest({ url: server.url, path, token: userToken, fields }) }) it('Should fail with negative timestamps', async function () { - const fields = { video: { id: server.video.id, startAt: -1 }, reason: 'my super reason' } + const fields = { video: { id: server.store.video.id, startAt: -1 }, reason: 'my super reason' } await makePostBodyRequest({ url: server.url, path, token: userToken, fields }) }) it('Should fail mith misordered startAt/endAt', async function () { - const fields = { video: { id: server.video.id, startAt: 5, endAt: 1 }, reason: 'my super reason' } + const fields = { video: { id: server.store.video.id, startAt: 5, endAt: 1 }, reason: 'my super reason' } await makePostBodyRequest({ url: server.url, path, token: userToken, fields }) }) @@ -275,7 +275,7 @@ describe('Test abuses API validators', function () { it('Should succeed with the corret parameters (advanced)', async function () { const fields: AbuseCreate = { video: { - id: server.video.id, + id: server.store.video.id, startAt: 1, endAt: 5 }, @@ -414,8 +414,8 @@ describe('Test abuses API validators', function () { await doubleFollow(anotherServer, server) - const server2VideoId = await anotherServer.videosCommand.getId({ uuid: server.video.uuid }) - await anotherServer.abusesCommand.report({ reason: 'remote server', videoId: server2VideoId }) + const server2VideoId = await anotherServer.videos.getId({ uuid: server.store.video.uuid }) + await anotherServer.abuses.report({ reason: 'remote server', videoId: server2VideoId }) await waitJobs([ server, anotherServer ]) diff --git a/server/tests/api/check-params/accounts.ts b/server/tests/api/check-params/accounts.ts index 45d440c47..223322626 100644 --- a/server/tests/api/check-params/accounts.ts +++ b/server/tests/api/check-params/accounts.ts @@ -40,7 +40,7 @@ describe('Test accounts API validators', function () { describe('When getting an account', function () { it('Should return 404 with a non existing name', async function () { - await server.accountsCommand.get({ accountName: 'arfaze', expectedStatus: HttpStatusCode.NOT_FOUND_404 }) + await server.accounts.get({ accountName: 'arfaze', expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) }) diff --git a/server/tests/api/check-params/blocklist.ts b/server/tests/api/check-params/blocklist.ts index 18238bb04..14e45e503 100644 --- a/server/tests/api/check-params/blocklist.ts +++ b/server/tests/api/check-params/blocklist.ts @@ -33,9 +33,9 @@ describe('Test blocklist API validators', function () { server = servers[0] const user = { username: 'user1', password: 'password' } - await server.usersCommand.create({ username: user.username, password: user.password }) + await server.users.create({ username: user.username, password: user.password }) - userAccessToken = await server.loginCommand.getAccessToken(user) + userAccessToken = await server.login.getAccessToken(user) await doubleFollow(servers[0], servers[1]) }) diff --git a/server/tests/api/check-params/bulk.ts b/server/tests/api/check-params/bulk.ts index 3f80c79a8..69ff7dd96 100644 --- a/server/tests/api/check-params/bulk.ts +++ b/server/tests/api/check-params/bulk.ts @@ -23,9 +23,9 @@ describe('Test bulk API validators', function () { await setAccessTokensToServers([ server ]) const user = { username: 'user1', password: 'password' } - await server.usersCommand.create({ username: user.username, password: user.password }) + await server.users.create({ username: user.username, password: user.password }) - userAccessToken = await server.loginCommand.getAccessToken(user) + userAccessToken = await server.login.getAccessToken(user) }) describe('When removing comments of', function () { diff --git a/server/tests/api/check-params/config.ts b/server/tests/api/check-params/config.ts index c204d9415..6fd26864e 100644 --- a/server/tests/api/check-params/config.ts +++ b/server/tests/api/check-params/config.ts @@ -205,8 +205,8 @@ describe('Test config API validators', function () { username: 'user1', password: 'password' } - await server.usersCommand.create({ username: user.username, password: user.password }) - userAccessToken = await server.loginCommand.getAccessToken(user) + await server.users.create({ username: user.username, password: user.password }) + userAccessToken = await server.login.getAccessToken(user) }) describe('When getting the configuration', function () { diff --git a/server/tests/api/check-params/contact-form.ts b/server/tests/api/check-params/contact-form.ts index 4eed1661a..d2541777f 100644 --- a/server/tests/api/check-params/contact-form.ts +++ b/server/tests/api/check-params/contact-form.ts @@ -26,7 +26,7 @@ describe('Test contact form API validators', function () { // Email is disabled server = await flushAndRunServer(1) - command = server.contactFormCommand + command = server.contactForm }) it('Should not accept a contact form if emails are disabled', async function () { diff --git a/server/tests/api/check-params/custom-pages.ts b/server/tests/api/check-params/custom-pages.ts index 58b0b8600..3d84fb3e6 100644 --- a/server/tests/api/check-params/custom-pages.ts +++ b/server/tests/api/check-params/custom-pages.ts @@ -25,9 +25,9 @@ describe('Test custom pages validators', function () { await setAccessTokensToServers([ server ]) const user = { username: 'user1', password: 'password' } - await server.usersCommand.create({ username: user.username, password: user.password }) + await server.users.create({ username: user.username, password: user.password }) - userAccessToken = await server.loginCommand.getAccessToken(user) + userAccessToken = await server.login.getAccessToken(user) }) describe('When updating instance homepage', function () { diff --git a/server/tests/api/check-params/debug.ts b/server/tests/api/check-params/debug.ts index 2a7485cf3..609f9566e 100644 --- a/server/tests/api/check-params/debug.ts +++ b/server/tests/api/check-params/debug.ts @@ -29,8 +29,8 @@ describe('Test debug API validators', function () { username: 'user1', password: 'my super password' } - await server.usersCommand.create({ username: user.username, password: user.password }) - userAccessToken = await server.loginCommand.getAccessToken(user) + await server.users.create({ username: user.username, password: user.password }) + userAccessToken = await server.login.getAccessToken(user) }) describe('When getting debug endpoint', function () { diff --git a/server/tests/api/check-params/follows.ts b/server/tests/api/check-params/follows.ts index 24e483448..fae3712ce 100644 --- a/server/tests/api/check-params/follows.ts +++ b/server/tests/api/check-params/follows.ts @@ -39,8 +39,8 @@ describe('Test server follows API validators', function () { password: 'password' } - await server.usersCommand.create({ username: user.username, password: user.password }) - userAccessToken = await server.loginCommand.getAccessToken(user) + await server.users.create({ username: user.username, password: user.password }) + userAccessToken = await server.login.getAccessToken(user) }) describe('When adding follows', function () { diff --git a/server/tests/api/check-params/jobs.ts b/server/tests/api/check-params/jobs.ts index 29439bebf..3786e8612 100644 --- a/server/tests/api/check-params/jobs.ts +++ b/server/tests/api/check-params/jobs.ts @@ -34,8 +34,8 @@ describe('Test jobs API validators', function () { username: 'user1', password: 'my super password' } - await server.usersCommand.create({ username: user.username, password: user.password }) - userAccessToken = await server.loginCommand.getAccessToken(user) + await server.users.create({ username: user.username, password: user.password }) + userAccessToken = await server.login.getAccessToken(user) }) describe('When listing jobs', function () { diff --git a/server/tests/api/check-params/live.ts b/server/tests/api/check-params/live.ts index 4b54fc31c..20f27dd1d 100644 --- a/server/tests/api/check-params/live.ts +++ b/server/tests/api/check-params/live.ts @@ -35,7 +35,7 @@ describe('Test video lives API validator', function () { await setAccessTokensToServers([ server ]) - await server.configCommand.updateCustomSubConfig({ + await server.config.updateCustomSubConfig({ newConfig: { live: { enabled: true, @@ -48,19 +48,19 @@ describe('Test video lives API validator', function () { const username = 'user1' const password = 'my super password' - await server.usersCommand.create({ username: username, password: password }) - userAccessToken = await server.loginCommand.getAccessToken({ username, password }) + await server.users.create({ username: username, password: password }) + userAccessToken = await server.login.getAccessToken({ username, password }) { - const { videoChannels } = await server.usersCommand.getMyInfo() + const { videoChannels } = await server.users.getMyInfo() channelId = videoChannels[0].id } { - videoIdNotLive = (await server.videosCommand.quickUpload({ name: 'not live' })).id + videoIdNotLive = (await server.videos.quickUpload({ name: 'not live' })).id } - command = server.liveCommand + command = server.live }) describe('When creating a live', function () { @@ -144,10 +144,10 @@ describe('Test video lives API validator', function () { username: 'fake', password: 'fake_password' } - await server.usersCommand.create({ username: user.username, password: user.password }) + await server.users.create({ username: user.username, password: user.password }) - const accessTokenUser = await server.loginCommand.getAccessToken(user) - const { videoChannels } = await server.usersCommand.getMyInfo({ token: accessTokenUser }) + const accessTokenUser = await server.login.getAccessToken(user) + const { videoChannels } = await server.users.getMyInfo({ token: accessTokenUser }) const customChannelId = videoChannels[0].id const fields = { ...baseCorrectParams, channelId: customChannelId } @@ -230,7 +230,7 @@ describe('Test video lives API validator', function () { }) it('Should forbid if live is disabled', async function () { - await server.configCommand.updateCustomSubConfig({ + await server.config.updateCustomSubConfig({ newConfig: { live: { enabled: false @@ -250,7 +250,7 @@ describe('Test video lives API validator', function () { it('Should forbid to save replay if not enabled by the admin', async function () { const fields = { ...baseCorrectParams, saveReplay: true } - await server.configCommand.updateCustomSubConfig({ + await server.config.updateCustomSubConfig({ newConfig: { live: { enabled: true, @@ -271,7 +271,7 @@ describe('Test video lives API validator', function () { it('Should allow to save replay if enabled by the admin', async function () { const fields = { ...baseCorrectParams, saveReplay: true } - await server.configCommand.updateCustomSubConfig({ + await server.config.updateCustomSubConfig({ newConfig: { live: { enabled: true, @@ -290,7 +290,7 @@ describe('Test video lives API validator', function () { }) it('Should not allow live if max instance lives is reached', async function () { - await server.configCommand.updateCustomSubConfig({ + await server.config.updateCustomSubConfig({ newConfig: { live: { enabled: true, @@ -309,7 +309,7 @@ describe('Test video lives API validator', function () { }) it('Should not allow live if max user lives is reached', async function () { - await server.configCommand.updateCustomSubConfig({ + await server.config.updateCustomSubConfig({ newConfig: { live: { enabled: true, @@ -401,7 +401,7 @@ describe('Test video lives API validator', function () { }) it('Should fail to update replay status if replay is not allowed on the instance', async function () { - await server.configCommand.updateCustomSubConfig({ + await server.config.updateCustomSubConfig({ newConfig: { live: { enabled: true, diff --git a/server/tests/api/check-params/logs.ts b/server/tests/api/check-params/logs.ts index 69eaad69f..cf8f77959 100644 --- a/server/tests/api/check-params/logs.ts +++ b/server/tests/api/check-params/logs.ts @@ -29,8 +29,8 @@ describe('Test logs API validators', function () { username: 'user1', password: 'my super password' } - await server.usersCommand.create({ username: user.username, password: user.password }) - userAccessToken = await server.loginCommand.getAccessToken(user) + await server.users.create({ username: user.username, password: user.password }) + userAccessToken = await server.login.getAccessToken(user) }) describe('When getting logs', function () { diff --git a/server/tests/api/check-params/plugins.ts b/server/tests/api/check-params/plugins.ts index 08fb2397f..d4b72c0f4 100644 --- a/server/tests/api/check-params/plugins.ts +++ b/server/tests/api/check-params/plugins.ts @@ -42,17 +42,17 @@ describe('Test server plugins API validators', function () { password: 'password' } - await server.usersCommand.create({ username: user.username, password: user.password }) - userAccessToken = await server.loginCommand.getAccessToken(user) + await server.users.create({ username: user.username, password: user.password }) + userAccessToken = await server.login.getAccessToken(user) { - const res = await server.pluginsCommand.install({ npmName: npmPlugin }) + const res = await server.plugins.install({ npmName: npmPlugin }) const plugin = res.body as PeerTubePlugin npmVersion = plugin.version } { - const res = await server.pluginsCommand.install({ npmName: themePlugin }) + const res = await server.plugins.install({ npmName: themePlugin }) const plugin = res.body as PeerTubePlugin themeVersion = plugin.version } diff --git a/server/tests/api/check-params/redundancy.ts b/server/tests/api/check-params/redundancy.ts index b1692b986..fca92fde4 100644 --- a/server/tests/api/check-params/redundancy.ts +++ b/server/tests/api/check-params/redundancy.ts @@ -40,16 +40,16 @@ describe('Test server redundancy API validators', function () { password: 'password' } - await servers[0].usersCommand.create({ username: user.username, password: user.password }) - userAccessToken = await servers[0].loginCommand.getAccessToken(user) + await servers[0].users.create({ username: user.username, password: user.password }) + userAccessToken = await servers[0].login.getAccessToken(user) - videoIdLocal = (await servers[0].videosCommand.quickUpload({ name: 'video' })).id + videoIdLocal = (await servers[0].videos.quickUpload({ name: 'video' })).id - const remoteUUID = (await servers[1].videosCommand.quickUpload({ name: 'video' })).uuid + const remoteUUID = (await servers[1].videos.quickUpload({ name: 'video' })).uuid await waitJobs(servers) - videoRemote = await servers[0].videosCommand.get({ id: remoteUUID }) + videoRemote = await servers[0].videos.get({ id: remoteUUID }) }) describe('When listing redundancies', function () { diff --git a/server/tests/api/check-params/search.ts b/server/tests/api/check-params/search.ts index 7973c112f..1acfa0922 100644 --- a/server/tests/api/check-params/search.ts +++ b/server/tests/api/check-params/search.ts @@ -14,7 +14,7 @@ import { } from '@shared/extra-utils' function updateSearchIndex (server: ServerInfo, enabled: boolean, disableLocalSearch = false) { - return server.configCommand.updateCustomSubConfig({ + return server.config.updateCustomSubConfig({ newConfig: { search: { searchIndex: { diff --git a/server/tests/api/check-params/services.ts b/server/tests/api/check-params/services.ts index f86712b4e..83435c24a 100644 --- a/server/tests/api/check-params/services.ts +++ b/server/tests/api/check-params/services.ts @@ -25,14 +25,14 @@ describe('Test services API validators', function () { await setAccessTokensToServers([ server ]) await setDefaultVideoChannel([ server ]) - server.video = await server.videosCommand.upload({ attributes: { name: 'my super name' } }) + server.store.video = await server.videos.upload({ attributes: { name: 'my super name' } }) { - const created = await server.playlistsCommand.create({ + const created = await server.playlists.create({ attributes: { displayName: 'super playlist', privacy: VideoPlaylistPrivacy.PUBLIC, - videoChannelId: server.videoChannel.id + videoChannelId: server.store.channel.id } }) @@ -48,7 +48,7 @@ describe('Test services API validators', function () { }) it('Should fail with an invalid host', async function () { - const embedUrl = 'http://hello.com/videos/watch/' + server.video.uuid + const embedUrl = 'http://hello.com/videos/watch/' + server.store.video.uuid await checkParamEmbed(server, embedUrl) }) @@ -63,37 +63,37 @@ describe('Test services API validators', function () { }) it('Should fail with an invalid path', async function () { - const embedUrl = `http://localhost:${server.port}/videos/watchs/${server.video.uuid}` + const embedUrl = `http://localhost:${server.port}/videos/watchs/${server.store.video.uuid}` await checkParamEmbed(server, embedUrl) }) it('Should fail with an invalid max height', async function () { - const embedUrl = `http://localhost:${server.port}/videos/watch/${server.video.uuid}` + const embedUrl = `http://localhost:${server.port}/videos/watch/${server.store.video.uuid}` await checkParamEmbed(server, embedUrl, HttpStatusCode.BAD_REQUEST_400, { maxheight: 'hello' }) }) it('Should fail with an invalid max width', async function () { - const embedUrl = `http://localhost:${server.port}/videos/watch/${server.video.uuid}` + const embedUrl = `http://localhost:${server.port}/videos/watch/${server.store.video.uuid}` await checkParamEmbed(server, embedUrl, HttpStatusCode.BAD_REQUEST_400, { maxwidth: 'hello' }) }) it('Should fail with an invalid format', async function () { - const embedUrl = `http://localhost:${server.port}/videos/watch/${server.video.uuid}` + const embedUrl = `http://localhost:${server.port}/videos/watch/${server.store.video.uuid}` await checkParamEmbed(server, embedUrl, HttpStatusCode.BAD_REQUEST_400, { format: 'blabla' }) }) it('Should fail with a non supported format', async function () { - const embedUrl = `http://localhost:${server.port}/videos/watch/${server.video.uuid}` + const embedUrl = `http://localhost:${server.port}/videos/watch/${server.store.video.uuid}` await checkParamEmbed(server, embedUrl, HttpStatusCode.NOT_IMPLEMENTED_501, { format: 'xml' }) }) it('Should succeed with the correct params with a video', async function () { - const embedUrl = `http://localhost:${server.port}/videos/watch/${server.video.uuid}` + const embedUrl = `http://localhost:${server.port}/videos/watch/${server.store.video.uuid}` const query = { format: 'json', maxheight: 400, diff --git a/server/tests/api/check-params/upload-quota.ts b/server/tests/api/check-params/upload-quota.ts index 164c581e3..4ca544790 100644 --- a/server/tests/api/check-params/upload-quota.ts +++ b/server/tests/api/check-params/upload-quota.ts @@ -29,12 +29,12 @@ describe('Test upload quota', function () { await setAccessTokensToServers([ server ]) await setDefaultVideoChannel([ server ]) - const user = await server.usersCommand.getMyInfo() + const user = await server.users.getMyInfo() rootId = user.id - await server.usersCommand.update({ userId: rootId, videoQuota: 42 }) + await server.users.update({ userId: rootId, videoQuota: 42 }) - command = server.videosCommand + command = server.videos }) describe('When having a video quota', function () { @@ -43,8 +43,8 @@ describe('Test upload quota', function () { this.timeout(30000) const user = { username: 'registered' + randomInt(1, 1500), password: 'password' } - await server.usersCommand.register(user) - const userToken = await server.loginCommand.getAccessToken(user) + await server.users.register(user) + const userToken = await server.login.getAccessToken(user) const attributes = { fixture: 'video_short2.webm' } for (let i = 0; i < 5; i++) { @@ -58,8 +58,8 @@ describe('Test upload quota', function () { this.timeout(30000) const user = { username: 'registered' + randomInt(1, 1500), password: 'password' } - await server.usersCommand.register(user) - const userToken = await server.loginCommand.getAccessToken(user) + await server.users.register(user) + const userToken = await server.login.getAccessToken(user) const attributes = { fixture: 'video_short2.webm' } for (let i = 0; i < 5; i++) { @@ -73,16 +73,16 @@ describe('Test upload quota', function () { this.timeout(120000) const baseAttributes = { - channelId: server.videoChannel.id, + channelId: server.store.channel.id, privacy: VideoPrivacy.PUBLIC } - await server.importsCommand.importVideo({ attributes: { ...baseAttributes, targetUrl: ImportsCommand.getGoodVideoUrl() } }) - await server.importsCommand.importVideo({ attributes: { ...baseAttributes, magnetUri: ImportsCommand.getMagnetURI() } }) - await server.importsCommand.importVideo({ attributes: { ...baseAttributes, torrentfile: 'video-720p.torrent' as any } }) + await server.imports.importVideo({ attributes: { ...baseAttributes, targetUrl: ImportsCommand.getGoodVideoUrl() } }) + await server.imports.importVideo({ attributes: { ...baseAttributes, magnetUri: ImportsCommand.getMagnetURI() } }) + await server.imports.importVideo({ attributes: { ...baseAttributes, torrentfile: 'video-720p.torrent' as any } }) await waitJobs([ server ]) - const { total, data: videoImports } = await server.importsCommand.getMyVideoImports() + const { total, data: videoImports } = await server.imports.getMyVideoImports() expect(total).to.equal(3) expect(videoImports).to.have.lengthOf(3) @@ -98,7 +98,7 @@ describe('Test upload quota', function () { describe('When having a daily video quota', function () { it('Should fail with a user having too many videos daily', async function () { - await server.usersCommand.update({ userId: rootId, videoQuotaDaily: 42 }) + 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' }) @@ -107,7 +107,7 @@ describe('Test upload quota', function () { describe('When having an absolute and daily video quota', function () { it('Should fail if exceeding total quota', async function () { - await server.usersCommand.update({ + await server.users.update({ userId: rootId, videoQuota: 42, videoQuotaDaily: 1024 * 1024 * 1024 @@ -118,7 +118,7 @@ describe('Test upload quota', function () { }) it('Should fail if exceeding daily quota', async function () { - await server.usersCommand.update({ + await server.users.update({ userId: rootId, videoQuota: 1024 * 1024 * 1024, videoQuotaDaily: 42 diff --git a/server/tests/api/check-params/user-subscriptions.ts b/server/tests/api/check-params/user-subscriptions.ts index 8ce201d61..885ad68e4 100644 --- a/server/tests/api/check-params/user-subscriptions.ts +++ b/server/tests/api/check-params/user-subscriptions.ts @@ -38,8 +38,8 @@ describe('Test user subscriptions API validators', function () { username: 'user1', password: 'my super password' } - await server.usersCommand.create({ username: user.username, password: user.password }) - userAccessToken = await server.loginCommand.getAccessToken(user) + await server.users.create({ username: user.username, password: user.password }) + userAccessToken = await server.login.getAccessToken(user) }) describe('When listing my subscriptions', function () { diff --git a/server/tests/api/check-params/users.ts b/server/tests/api/check-params/users.ts index 33c48a009..bce3f0774 100644 --- a/server/tests/api/check-params/users.ts +++ b/server/tests/api/check-params/users.ts @@ -60,27 +60,27 @@ describe('Test users API validators', function () { { const user = { username: 'user1' } - await server.usersCommand.create({ ...user }) - userToken = await server.loginCommand.getAccessToken(user) + await server.users.create({ ...user }) + userToken = await server.login.getAccessToken(user) } { const moderator = { username: 'moderator1' } - await server.usersCommand.create({ ...moderator, role: UserRole.MODERATOR }) - moderatorToken = await server.loginCommand.getAccessToken(moderator) + await server.users.create({ ...moderator, role: UserRole.MODERATOR }) + moderatorToken = await server.login.getAccessToken(moderator) } { const moderator = { username: 'moderator2' } - await server.usersCommand.create({ ...moderator, role: UserRole.MODERATOR }) + await server.users.create({ ...moderator, role: UserRole.MODERATOR }) } { - video = await server.videosCommand.upload() + video = await server.videos.upload() } { - const { data } = await server.usersCommand.list() + const { data } = await server.users.list() userId = data.find(u => u.username === 'user1').id rootId = data.find(u => u.username === 'root').id moderatorId = data.find(u => u.username === 'moderator2').id @@ -341,7 +341,7 @@ describe('Test users API validators', function () { it('Should fail with a non admin user', async function () { const user = { username: 'user1' } - userToken = await server.loginCommand.getAccessToken(user) + userToken = await server.login.getAccessToken(user) const fields = { username: 'user3', @@ -596,28 +596,28 @@ describe('Test users API validators', function () { describe('When managing my scoped tokens', function () { it('Should fail to get my scoped tokens with an non authenticated user', async function () { - await server.usersCommand.getMyScopedTokens({ token: null, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) + await server.users.getMyScopedTokens({ token: null, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should fail to get my scoped tokens with a bad token', async function () { - await server.usersCommand.getMyScopedTokens({ token: 'bad', expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) + await server.users.getMyScopedTokens({ token: 'bad', expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should succeed to get my scoped tokens', async function () { - await server.usersCommand.getMyScopedTokens() + await server.users.getMyScopedTokens() }) it('Should fail to renew my scoped tokens with an non authenticated user', async function () { - await server.usersCommand.renewMyScopedTokens({ token: null, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) + await server.users.renewMyScopedTokens({ token: null, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should fail to renew my scoped tokens with a bad token', async function () { - await server.usersCommand.renewMyScopedTokens({ token: 'bad', expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) + await server.users.renewMyScopedTokens({ token: 'bad', expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should succeed to renew my scoped tokens', async function () { - await server.usersCommand.renewMyScopedTokens() + await server.users.renewMyScopedTokens() }) }) @@ -769,11 +769,11 @@ describe('Test users API validators', function () { describe('When getting my information', function () { it('Should fail with a non authenticated user', async function () { - await server.usersCommand.getMyInfo({ token: 'fake_token', expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) + await server.users.getMyInfo({ token: 'fake_token', expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should success with the correct parameters', async function () { - await server.usersCommand.getMyInfo({ token: userToken }) + await server.users.getMyInfo({ token: userToken }) }) }) @@ -781,7 +781,7 @@ describe('Test users API validators', function () { let command: UsersCommand before(function () { - command = server.usersCommand + command = server.users }) it('Should fail with a non authenticated user', async function () { @@ -846,54 +846,54 @@ describe('Test users API validators', function () { it('Should fail with an incorrect id', async function () { const options = { userId: 'blabla' as any, expectedStatus: HttpStatusCode.BAD_REQUEST_400 } - await server.usersCommand.remove(options) - await server.usersCommand.banUser({ userId: 'blabla' as any, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) - await server.usersCommand.unbanUser({ userId: 'blabla' as any, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) + await server.users.remove(options) + await server.users.banUser({ userId: 'blabla' as any, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) + await server.users.unbanUser({ userId: 'blabla' as any, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) it('Should fail with the root user', async function () { const options = { userId: rootId, expectedStatus: HttpStatusCode.BAD_REQUEST_400 } - await server.usersCommand.remove(options) - await server.usersCommand.banUser(options) - await server.usersCommand.unbanUser(options) + await server.users.remove(options) + await server.users.banUser(options) + await server.users.unbanUser(options) }) it('Should return 404 with a non existing id', async function () { const options = { userId: 4545454, expectedStatus: HttpStatusCode.NOT_FOUND_404 } - await server.usersCommand.remove(options) - await server.usersCommand.banUser(options) - await server.usersCommand.unbanUser(options) + await server.users.remove(options) + await server.users.banUser(options) + await server.users.unbanUser(options) }) it('Should fail with a non admin user', async function () { const options = { userId, token: userToken, expectedStatus: HttpStatusCode.FORBIDDEN_403 } - await server.usersCommand.remove(options) - await server.usersCommand.banUser(options) - await server.usersCommand.unbanUser(options) + await server.users.remove(options) + await server.users.banUser(options) + await server.users.unbanUser(options) }) it('Should fail on a moderator with a moderator', async function () { const options = { userId: moderatorId, token: moderatorToken, expectedStatus: HttpStatusCode.FORBIDDEN_403 } - await server.usersCommand.remove(options) - await server.usersCommand.banUser(options) - await server.usersCommand.unbanUser(options) + await server.users.remove(options) + await server.users.banUser(options) + await server.users.unbanUser(options) }) it('Should succeed on a user with a moderator', async function () { const options = { userId, token: moderatorToken } - await server.usersCommand.banUser(options) - await server.usersCommand.unbanUser(options) + await server.users.banUser(options) + await server.users.unbanUser(options) }) }) describe('When deleting our account', function () { it('Should fail with with the root account', async function () { - await server.usersCommand.deleteMe({ expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) + await server.users.deleteMe({ expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) }) @@ -1011,7 +1011,7 @@ describe('Test users API validators', function () { it('Should fail with an existing channel', async function () { const attributes = { name: 'existing_channel', displayName: 'hello', description: 'super description' } - await server.channelsCommand.create({ attributes }) + await server.channels.create({ attributes }) const fields = { ...baseCorrectParams, channel: { name: 'existing_channel', displayName: 'toto' } } @@ -1055,7 +1055,7 @@ describe('Test users API validators', function () { describe('When registering multiple users on a server with users limit', function () { it('Should fail when after 3 registrations', async function () { - await server.usersCommand.register({ username: 'user42', expectedStatus: HttpStatusCode.FORBIDDEN_403 }) + await server.users.register({ username: 'user42', expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) }) diff --git a/server/tests/api/check-params/video-blacklist.ts b/server/tests/api/check-params/video-blacklist.ts index 0fda31b29..51609b982 100644 --- a/server/tests/api/check-params/video-blacklist.ts +++ b/server/tests/api/check-params/video-blacklist.ts @@ -40,41 +40,41 @@ describe('Test video blacklist API validators', function () { { const username = 'user1' const password = 'my super password' - await servers[0].usersCommand.create({ username: username, password: password }) - userAccessToken1 = await servers[0].loginCommand.getAccessToken({ username, password }) + await servers[0].users.create({ username: username, password: password }) + userAccessToken1 = await servers[0].login.getAccessToken({ username, password }) } { const username = 'user2' const password = 'my super password' - await servers[0].usersCommand.create({ username: username, password: password }) - userAccessToken2 = await servers[0].loginCommand.getAccessToken({ username, password }) + await servers[0].users.create({ username: username, password: password }) + userAccessToken2 = await servers[0].login.getAccessToken({ username, password }) } { - servers[0].video = await servers[0].videosCommand.upload({ token: userAccessToken1 }) + servers[0].store.video = await servers[0].videos.upload({ token: userAccessToken1 }) } { - const { uuid } = await servers[0].videosCommand.upload() + const { uuid } = await servers[0].videos.upload() notBlacklistedVideoId = uuid } { - const { uuid } = await servers[1].videosCommand.upload() + const { uuid } = await servers[1].videos.upload() remoteVideoUUID = uuid } await waitJobs(servers) - command = servers[0].blacklistCommand + command = servers[0].blacklist }) describe('When adding a video in blacklist', function () { const basePath = '/api/v1/videos/' it('Should fail with nothing', async function () { - const path = basePath + servers[0].video + '/blacklist' + const path = basePath + servers[0].store.video + '/blacklist' const fields = {} await makePostBodyRequest({ url: servers[0].url, path, token: servers[0].accessToken, fields }) }) @@ -86,13 +86,13 @@ describe('Test video blacklist API validators', function () { }) it('Should fail with a non authenticated user', async function () { - const path = basePath + servers[0].video + '/blacklist' + const path = basePath + servers[0].store.video + '/blacklist' const fields = {} await makePostBodyRequest({ url: servers[0].url, path, token: 'hello', fields, statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should fail with a non admin user', async function () { - const path = basePath + servers[0].video + '/blacklist' + const path = basePath + servers[0].store.video + '/blacklist' const fields = {} await makePostBodyRequest({ url: servers[0].url, @@ -104,7 +104,7 @@ describe('Test video blacklist API validators', function () { }) it('Should fail with an invalid reason', async function () { - const path = basePath + servers[0].video.uuid + '/blacklist' + const path = basePath + servers[0].store.video.uuid + '/blacklist' const fields = { reason: 'a'.repeat(305) } await makePostBodyRequest({ url: servers[0].url, path, token: servers[0].accessToken, fields }) @@ -124,7 +124,7 @@ describe('Test video blacklist API validators', function () { }) it('Should succeed with the correct params', async function () { - const path = basePath + servers[0].video.uuid + '/blacklist' + const path = basePath + servers[0].store.video.uuid + '/blacklist' const fields = {} await makePostBodyRequest({ @@ -159,13 +159,13 @@ describe('Test video blacklist API validators', function () { }) it('Should fail with a non authenticated user', async function () { - const path = basePath + servers[0].video + '/blacklist' + const path = basePath + servers[0].store.video + '/blacklist' const fields = {} await makePutBodyRequest({ url: servers[0].url, path, token: 'hello', fields, statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should fail with a non admin user', async function () { - const path = basePath + servers[0].video + '/blacklist' + const path = basePath + servers[0].store.video + '/blacklist' const fields = {} await makePutBodyRequest({ url: servers[0].url, @@ -177,14 +177,14 @@ describe('Test video blacklist API validators', function () { }) it('Should fail with an invalid reason', async function () { - const path = basePath + servers[0].video.uuid + '/blacklist' + const path = basePath + servers[0].store.video.uuid + '/blacklist' const fields = { reason: 'a'.repeat(305) } await makePutBodyRequest({ url: servers[0].url, path, token: servers[0].accessToken, fields }) }) it('Should succeed with the correct params', async function () { - const path = basePath + servers[0].video.shortUUID + '/blacklist' + const path = basePath + servers[0].store.video.shortUUID + '/blacklist' const fields = { reason: 'hello' } await makePutBodyRequest({ @@ -200,27 +200,27 @@ describe('Test video blacklist API validators', function () { describe('When getting blacklisted video', function () { it('Should fail with a non authenticated user', async function () { - await servers[0].videosCommand.get({ id: servers[0].video.uuid, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) + await servers[0].videos.get({ id: servers[0].store.video.uuid, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should fail with another user', async function () { - await servers[0].videosCommand.getWithToken({ + await servers[0].videos.getWithToken({ token: userAccessToken2, - id: servers[0].video.uuid, + id: servers[0].store.video.uuid, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) it('Should succeed with the owner authenticated user', async function () { - const video = await servers[0].videosCommand.getWithToken({ token: userAccessToken1, id: servers[0].video.uuid }) + const video = await servers[0].videos.getWithToken({ token: userAccessToken1, id: servers[0].store.video.uuid }) expect(video.blacklisted).to.be.true }) it('Should succeed with an admin', async function () { - const video = servers[0].video + const video = servers[0].store.video for (const id of [ video.id, video.uuid, video.shortUUID ]) { - const video = await servers[0].videosCommand.getWithToken({ id, expectedStatus: HttpStatusCode.OK_200 }) + const video = await servers[0].videos.getWithToken({ id, expectedStatus: HttpStatusCode.OK_200 }) expect(video.blacklisted).to.be.true } }) @@ -229,11 +229,11 @@ describe('Test video blacklist API validators', function () { describe('When removing a video in blacklist', function () { it('Should fail with a non authenticated user', async function () { - await command.remove({ token: 'fake token', videoId: servers[0].video.uuid, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) + await command.remove({ token: 'fake token', videoId: servers[0].store.video.uuid, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should fail with a non admin user', async function () { - await command.remove({ token: userAccessToken2, videoId: servers[0].video.uuid, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) + await command.remove({ token: userAccessToken2, videoId: servers[0].store.video.uuid, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) it('Should fail with an incorrect id', async function () { @@ -246,7 +246,7 @@ describe('Test video blacklist API validators', function () { }) it('Should succeed with the correct params', async function () { - await command.remove({ videoId: servers[0].video.uuid, expectedStatus: HttpStatusCode.NO_CONTENT_204 }) + await command.remove({ videoId: servers[0].store.video.uuid, expectedStatus: HttpStatusCode.NO_CONTENT_204 }) }) }) @@ -254,11 +254,11 @@ describe('Test video blacklist API validators', function () { const basePath = '/api/v1/videos/blacklist/' it('Should fail with a non authenticated user', async function () { - await servers[0].blacklistCommand.list({ token: 'fake token', expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) + await servers[0].blacklist.list({ token: 'fake token', expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should fail with a non admin user', async function () { - await servers[0].blacklistCommand.list({ token: userAccessToken2, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) + await servers[0].blacklist.list({ token: userAccessToken2, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) it('Should fail with a bad start pagination', async function () { @@ -274,11 +274,11 @@ describe('Test video blacklist API validators', function () { }) it('Should fail with an invalid type', async function () { - await servers[0].blacklistCommand.list({ type: 0, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) + await servers[0].blacklist.list({ type: 0, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) it('Should succeed with the correct parameters', async function () { - await servers[0].blacklistCommand.list({ type: VideoBlacklistType.MANUAL }) + await servers[0].blacklist.list({ type: VideoBlacklistType.MANUAL }) }) }) diff --git a/server/tests/api/check-params/video-captions.ts b/server/tests/api/check-params/video-captions.ts index f3941b3fa..913f894b9 100644 --- a/server/tests/api/check-params/video-captions.ts +++ b/server/tests/api/check-params/video-captions.ts @@ -30,15 +30,15 @@ describe('Test video captions API validator', function () { await setAccessTokensToServers([ server ]) - video = await server.videosCommand.upload() + video = await server.videos.upload() { const user = { username: 'user1', password: 'my super password' } - await server.usersCommand.create({ username: user.username, password: user.password }) - userAccessToken = await server.loginCommand.getAccessToken(user) + await server.users.create({ username: user.username, password: user.password }) + userAccessToken = await server.login.getAccessToken(user) } }) @@ -152,7 +152,7 @@ describe('Test video captions API validator', function () { // }) it('Should succeed with a valid captionfile extension and octet-stream mime type', async function () { - await server.captionsCommand.createVideoCaption({ + await server.captions.createVideoCaption({ language: 'zh', videoId: video.uuid, fixture: 'subtitle-good.srt', diff --git a/server/tests/api/check-params/video-channels.ts b/server/tests/api/check-params/video-channels.ts index 2b4c17ea1..8e6e32f20 100644 --- a/server/tests/api/check-params/video-channels.ts +++ b/server/tests/api/check-params/video-channels.ts @@ -44,11 +44,11 @@ describe('Test video channels API validator', function () { } { - await server.usersCommand.create({ username: user.username, password: user.password }) - accessTokenUser = await server.loginCommand.getAccessToken(user) + await server.users.create({ username: user.username, password: user.password }) + accessTokenUser = await server.login.getAccessToken(user) } - command = server.channelsCommand + command = server.channels }) describe('When listing a video channels', function () { @@ -81,7 +81,7 @@ describe('Test video channels API validator', function () { }) it('Should fail with a unknown account', async function () { - await server.channelsCommand.listByAccount({ accountName: 'unknown', expectedStatus: HttpStatusCode.NOT_FOUND_404 }) + await server.channels.listByAccount({ accountName: 'unknown', expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) it('Should succeed with the correct parameters', async function () { diff --git a/server/tests/api/check-params/video-comments.ts b/server/tests/api/check-params/video-comments.ts index bdf7f91ee..44af9d7e3 100644 --- a/server/tests/api/check-params/video-comments.ts +++ b/server/tests/api/check-params/video-comments.ts @@ -38,26 +38,26 @@ describe('Test video comments API validator', function () { await setAccessTokensToServers([ server ]) { - const video = await server.videosCommand.upload({ attributes: {} }) + const video = await server.videos.upload({ attributes: {} }) pathThread = '/api/v1/videos/' + video.uuid + '/comment-threads' } { - const created = await server.commentsCommand.createThread({ videoId: video.uuid, text: 'coucou' }) + const created = await server.comments.createThread({ videoId: video.uuid, text: 'coucou' }) commentId = created.id pathComment = '/api/v1/videos/' + video.uuid + '/comments/' + commentId } { const user = { username: 'user1', password: 'my super password' } - await server.usersCommand.create({ username: user.username, password: user.password }) - userAccessToken = await server.loginCommand.getAccessToken(user) + await server.users.create({ username: user.username, password: user.password }) + userAccessToken = await server.login.getAccessToken(user) } { const user = { username: 'user2', password: 'my super password' } - await server.usersCommand.create({ username: user.username, password: user.password }) - userAccessToken2 = await server.loginCommand.getAccessToken(user) + await server.users.create({ username: user.username, password: user.password }) + userAccessToken2 = await server.login.getAccessToken(user) } }) @@ -274,7 +274,7 @@ describe('Test video comments API validator', function () { let commentToDelete: number { - const created = await server.commentsCommand.createThread({ videoId: video.uuid, token: userAccessToken, text: 'hello' }) + const created = await server.comments.createThread({ videoId: video.uuid, token: userAccessToken, text: 'hello' }) commentToDelete = created.id } @@ -289,12 +289,12 @@ describe('Test video comments API validator', function () { let anotherVideoUUID: string { - const { uuid } = await server.videosCommand.upload({ token: userAccessToken, attributes: { name: 'video' } }) + const { uuid } = await server.videos.upload({ token: userAccessToken, attributes: { name: 'video' } }) anotherVideoUUID = uuid } { - const created = await server.commentsCommand.createThread({ videoId: anotherVideoUUID, text: 'hello' }) + const created = await server.comments.createThread({ videoId: anotherVideoUUID, text: 'hello' }) commentToDelete = created.id } @@ -316,7 +316,7 @@ describe('Test video comments API validator', function () { describe('When a video has comments disabled', function () { before(async function () { - video = await server.videosCommand.upload({ attributes: { commentsEnabled: false } }) + video = await server.videos.upload({ attributes: { commentsEnabled: false } }) pathThread = '/api/v1/videos/' + video.uuid + '/comment-threads' }) diff --git a/server/tests/api/check-params/video-imports.ts b/server/tests/api/check-params/video-imports.ts index d09e473de..1a6b6075f 100644 --- a/server/tests/api/check-params/video-imports.ts +++ b/server/tests/api/check-params/video-imports.ts @@ -36,11 +36,11 @@ describe('Test video imports API validator', function () { const username = 'user1' const password = 'my super password' - await server.usersCommand.create({ username: username, password: password }) - userAccessToken = await server.loginCommand.getAccessToken({ username, password }) + await server.users.create({ username: username, password: password }) + userAccessToken = await server.login.getAccessToken({ username, password }) { - const { videoChannels } = await server.usersCommand.getMyInfo() + const { videoChannels } = await server.users.getMyInfo() channelId = videoChannels[0].id } }) @@ -162,10 +162,10 @@ describe('Test video imports API validator', function () { username: 'fake', password: 'fake_password' } - await server.usersCommand.create({ username: user.username, password: user.password }) + await server.users.create({ username: user.username, password: user.password }) - const accessTokenUser = await server.loginCommand.getAccessToken(user) - const { videoChannels } = await server.usersCommand.getMyInfo({ token: accessTokenUser }) + const accessTokenUser = await server.login.getAccessToken(user) + const { videoChannels } = await server.users.getMyInfo({ token: accessTokenUser }) const customChannelId = videoChannels[0].id const fields = { ...baseCorrectParams, channelId: customChannelId } @@ -256,7 +256,7 @@ describe('Test video imports API validator', function () { }) it('Should forbid to import http videos', async function () { - await server.configCommand.updateCustomSubConfig({ + await server.config.updateCustomSubConfig({ newConfig: { import: { videos: { @@ -281,7 +281,7 @@ describe('Test video imports API validator', function () { }) it('Should forbid to import torrent videos', async function () { - await server.configCommand.updateCustomSubConfig({ + await server.config.updateCustomSubConfig({ newConfig: { import: { videos: { diff --git a/server/tests/api/check-params/video-playlists.ts b/server/tests/api/check-params/video-playlists.ts index ebd7e2413..e0e42ebb0 100644 --- a/server/tests/api/check-params/video-playlists.ts +++ b/server/tests/api/check-params/video-playlists.ts @@ -47,10 +47,10 @@ describe('Test video playlists API validator', function () { await setAccessTokensToServers([ server ]) await setDefaultVideoChannel([ server ]) - userAccessToken = await server.usersCommand.generateUserAndToken('user1') - videoId = (await server.videosCommand.quickUpload({ name: 'video 1' })).id + userAccessToken = await server.users.generateUserAndToken('user1') + videoId = (await server.videos.quickUpload({ name: 'video 1' })).id - command = server.playlistsCommand + command = server.playlists { const { data } = await command.listByAccount({ @@ -68,7 +68,7 @@ describe('Test video playlists API validator', function () { attributes: { displayName: 'super playlist', privacy: VideoPlaylistPrivacy.PUBLIC, - videoChannelId: server.videoChannel.id + videoChannelId: server.store.channel.id } }) } @@ -176,7 +176,7 @@ describe('Test video playlists API validator', function () { const playlist = await command.create({ attributes: { displayName: 'super playlist', - videoChannelId: server.videoChannel.id, + videoChannelId: server.store.channel.id, privacy: VideoPlaylistPrivacy.UNLISTED } }) @@ -200,7 +200,7 @@ describe('Test video playlists API validator', function () { displayName: 'display name', privacy: VideoPlaylistPrivacy.UNLISTED, thumbnailfile: 'thumbnail.jpg', - videoChannelId: server.videoChannel.id, + videoChannelId: server.store.channel.id, ...attributes }, @@ -485,8 +485,8 @@ describe('Test video playlists API validator', function () { } before(async function () { - videoId3 = (await server.videosCommand.quickUpload({ name: 'video 3' })).id - videoId4 = (await server.videosCommand.quickUpload({ name: 'video 4' })).id + videoId3 = (await server.videos.quickUpload({ name: 'video 3' })).id + videoId4 = (await server.videos.quickUpload({ name: 'video 4' })).id for (const id of [ videoId3, videoId4 ]) { await command.addElement({ playlistId: playlist.shortUUID, attributes: { videoId: id } }) diff --git a/server/tests/api/check-params/videos-filter.ts b/server/tests/api/check-params/videos-filter.ts index d7bf081d4..cbfdef1db 100644 --- a/server/tests/api/check-params/videos-filter.ts +++ b/server/tests/api/check-params/videos-filter.ts @@ -49,13 +49,13 @@ describe('Test video filters validators', function () { await setDefaultVideoChannel([ server ]) const user = { username: 'user1', password: 'my super password' } - await server.usersCommand.create({ username: user.username, password: user.password }) - userAccessToken = await server.loginCommand.getAccessToken(user) + await server.users.create({ username: user.username, password: user.password }) + userAccessToken = await server.login.getAccessToken(user) const moderator = { username: 'moderator', password: 'my super password' } - await server.usersCommand.create({ username: moderator.username, password: moderator.password, role: UserRole.MODERATOR }) + await server.users.create({ username: moderator.username, password: moderator.password, role: UserRole.MODERATOR }) - moderatorAccessToken = await server.loginCommand.getAccessToken(moderator) + moderatorAccessToken = await server.login.getAccessToken(moderator) }) describe('When setting a video filter', function () { diff --git a/server/tests/api/check-params/videos-history.ts b/server/tests/api/check-params/videos-history.ts index 1da922a17..549c9fa1f 100644 --- a/server/tests/api/check-params/videos-history.ts +++ b/server/tests/api/check-params/videos-history.ts @@ -29,7 +29,7 @@ describe('Test videos history API validator', function () { await setAccessTokensToServers([ server ]) - const { uuid } = await server.videosCommand.upload() + const { uuid } = await server.videos.upload() watchingPath = '/api/v1/videos/' + uuid + '/watching' }) diff --git a/server/tests/api/check-params/videos-overviews.ts b/server/tests/api/check-params/videos-overviews.ts index 44a936c9f..3597c81d3 100644 --- a/server/tests/api/check-params/videos-overviews.ts +++ b/server/tests/api/check-params/videos-overviews.ts @@ -17,12 +17,12 @@ describe('Test videos overview', function () { describe('When getting videos overview', function () { it('Should fail with a bad pagination', async function () { - await server.overviewsCommand.getVideos({ page: 0, expectedStatus: 400 }) - await server.overviewsCommand.getVideos({ page: 100, expectedStatus: 400 }) + await server.overviews.getVideos({ page: 0, expectedStatus: 400 }) + await server.overviews.getVideos({ page: 100, expectedStatus: 400 }) }) it('Should succeed with a good pagination', async function () { - await server.overviewsCommand.getVideos({ page: 1 }) + await server.overviews.getVideos({ page: 1 }) }) }) diff --git a/server/tests/api/check-params/videos.ts b/server/tests/api/check-params/videos.ts index 8f9f33b8c..69bdae7cf 100644 --- a/server/tests/api/check-params/videos.ts +++ b/server/tests/api/check-params/videos.ts @@ -44,11 +44,11 @@ describe('Test videos API validator', function () { const username = 'user1' const password = 'my super password' - await server.usersCommand.create({ username: username, password: password }) - userAccessToken = await server.loginCommand.getAccessToken({ username, password }) + await server.users.create({ username: username, password: password }) + userAccessToken = await server.login.getAccessToken({ username, password }) { - const body = await server.usersCommand.getMyInfo() + const body = await server.users.getMyInfo() channelId = body.videoChannels[0].id channelName = body.videoChannels[0].name accountName = body.account.name + '@' + body.account.host @@ -274,10 +274,10 @@ describe('Test videos API validator', function () { username: 'fake' + randomInt(0, 1500), password: 'fake_password' } - await server.usersCommand.create({ username: user.username, password: user.password }) + await server.users.create({ username: user.username, password: user.password }) - const accessTokenUser = await server.loginCommand.getAccessToken(user) - const { videoChannels } = await server.usersCommand.getMyInfo({ token: accessTokenUser }) + const accessTokenUser = await server.login.getAccessToken(user) + const { videoChannels } = await server.users.getMyInfo({ token: accessTokenUser }) const customChannelId = videoChannels[0].id const fields = { ...baseCorrectParams, channelId: customChannelId } @@ -484,7 +484,7 @@ describe('Test videos API validator', function () { } before(async function () { - const { data } = await server.videosCommand.list() + const { data } = await server.videos.list() video = data[0] }) @@ -710,15 +710,15 @@ describe('Test videos API validator', function () { }) it('Should fail without a correct uuid', async function () { - await server.videosCommand.get({ id: 'coucou', expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) + await server.videos.get({ id: 'coucou', expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) it('Should return 404 with an incorrect video', async function () { - await server.videosCommand.get({ id: '4da6fde3-88f7-4d16-b119-108df5630b06', expectedStatus: HttpStatusCode.NOT_FOUND_404 }) + await server.videos.get({ id: '4da6fde3-88f7-4d16-b119-108df5630b06', expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) it('Shoud report the appropriate error', async function () { - const body = await server.videosCommand.get({ id: 'hi', expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) + const body = await server.videos.get({ id: 'hi', expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) const error = body as unknown as PeerTubeProblemDocument expect(error.docs).to.equal('https://docs.joinpeertube.org/api-rest-reference.html#operation/getVideo') @@ -734,7 +734,7 @@ describe('Test videos API validator', function () { }) it('Should succeed with the correct parameters', async function () { - await server.videosCommand.get({ id: video.shortUUID }) + await server.videos.get({ id: video.shortUUID }) }) }) @@ -742,7 +742,7 @@ describe('Test videos API validator', function () { let videoId: number before(async function () { - const { data } = await server.videosCommand.list() + const { data } = await server.videos.list() videoId = data[0].id }) @@ -797,21 +797,21 @@ describe('Test videos API validator', function () { }) it('Should fail without a correct uuid', async function () { - await server.videosCommand.remove({ id: 'hello', expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) + await server.videos.remove({ id: 'hello', expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) it('Should fail with a video which does not exist', async function () { - await server.videosCommand.remove({ id: '4da6fde3-88f7-4d16-b119-108df5630b06', expectedStatus: HttpStatusCode.NOT_FOUND_404 }) + await server.videos.remove({ id: '4da6fde3-88f7-4d16-b119-108df5630b06', expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) it('Should fail with a video of another user without the appropriate right', async function () { - await server.videosCommand.remove({ token: userAccessToken, id: video.uuid, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) + await server.videos.remove({ token: userAccessToken, id: video.uuid, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) it('Should fail with a video of another server') it('Shoud report the appropriate error', async function () { - const body = await server.videosCommand.remove({ id: 'hello', expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) + const body = await server.videos.remove({ id: 'hello', expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) const error = body as unknown as PeerTubeProblemDocument expect(error.docs).to.equal('https://docs.joinpeertube.org/api-rest-reference.html#operation/delVideo') @@ -827,7 +827,7 @@ describe('Test videos API validator', function () { }) it('Should succeed with the correct parameters', async function () { - await server.videosCommand.remove({ id: video.uuid }) + await server.videos.remove({ id: video.uuid }) }) }) diff --git a/server/tests/api/live/live-constraints.ts b/server/tests/api/live/live-constraints.ts index 7900b1abe..1c380883c 100644 --- a/server/tests/api/live/live-constraints.ts +++ b/server/tests/api/live/live-constraints.ts @@ -32,13 +32,13 @@ describe('Test live constraints', function () { saveReplay } - const { uuid } = await servers[0].liveCommand.create({ token: userAccessToken, fields: liveAttributes }) + const { uuid } = await servers[0].live.create({ token: userAccessToken, fields: liveAttributes }) return uuid } async function checkSaveReplay (videoId: string, resolutions = [ 720 ]) { for (const server of servers) { - const video = await server.videosCommand.get({ id: videoId }) + const video = await server.videos.get({ id: videoId }) expect(video.isLive).to.be.false expect(video.duration).to.be.greaterThan(0) } @@ -48,12 +48,12 @@ describe('Test live constraints', function () { async function waitUntilLivePublishedOnAllServers (videoId: string) { for (const server of servers) { - await server.liveCommand.waitUntilPublished({ videoId }) + await server.live.waitUntilPublished({ videoId }) } } function updateQuota (options: { total: number, daily: number }) { - return servers[0].usersCommand.update({ + return servers[0].users.update({ userId, videoQuota: options.total, videoQuotaDaily: options.daily @@ -69,7 +69,7 @@ describe('Test live constraints', function () { await setAccessTokensToServers(servers) await setDefaultVideoChannel(servers) - await servers[0].configCommand.updateCustomSubConfig({ + await servers[0].config.updateCustomSubConfig({ newConfig: { live: { enabled: true, @@ -82,7 +82,7 @@ describe('Test live constraints', function () { }) { - const res = await servers[0].usersCommand.generate('user1') + const res = await servers[0].users.generate('user1') userId = res.userId userChannelId = res.userChannelId userAccessToken = res.token @@ -98,7 +98,7 @@ describe('Test live constraints', function () { this.timeout(60000) const userVideoLiveoId = await createLiveWrapper(false) - await servers[0].liveCommand.runAndTestStreamError({ token: userAccessToken, videoId: userVideoLiveoId, shouldHaveError: false }) + await servers[0].live.runAndTestStreamError({ token: userAccessToken, videoId: userVideoLiveoId, shouldHaveError: false }) }) it('Should have size limit depending on user global quota if save replay is enabled', async function () { @@ -108,7 +108,7 @@ describe('Test live constraints', function () { await wait(5000) const userVideoLiveoId = await createLiveWrapper(true) - await servers[0].liveCommand.runAndTestStreamError({ token: userAccessToken, videoId: userVideoLiveoId, shouldHaveError: true }) + await servers[0].live.runAndTestStreamError({ token: userAccessToken, videoId: userVideoLiveoId, shouldHaveError: true }) await waitUntilLivePublishedOnAllServers(userVideoLiveoId) await waitJobs(servers) @@ -125,7 +125,7 @@ describe('Test live constraints', function () { await updateQuota({ total: -1, daily: 1 }) const userVideoLiveoId = await createLiveWrapper(true) - await servers[0].liveCommand.runAndTestStreamError({ token: userAccessToken, videoId: userVideoLiveoId, shouldHaveError: true }) + await servers[0].live.runAndTestStreamError({ token: userAccessToken, videoId: userVideoLiveoId, shouldHaveError: true }) await waitUntilLivePublishedOnAllServers(userVideoLiveoId) await waitJobs(servers) @@ -142,13 +142,13 @@ describe('Test live constraints', function () { await updateQuota({ total: 10 * 1000 * 1000, daily: -1 }) const userVideoLiveoId = await createLiveWrapper(true) - await servers[0].liveCommand.runAndTestStreamError({ token: userAccessToken, videoId: userVideoLiveoId, shouldHaveError: false }) + await servers[0].live.runAndTestStreamError({ token: userAccessToken, videoId: userVideoLiveoId, shouldHaveError: false }) }) it('Should have max duration limit', async function () { this.timeout(60000) - await servers[0].configCommand.updateCustomSubConfig({ + await servers[0].config.updateCustomSubConfig({ newConfig: { live: { enabled: true, @@ -163,7 +163,7 @@ describe('Test live constraints', function () { }) const userVideoLiveoId = await createLiveWrapper(true) - await servers[0].liveCommand.runAndTestStreamError({ token: userAccessToken, videoId: userVideoLiveoId, shouldHaveError: true }) + await servers[0].live.runAndTestStreamError({ token: userAccessToken, videoId: userVideoLiveoId, shouldHaveError: true }) await waitUntilLivePublishedOnAllServers(userVideoLiveoId) await waitJobs(servers) diff --git a/server/tests/api/live/live-permanent.ts b/server/tests/api/live/live-permanent.ts index 707f2edf8..900bd6f5c 100644 --- a/server/tests/api/live/live-permanent.ts +++ b/server/tests/api/live/live-permanent.ts @@ -24,20 +24,20 @@ describe('Permanent live', function () { async function createLiveWrapper (permanentLive: boolean) { const attributes: LiveVideoCreate = { - channelId: servers[0].videoChannel.id, + channelId: servers[0].store.channel.id, privacy: VideoPrivacy.PUBLIC, name: 'my super live', saveReplay: false, permanentLive } - const { uuid } = await servers[0].liveCommand.create({ fields: attributes }) + const { uuid } = await servers[0].live.create({ fields: attributes }) return uuid } async function checkVideoState (videoId: string, state: VideoState) { for (const server of servers) { - const video = await server.videosCommand.get({ id: videoId }) + const video = await server.videos.get({ id: videoId }) expect(video.state.id).to.equal(state) } } @@ -54,7 +54,7 @@ describe('Permanent live', function () { // Server 1 and server 2 follow each other await doubleFollow(servers[0], servers[1]) - await servers[0].configCommand.updateCustomSubConfig({ + await servers[0].config.updateCustomSubConfig({ newConfig: { live: { enabled: true, @@ -75,14 +75,14 @@ describe('Permanent live', function () { const videoUUID = await createLiveWrapper(false) { - const live = await servers[0].liveCommand.get({ videoId: videoUUID }) + const live = await servers[0].live.get({ videoId: videoUUID }) expect(live.permanentLive).to.be.false } - await servers[0].liveCommand.update({ videoId: videoUUID, fields: { permanentLive: true } }) + await servers[0].live.update({ videoId: videoUUID, fields: { permanentLive: true } }) { - const live = await servers[0].liveCommand.get({ videoId: videoUUID }) + const live = await servers[0].live.get({ videoId: videoUUID }) expect(live.permanentLive).to.be.true } }) @@ -92,7 +92,7 @@ describe('Permanent live', function () { videoUUID = await createLiveWrapper(true) - const live = await servers[0].liveCommand.get({ videoId: videoUUID }) + const live = await servers[0].live.get({ videoId: videoUUID }) expect(live.permanentLive).to.be.true await waitJobs(servers) @@ -101,16 +101,16 @@ describe('Permanent live', function () { it('Should stream into this permanent live', async function () { this.timeout(120000) - const ffmpegCommand = await servers[0].liveCommand.sendRTMPStreamInVideo({ videoId: videoUUID }) + const ffmpegCommand = await servers[0].live.sendRTMPStreamInVideo({ videoId: videoUUID }) for (const server of servers) { - await server.liveCommand.waitUntilPublished({ videoId: videoUUID }) + await server.live.waitUntilPublished({ videoId: videoUUID }) } await checkVideoState(videoUUID, VideoState.PUBLISHED) await stopFfmpeg(ffmpegCommand) - await servers[0].liveCommand.waitUntilWaiting({ videoId: videoUUID }) + await servers[0].live.waitUntilWaiting({ videoId: videoUUID }) await waitJobs(servers) }) @@ -122,7 +122,7 @@ describe('Permanent live', function () { await waitJobs(servers) for (const server of servers) { - const videoDetails = await server.videosCommand.get({ id: videoUUID }) + const videoDetails = await server.videos.get({ id: videoUUID }) expect(videoDetails.streamingPlaylists).to.have.lengthOf(1) } }) @@ -136,7 +136,7 @@ describe('Permanent live', function () { it('Should be able to stream again in the permanent live', async function () { this.timeout(20000) - await servers[0].configCommand.updateCustomSubConfig({ + await servers[0].config.updateCustomSubConfig({ newConfig: { live: { enabled: true, @@ -150,15 +150,15 @@ describe('Permanent live', function () { } }) - const ffmpegCommand = await servers[0].liveCommand.sendRTMPStreamInVideo({ videoId: videoUUID }) + const ffmpegCommand = await servers[0].live.sendRTMPStreamInVideo({ videoId: videoUUID }) for (const server of servers) { - await server.liveCommand.waitUntilPublished({ videoId: videoUUID }) + await server.live.waitUntilPublished({ videoId: videoUUID }) } await checkVideoState(videoUUID, VideoState.PUBLISHED) - const count = await servers[0].liveCommand.countPlaylists({ videoUUID }) + const count = await servers[0].live.countPlaylists({ videoUUID }) // master playlist and 720p playlist expect(count).to.equal(2) diff --git a/server/tests/api/live/live-save-replay.ts b/server/tests/api/live/live-save-replay.ts index a87a2cd12..7a33df90a 100644 --- a/server/tests/api/live/live-save-replay.ts +++ b/server/tests/api/live/live-save-replay.ts @@ -30,19 +30,19 @@ describe('Save replay setting', function () { async function createLiveWrapper (saveReplay: boolean) { if (liveVideoUUID) { try { - await servers[0].videosCommand.remove({ id: liveVideoUUID }) + await servers[0].videos.remove({ id: liveVideoUUID }) await waitJobs(servers) } catch {} } const attributes: LiveVideoCreate = { - channelId: servers[0].videoChannel.id, + channelId: servers[0].store.channel.id, privacy: VideoPrivacy.PUBLIC, name: 'my super live', saveReplay } - const { uuid } = await servers[0].liveCommand.create({ fields: attributes }) + const { uuid } = await servers[0].live.create({ fields: attributes }) return uuid } @@ -50,32 +50,32 @@ describe('Save replay setting', function () { for (const server of servers) { const length = existsInList ? 1 : 0 - const { data, total } = await server.videosCommand.list() + const { data, total } = await server.videos.list() expect(data).to.have.lengthOf(length) expect(total).to.equal(length) if (expectedStatus) { - await server.videosCommand.get({ id: videoId, expectedStatus }) + await server.videos.get({ id: videoId, expectedStatus }) } } } async function checkVideoState (videoId: string, state: VideoState) { for (const server of servers) { - const video = await server.videosCommand.get({ id: videoId }) + const video = await server.videos.get({ id: videoId }) expect(video.state.id).to.equal(state) } } async function waitUntilLivePublishedOnAllServers (videoId: string) { for (const server of servers) { - await server.liveCommand.waitUntilPublished({ videoId }) + await server.live.waitUntilPublished({ videoId }) } } async function waitUntilLiveSavedOnAllServers (videoId: string) { for (const server of servers) { - await server.liveCommand.waitUntilSaved({ videoId }) + await server.live.waitUntilSaved({ videoId }) } } @@ -91,7 +91,7 @@ describe('Save replay setting', function () { // Server 1 and server 2 follow each other await doubleFollow(servers[0], servers[1]) - await servers[0].configCommand.updateCustomSubConfig({ + await servers[0].config.updateCustomSubConfig({ newConfig: { live: { enabled: true, @@ -126,7 +126,7 @@ describe('Save replay setting', function () { it('Should correctly have updated the live and federated it when streaming in the live', async function () { this.timeout(30000) - ffmpegCommand = await servers[0].liveCommand.sendRTMPStreamInVideo({ videoId: liveVideoUUID }) + ffmpegCommand = await servers[0].live.sendRTMPStreamInVideo({ videoId: liveVideoUUID }) await waitUntilLivePublishedOnAllServers(liveVideoUUID) @@ -142,7 +142,7 @@ describe('Save replay setting', function () { await stopFfmpeg(ffmpegCommand) for (const server of servers) { - await server.liveCommand.waitUntilEnded({ videoId: liveVideoUUID }) + await server.live.waitUntilEnded({ videoId: liveVideoUUID }) } await waitJobs(servers) @@ -159,7 +159,7 @@ describe('Save replay setting', function () { liveVideoUUID = await createLiveWrapper(false) - ffmpegCommand = await servers[0].liveCommand.sendRTMPStreamInVideo({ videoId: liveVideoUUID }) + ffmpegCommand = await servers[0].live.sendRTMPStreamInVideo({ videoId: liveVideoUUID }) await waitUntilLivePublishedOnAllServers(liveVideoUUID) @@ -167,7 +167,7 @@ describe('Save replay setting', function () { await checkVideosExist(liveVideoUUID, true, HttpStatusCode.OK_200) await Promise.all([ - servers[0].blacklistCommand.add({ videoId: liveVideoUUID, reason: 'bad live', unfederate: true }), + servers[0].blacklist.add({ videoId: liveVideoUUID, reason: 'bad live', unfederate: true }), testFfmpegStreamError(ffmpegCommand, true) ]) @@ -175,8 +175,8 @@ describe('Save replay setting', function () { await checkVideosExist(liveVideoUUID, false) - await servers[0].videosCommand.get({ id: liveVideoUUID, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) - await servers[1].videosCommand.get({ id: liveVideoUUID, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) + await servers[0].videos.get({ id: liveVideoUUID, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) + await servers[1].videos.get({ id: liveVideoUUID, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) await wait(5000) await waitJobs(servers) @@ -188,7 +188,7 @@ describe('Save replay setting', function () { liveVideoUUID = await createLiveWrapper(false) - ffmpegCommand = await servers[0].liveCommand.sendRTMPStreamInVideo({ videoId: liveVideoUUID }) + ffmpegCommand = await servers[0].live.sendRTMPStreamInVideo({ videoId: liveVideoUUID }) await waitUntilLivePublishedOnAllServers(liveVideoUUID) @@ -197,7 +197,7 @@ describe('Save replay setting', function () { await Promise.all([ testFfmpegStreamError(ffmpegCommand, true), - servers[0].videosCommand.remove({ id: liveVideoUUID }) + servers[0].videos.remove({ id: liveVideoUUID }) ]) await wait(5000) @@ -224,7 +224,7 @@ describe('Save replay setting', function () { it('Should correctly have updated the live and federated it when streaming in the live', async function () { this.timeout(20000) - ffmpegCommand = await servers[0].liveCommand.sendRTMPStreamInVideo({ videoId: liveVideoUUID }) + ffmpegCommand = await servers[0].live.sendRTMPStreamInVideo({ videoId: liveVideoUUID }) await waitUntilLivePublishedOnAllServers(liveVideoUUID) await waitJobs(servers) @@ -249,11 +249,11 @@ describe('Save replay setting', function () { it('Should update the saved live and correctly federate the updated attributes', async function () { this.timeout(30000) - await servers[0].videosCommand.update({ id: liveVideoUUID, attributes: { name: 'video updated' } }) + await servers[0].videos.update({ id: liveVideoUUID, attributes: { name: 'video updated' } }) await waitJobs(servers) for (const server of servers) { - const video = await server.videosCommand.get({ id: liveVideoUUID }) + const video = await server.videos.get({ id: liveVideoUUID }) expect(video.name).to.equal('video updated') expect(video.isLive).to.be.false } @@ -268,14 +268,14 @@ describe('Save replay setting', function () { liveVideoUUID = await createLiveWrapper(true) - ffmpegCommand = await servers[0].liveCommand.sendRTMPStreamInVideo({ videoId: liveVideoUUID }) + ffmpegCommand = await servers[0].live.sendRTMPStreamInVideo({ videoId: liveVideoUUID }) await waitUntilLivePublishedOnAllServers(liveVideoUUID) await waitJobs(servers) await checkVideosExist(liveVideoUUID, true, HttpStatusCode.OK_200) await Promise.all([ - servers[0].blacklistCommand.add({ videoId: liveVideoUUID, reason: 'bad live', unfederate: true }), + servers[0].blacklist.add({ videoId: liveVideoUUID, reason: 'bad live', unfederate: true }), testFfmpegStreamError(ffmpegCommand, true) ]) @@ -283,8 +283,8 @@ describe('Save replay setting', function () { await checkVideosExist(liveVideoUUID, false) - await servers[0].videosCommand.get({ id: liveVideoUUID, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) - await servers[1].videosCommand.get({ id: liveVideoUUID, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) + await servers[0].videos.get({ id: liveVideoUUID, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) + await servers[1].videos.get({ id: liveVideoUUID, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) await wait(5000) await waitJobs(servers) @@ -296,14 +296,14 @@ describe('Save replay setting', function () { liveVideoUUID = await createLiveWrapper(true) - ffmpegCommand = await servers[0].liveCommand.sendRTMPStreamInVideo({ videoId: liveVideoUUID }) + ffmpegCommand = await servers[0].live.sendRTMPStreamInVideo({ videoId: liveVideoUUID }) await waitUntilLivePublishedOnAllServers(liveVideoUUID) await waitJobs(servers) await checkVideosExist(liveVideoUUID, true, HttpStatusCode.OK_200) await Promise.all([ - servers[0].videosCommand.remove({ id: liveVideoUUID }), + servers[0].videos.remove({ id: liveVideoUUID }), testFfmpegStreamError(ffmpegCommand, true) ]) diff --git a/server/tests/api/live/live-socket-messages.ts b/server/tests/api/live/live-socket-messages.ts index 1f3d455a8..ad67d6285 100644 --- a/server/tests/api/live/live-socket-messages.ts +++ b/server/tests/api/live/live-socket-messages.ts @@ -30,7 +30,7 @@ describe('Test live', function () { await setAccessTokensToServers(servers) await setDefaultVideoChannel(servers) - await servers[0].configCommand.updateCustomSubConfig({ + await servers[0].config.updateCustomSubConfig({ newConfig: { live: { enabled: true, @@ -51,11 +51,11 @@ describe('Test live', function () { async function createLiveWrapper () { const liveAttributes = { name: 'live video', - channelId: servers[0].videoChannel.id, + channelId: servers[0].store.channel.id, privacy: VideoPrivacy.PUBLIC } - const { uuid } = await servers[0].liveCommand.create({ fields: liveAttributes }) + const { uuid } = await servers[0].live.create({ fields: liveAttributes }) return uuid } @@ -69,22 +69,22 @@ describe('Test live', function () { await waitJobs(servers) { - const videoId = await servers[0].videosCommand.getId({ uuid: liveVideoUUID }) + const videoId = await servers[0].videos.getId({ uuid: liveVideoUUID }) - const localSocket = servers[0].socketIOCommand.getLiveNotificationSocket() + const localSocket = servers[0].socketIO.getLiveNotificationSocket() localSocket.on('state-change', data => localStateChanges.push(data.state)) localSocket.emit('subscribe', { videoId }) } { - const videoId = await servers[1].videosCommand.getId({ uuid: liveVideoUUID }) + const videoId = await servers[1].videos.getId({ uuid: liveVideoUUID }) - const remoteSocket = servers[1].socketIOCommand.getLiveNotificationSocket() + const remoteSocket = servers[1].socketIO.getLiveNotificationSocket() remoteSocket.on('state-change', data => remoteStateChanges.push(data.state)) remoteSocket.emit('subscribe', { videoId }) } - const ffmpegCommand = await servers[0].liveCommand.sendRTMPStreamInVideo({ videoId: liveVideoUUID }) + const ffmpegCommand = await servers[0].live.sendRTMPStreamInVideo({ videoId: liveVideoUUID }) await waitUntilLivePublishedOnAllServers(servers, liveVideoUUID) await waitJobs(servers) @@ -97,7 +97,7 @@ describe('Test live', function () { await stopFfmpeg(ffmpegCommand) for (const server of servers) { - await server.liveCommand.waitUntilEnded({ videoId: liveVideoUUID }) + await server.live.waitUntilEnded({ videoId: liveVideoUUID }) } await waitJobs(servers) @@ -117,22 +117,22 @@ describe('Test live', function () { await waitJobs(servers) { - const videoId = await servers[0].videosCommand.getId({ uuid: liveVideoUUID }) + const videoId = await servers[0].videos.getId({ uuid: liveVideoUUID }) - const localSocket = servers[0].socketIOCommand.getLiveNotificationSocket() + const localSocket = servers[0].socketIO.getLiveNotificationSocket() localSocket.on('views-change', data => { localLastVideoViews = data.views }) localSocket.emit('subscribe', { videoId }) } { - const videoId = await servers[1].videosCommand.getId({ uuid: liveVideoUUID }) + const videoId = await servers[1].videos.getId({ uuid: liveVideoUUID }) - const remoteSocket = servers[1].socketIOCommand.getLiveNotificationSocket() + const remoteSocket = servers[1].socketIO.getLiveNotificationSocket() remoteSocket.on('views-change', data => { remoteLastVideoViews = data.views }) remoteSocket.emit('subscribe', { videoId }) } - const ffmpegCommand = await servers[0].liveCommand.sendRTMPStreamInVideo({ videoId: liveVideoUUID }) + const ffmpegCommand = await servers[0].live.sendRTMPStreamInVideo({ videoId: liveVideoUUID }) await waitUntilLivePublishedOnAllServers(servers, liveVideoUUID) await waitJobs(servers) @@ -140,8 +140,8 @@ describe('Test live', function () { expect(localLastVideoViews).to.equal(0) expect(remoteLastVideoViews).to.equal(0) - await servers[0].videosCommand.view({ id: liveVideoUUID }) - await servers[1].videosCommand.view({ id: liveVideoUUID }) + await servers[0].videos.view({ id: liveVideoUUID }) + await servers[1].videos.view({ id: liveVideoUUID }) await waitJobs(servers) await wait(5000) @@ -161,13 +161,13 @@ describe('Test live', function () { const liveVideoUUID = await createLiveWrapper() await waitJobs(servers) - const videoId = await servers[0].videosCommand.getId({ uuid: liveVideoUUID }) + const videoId = await servers[0].videos.getId({ uuid: liveVideoUUID }) - const socket = servers[0].socketIOCommand.getLiveNotificationSocket() + const socket = servers[0].socketIO.getLiveNotificationSocket() socket.on('state-change', data => stateChanges.push(data.state)) socket.emit('subscribe', { videoId }) - const command = await servers[0].liveCommand.sendRTMPStreamInVideo({ videoId: liveVideoUUID }) + const command = await servers[0].live.sendRTMPStreamInVideo({ videoId: liveVideoUUID }) await waitUntilLivePublishedOnAllServers(servers, liveVideoUUID) await waitJobs(servers) diff --git a/server/tests/api/live/live-views.ts b/server/tests/api/live/live-views.ts index 1951b11a5..43222f9c9 100644 --- a/server/tests/api/live/live-views.ts +++ b/server/tests/api/live/live-views.ts @@ -31,7 +31,7 @@ describe('Test live', function () { await setAccessTokensToServers(servers) await setDefaultVideoChannel(servers) - await servers[0].configCommand.updateCustomSubConfig({ + await servers[0].config.updateCustomSubConfig({ newConfig: { live: { enabled: true, @@ -53,7 +53,7 @@ describe('Test live', function () { async function countViews (expected: number) { for (const server of servers) { - const video = await server.videosCommand.get({ id: liveVideoId }) + const video = await server.videos.get({ id: liveVideoId }) expect(video.views).to.equal(expected) } } @@ -63,14 +63,14 @@ describe('Test live', function () { const liveAttributes = { name: 'live video', - channelId: servers[0].videoChannel.id, + channelId: servers[0].store.channel.id, privacy: VideoPrivacy.PUBLIC } - const live = await servers[0].liveCommand.create({ fields: liveAttributes }) + const live = await servers[0].live.create({ fields: liveAttributes }) liveVideoId = live.uuid - command = await servers[0].liveCommand.sendRTMPStreamInVideo({ videoId: liveVideoId }) + command = await servers[0].live.sendRTMPStreamInVideo({ videoId: liveVideoId }) await waitUntilLivePublishedOnAllServers(servers, liveVideoId) await waitJobs(servers) }) @@ -82,8 +82,8 @@ describe('Test live', function () { it('Should view a live twice and display 1 view', async function () { this.timeout(30000) - await servers[0].videosCommand.view({ id: liveVideoId }) - await servers[0].videosCommand.view({ id: liveVideoId }) + await servers[0].videos.view({ id: liveVideoId }) + await servers[0].videos.view({ id: liveVideoId }) await wait(7000) @@ -104,9 +104,9 @@ describe('Test live', function () { it('Should view a live on a remote and on local and display 2 views', async function () { this.timeout(30000) - await servers[0].videosCommand.view({ id: liveVideoId }) - await servers[1].videosCommand.view({ id: liveVideoId }) - await servers[1].videosCommand.view({ id: liveVideoId }) + await servers[0].videos.view({ id: liveVideoId }) + await servers[1].videos.view({ id: liveVideoId }) + await servers[1].videos.view({ id: liveVideoId }) await wait(7000) await waitJobs(servers) diff --git a/server/tests/api/live/live.ts b/server/tests/api/live/live.ts index c88143982..2cce1f448 100644 --- a/server/tests/api/live/live.ts +++ b/server/tests/api/live/live.ts @@ -44,7 +44,7 @@ describe('Test live', function () { await setAccessTokensToServers(servers) await setDefaultVideoChannel(servers) - await servers[0].configCommand.updateCustomSubConfig({ + await servers[0].config.updateCustomSubConfig({ newConfig: { live: { enabled: true, @@ -59,7 +59,7 @@ describe('Test live', function () { // Server 1 and server 2 follow each other await doubleFollow(servers[0], servers[1]) - commands = servers.map(s => s.liveCommand) + commands = servers.map(s => s.live) }) describe('Live creation, update and delete', function () { @@ -74,7 +74,7 @@ describe('Test live', function () { language: 'fr', description: 'super live description', support: 'support field', - channelId: servers[0].videoChannel.id, + channelId: servers[0].store.channel.id, nsfw: false, waitTranscoding: false, name: 'my super live', @@ -93,7 +93,7 @@ describe('Test live', function () { await waitJobs(servers) for (const server of servers) { - const video = await server.videosCommand.get({ id: liveVideoUUID }) + const video = await server.videos.get({ id: liveVideoUUID }) expect(video.category.id).to.equal(1) expect(video.licence.id).to.equal(2) @@ -101,8 +101,8 @@ describe('Test live', function () { expect(video.description).to.equal('super live description') expect(video.support).to.equal('support field') - expect(video.channel.name).to.equal(servers[0].videoChannel.name) - expect(video.channel.host).to.equal(servers[0].videoChannel.host) + expect(video.channel.name).to.equal(servers[0].store.channel.name) + expect(video.channel.host).to.equal(servers[0].store.channel.host) expect(video.isLive).to.be.true @@ -117,7 +117,7 @@ describe('Test live', function () { await testImage(server.url, 'video_short1-preview.webm', video.previewPath) await testImage(server.url, 'video_short1.webm', video.thumbnailPath) - const live = await server.liveCommand.get({ videoId: liveVideoUUID }) + const live = await server.live.get({ videoId: liveVideoUUID }) if (server.url === servers[0].url) { expect(live.rtmpUrl).to.equal('rtmp://' + server.hostname + ':' + servers[0].rtmpPort + '/live') @@ -136,7 +136,7 @@ describe('Test live', function () { const attributes: LiveVideoCreate = { name: 'default live thumbnail', - channelId: servers[0].videoChannel.id, + channelId: servers[0].store.channel.id, privacy: VideoPrivacy.UNLISTED, nsfw: true } @@ -147,7 +147,7 @@ describe('Test live', function () { await waitJobs(servers) for (const server of servers) { - const video = await server.videosCommand.get({ id: videoId }) + const video = await server.videos.get({ id: videoId }) expect(video.privacy.id).to.equal(VideoPrivacy.UNLISTED) expect(video.nsfw).to.be.true @@ -158,7 +158,7 @@ describe('Test live', function () { it('Should not have the live listed since nobody streams into', async function () { for (const server of servers) { - const { total, data } = await server.videosCommand.list() + const { total, data } = await server.videos.list() expect(total).to.equal(0) expect(data).to.have.lengthOf(0) @@ -178,7 +178,7 @@ describe('Test live', function () { it('Have the live updated', async function () { for (const server of servers) { - const live = await server.liveCommand.get({ videoId: liveVideoUUID }) + const live = await server.live.get({ videoId: liveVideoUUID }) if (server.url === servers[0].url) { expect(live.rtmpUrl).to.equal('rtmp://' + server.hostname + ':' + servers[0].rtmpPort + '/live') @@ -195,14 +195,14 @@ describe('Test live', function () { it('Delete the live', async function () { this.timeout(10000) - await servers[0].videosCommand.remove({ id: liveVideoUUID }) + await servers[0].videos.remove({ id: liveVideoUUID }) await waitJobs(servers) }) it('Should have the live deleted', async function () { for (const server of servers) { - await server.videosCommand.get({ id: liveVideoUUID, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) - await server.liveCommand.get({ videoId: liveVideoUUID, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) + await server.videos.get({ id: liveVideoUUID, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) + await server.live.get({ videoId: liveVideoUUID, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) } }) }) @@ -215,19 +215,19 @@ describe('Test live', function () { before(async function () { this.timeout(120000) - vodVideoId = (await servers[0].videosCommand.quickUpload({ name: 'vod video' })).uuid + vodVideoId = (await servers[0].videos.quickUpload({ name: 'vod video' })).uuid - const liveOptions = { name: 'live', privacy: VideoPrivacy.PUBLIC, channelId: servers[0].videoChannel.id } + const liveOptions = { name: 'live', privacy: VideoPrivacy.PUBLIC, channelId: servers[0].store.channel.id } const live = await commands[0].create({ fields: liveOptions }) liveVideoId = live.uuid - ffmpegCommand = await servers[0].liveCommand.sendRTMPStreamInVideo({ videoId: liveVideoId }) + ffmpegCommand = await servers[0].live.sendRTMPStreamInVideo({ videoId: liveVideoId }) await waitUntilLivePublishedOnAllServers(servers, liveVideoId) await waitJobs(servers) }) it('Should only display lives', async function () { - const { data, total } = await servers[0].videosCommand.list({ isLive: true }) + const { data, total } = await servers[0].videos.list({ isLive: true }) expect(total).to.equal(1) expect(data).to.have.lengthOf(1) @@ -235,7 +235,7 @@ describe('Test live', function () { }) it('Should not display lives', async function () { - const { data, total } = await servers[0].videosCommand.list({ isLive: false }) + const { data, total } = await servers[0].videos.list({ isLive: false }) expect(total).to.equal(1) expect(data).to.have.lengthOf(1) @@ -248,22 +248,22 @@ describe('Test live', function () { await stopFfmpeg(ffmpegCommand) await waitJobs(servers) - const { data } = await servers[0].videosCommand.listMyVideos({ isLive: true }) + const { data } = await servers[0].videos.listMyVideos({ isLive: true }) const result = data.every(v => v.isLive) expect(result).to.be.true }) it('Should not display my lives', async function () { - const { data } = await servers[0].videosCommand.listMyVideos({ isLive: false }) + const { data } = await servers[0].videos.listMyVideos({ isLive: false }) const result = data.every(v => !v.isLive) expect(result).to.be.true }) after(async function () { - await servers[0].videosCommand.remove({ id: vodVideoId }) - await servers[0].videosCommand.remove({ id: liveVideoId }) + await servers[0].videos.remove({ id: vodVideoId }) + await servers[0].videos.remove({ id: liveVideoId }) }) }) @@ -278,7 +278,7 @@ describe('Test live', function () { async function createLiveWrapper () { const liveAttributes = { name: 'user live', - channelId: servers[0].videoChannel.id, + channelId: servers[0].store.channel.id, privacy: VideoPrivacy.PUBLIC, saveReplay: false } @@ -286,7 +286,7 @@ describe('Test live', function () { const { uuid } = await commands[0].create({ fields: liveAttributes }) const live = await commands[0].get({ videoId: uuid }) - const video = await servers[0].videosCommand.get({ id: uuid }) + const video = await servers[0].videos.get({ id: uuid }) return Object.assign(video, live) } @@ -316,7 +316,7 @@ describe('Test live', function () { it('Should list this live now someone stream into it', async function () { for (const server of servers) { - const { total, data } = await server.videosCommand.list() + const { total, data } = await server.videos.list() expect(total).to.equal(1) expect(data).to.have.lengthOf(1) @@ -332,7 +332,7 @@ describe('Test live', function () { liveVideo = await createLiveWrapper() - await servers[0].blacklistCommand.add({ videoId: liveVideo.uuid }) + await servers[0].blacklist.add({ videoId: liveVideo.uuid }) const command = sendRTMPStream(rtmpUrl + '/live', liveVideo.streamKey) await testFfmpegStreamError(command, true) @@ -343,7 +343,7 @@ describe('Test live', function () { liveVideo = await createLiveWrapper() - await servers[0].videosCommand.remove({ id: liveVideo.uuid }) + await servers[0].videos.remove({ id: liveVideo.uuid }) const command = sendRTMPStream(rtmpUrl + '/live', liveVideo.streamKey) await testFfmpegStreamError(command, true) @@ -356,7 +356,7 @@ describe('Test live', function () { async function createLiveWrapper (saveReplay: boolean) { const liveAttributes = { name: 'live video', - channelId: servers[0].videoChannel.id, + channelId: servers[0].store.channel.id, privacy: VideoPrivacy.PUBLIC, saveReplay } @@ -367,10 +367,10 @@ describe('Test live', function () { async function testVideoResolutions (liveVideoId: string, resolutions: number[]) { for (const server of servers) { - const { data } = await server.videosCommand.list() + const { data } = await server.videos.list() expect(data.find(v => v.uuid === liveVideoId)).to.exist - const video = await server.videosCommand.get({ id: liveVideoId }) + const video = await server.videos.get({ id: liveVideoId }) expect(video.streamingPlaylists).to.have.lengthOf(1) @@ -387,7 +387,7 @@ describe('Test live', function () { const segmentName = `${i}-00000${segmentNum}.ts` await commands[0].waitUntilSegmentGeneration({ videoUUID: video.uuid, resolution: i, segment: segmentNum }) - const subPlaylist = await servers[0].streamingPlaylistsCommand.get({ + const subPlaylist = await servers[0].streamingPlaylists.get({ url: `${servers[0].url}/static/streaming-playlists/hls/${video.uuid}/${i}.m3u8` }) @@ -406,7 +406,7 @@ describe('Test live', function () { } function updateConf (resolutions: number[]) { - return servers[0].configCommand.updateCustomSubConfig({ + return servers[0].config.updateCustomSubConfig({ newConfig: { live: { enabled: true, @@ -490,7 +490,7 @@ describe('Test live', function () { } for (const server of servers) { - const video = await server.videosCommand.get({ id: liveVideoId }) + const video = await server.videos.get({ id: liveVideoId }) expect(video.state.id).to.equal(VideoState.PUBLISHED) expect(video.duration).to.be.greaterThan(1) @@ -515,7 +515,7 @@ describe('Test live', function () { } const filename = `${video.uuid}-${resolution}-fragmented.mp4` - const segmentPath = servers[0].serversCommand.buildDirectory(join('streaming-playlists', 'hls', video.uuid, filename)) + const segmentPath = servers[0].servers.buildDirectory(join('streaming-playlists', 'hls', video.uuid, filename)) const probe = await ffprobePromise(segmentPath) const videoStream = await getVideoStreamFromFile(segmentPath, probe) @@ -542,7 +542,7 @@ describe('Test live', function () { async function createLiveWrapper (saveReplay: boolean) { const liveAttributes = { name: 'live video', - channelId: servers[0].videoChannel.id, + channelId: servers[0].store.channel.id, privacy: VideoPrivacy.PUBLIC, saveReplay } diff --git a/server/tests/api/moderation/abuses.ts b/server/tests/api/moderation/abuses.ts index 7574b8f4a..97a0d95c4 100644 --- a/server/tests/api/moderation/abuses.ts +++ b/server/tests/api/moderation/abuses.ts @@ -33,7 +33,7 @@ describe('Test abuses', function () { // Server 1 and server 2 follow each other await doubleFollow(servers[0], servers[1]) - commands = servers.map(s => s.abusesCommand) + commands = servers.map(s => s.abuses) }) describe('Video abuses', function () { @@ -47,7 +47,7 @@ describe('Test abuses', function () { name: 'my super name for server 1', description: 'my super description for server 1' } - await servers[0].videosCommand.upload({ attributes }) + await servers[0].videos.upload({ attributes }) } { @@ -55,17 +55,17 @@ describe('Test abuses', function () { name: 'my super name for server 2', description: 'my super description for server 2' } - await servers[1].videosCommand.upload({ attributes }) + await servers[1].videos.upload({ attributes }) } // Wait videos propagation, server 2 has transcoding enabled await waitJobs(servers) - const { data } = await servers[0].videosCommand.list() + const { data } = await servers[0].videos.list() expect(data.length).to.equal(2) - servers[0].video = data.find(video => video.name === 'my super name for server 1') - servers[1].video = data.find(video => video.name === 'my super name for server 2') + servers[0].store.video = data.find(video => video.name === 'my super name for server 1') + servers[1].store.video = data.find(video => video.name === 'my super name for server 2') }) it('Should not have abuses', async function () { @@ -80,7 +80,7 @@ describe('Test abuses', function () { this.timeout(15000) const reason = 'my super bad reason' - await commands[0].report({ videoId: servers[0].video.id, reason }) + await commands[0].report({ videoId: servers[0].store.video.id, reason }) // We wait requests propagation, even if the server 1 is not supposed to make a request to server 2 await waitJobs(servers) @@ -100,7 +100,7 @@ describe('Test abuses', function () { expect(abuse.reporterAccount.name).to.equal('root') expect(abuse.reporterAccount.host).to.equal(servers[0].host) - expect(abuse.video.id).to.equal(servers[0].video.id) + expect(abuse.video.id).to.equal(servers[0].store.video.id) expect(abuse.video.channel).to.exist expect(abuse.comment).to.be.null @@ -127,7 +127,7 @@ describe('Test abuses', function () { this.timeout(10000) const reason = 'my super bad reason 2' - const videoId = await servers[0].videosCommand.getId({ uuid: servers[1].video.uuid }) + const videoId = await servers[0].videos.getId({ uuid: servers[1].store.video.uuid }) await commands[0].report({ videoId, reason }) // We wait requests propagation @@ -146,7 +146,7 @@ describe('Test abuses', function () { expect(abuse1.reporterAccount.name).to.equal('root') expect(abuse1.reporterAccount.host).to.equal(servers[0].host) - expect(abuse1.video.id).to.equal(servers[0].video.id) + expect(abuse1.video.id).to.equal(servers[0].store.video.id) expect(abuse1.video.countReports).to.equal(1) expect(abuse1.video.nthReport).to.equal(1) @@ -165,7 +165,7 @@ describe('Test abuses', function () { expect(abuse2.reporterAccount.name).to.equal('root') expect(abuse2.reporterAccount.host).to.equal(servers[0].host) - expect(abuse2.video.id).to.equal(servers[1].video.id) + expect(abuse2.video.id).to.equal(servers[1].store.video.id) expect(abuse2.comment).to.be.null @@ -200,7 +200,7 @@ describe('Test abuses', function () { this.timeout(10000) { - const videoId = await servers[1].videosCommand.getId({ uuid: servers[0].video.uuid }) + const videoId = await servers[1].videos.getId({ uuid: servers[0].store.video.uuid }) await commands[1].report({ videoId, reason: 'will mute this' }) await waitJobs(servers) @@ -211,7 +211,7 @@ describe('Test abuses', function () { const accountToBlock = 'root@' + servers[1].host { - await servers[0].blocklistCommand.addToServerBlocklist({ account: accountToBlock }) + await servers[0].blocklist.addToServerBlocklist({ account: accountToBlock }) const body = await commands[0].getAdminList() expect(body.total).to.equal(2) @@ -221,7 +221,7 @@ describe('Test abuses', function () { } { - await servers[0].blocklistCommand.removeFromServerBlocklist({ account: accountToBlock }) + await servers[0].blocklist.removeFromServerBlocklist({ account: accountToBlock }) const body = await commands[0].getAdminList() expect(body.total).to.equal(3) @@ -232,7 +232,7 @@ describe('Test abuses', function () { const serverToBlock = servers[1].host { - await servers[0].blocklistCommand.addToServerBlocklist({ server: serverToBlock }) + await servers[0].blocklist.addToServerBlocklist({ server: serverToBlock }) const body = await commands[0].getAdminList() expect(body.total).to.equal(2) @@ -242,7 +242,7 @@ describe('Test abuses', function () { } { - await servers[0].blocklistCommand.removeFromServerBlocklist({ server: serverToBlock }) + await servers[0].blocklist.removeFromServerBlocklist({ server: serverToBlock }) const body = await commands[0].getAdminList() expect(body.total).to.equal(3) @@ -252,7 +252,7 @@ describe('Test abuses', function () { it('Should keep the video abuse when deleting the video', async function () { this.timeout(10000) - await servers[1].videosCommand.remove({ id: abuseServer2.video.uuid }) + await servers[1].videos.remove({ id: abuseServer2.video.uuid }) await waitJobs(servers) @@ -272,15 +272,15 @@ describe('Test abuses', function () { // register a second user to have two reporters/reportees const user = { username: 'user2', password: 'password' } - await servers[0].usersCommand.create({ ...user }) - const userAccessToken = await servers[0].loginCommand.getAccessToken(user) + await servers[0].users.create({ ...user }) + const userAccessToken = await servers[0].login.getAccessToken(user) // upload a third video via this user const attributes = { name: 'my second super name for server 1', description: 'my second super description for server 1' } - const { id } = await servers[0].videosCommand.upload({ token: userAccessToken, attributes }) + const { id } = await servers[0].videos.upload({ token: userAccessToken, attributes }) const video3Id = id // resume with the test @@ -288,7 +288,7 @@ describe('Test abuses', function () { await commands[0].report({ videoId: video3Id, reason: reason3 }) const reason4 = 'my super bad reason 4' - await commands[0].report({ token: userAccessToken, videoId: servers[0].video.id, reason: reason4 }) + await commands[0].report({ token: userAccessToken, videoId: servers[0].store.video.id, reason: reason4 }) { const body = await commands[0].getAdminList() @@ -301,7 +301,7 @@ describe('Test abuses', function () { expect(abuseVideo3.countReportsForReportee).to.equal(1, "wrong reports count for reporter on video 3 abuse") expect(abuseVideo3.countReportsForReporter).to.equal(3, "wrong reports count for reportee on video 3 abuse") - const abuseServer1 = abuses.find(a => a.video.id === servers[0].video.id) + const abuseServer1 = abuses.find(a => a.video.id === servers[0].store.video.id) expect(abuseServer1.countReportsForReportee).to.equal(3, "wrong reports count for reporter on video 1 abuse") } }) @@ -312,7 +312,7 @@ describe('Test abuses', function () { const reason5 = 'my super bad reason 5' const predefinedReasons5: AbusePredefinedReasonsString[] = [ 'violentOrRepulsive', 'captions' ] const createRes = await commands[0].report({ - videoId: servers[0].video.id, + videoId: servers[0].store.video.id, reason: reason5, predefinedReasons: predefinedReasons5, startAt: 1, @@ -391,10 +391,10 @@ describe('Test abuses', function () { async function getComment (server: ServerInfo, videoIdArg: number | string) { const videoId = typeof videoIdArg === 'string' - ? await server.videosCommand.getId({ uuid: videoIdArg }) + ? await server.videos.getId({ uuid: videoIdArg }) : videoIdArg - const { data } = await server.commentsCommand.listThreads({ videoId }) + const { data } = await server.comments.listThreads({ videoId }) return data[0] } @@ -402,11 +402,11 @@ describe('Test abuses', function () { before(async function () { this.timeout(50000) - servers[0].video = await await servers[0].videosCommand.quickUpload({ name: 'server 1' }) - servers[1].video = await await servers[1].videosCommand.quickUpload({ name: 'server 2' }) + servers[0].store.video = await await servers[0].videos.quickUpload({ name: 'server 1' }) + servers[1].store.video = await await servers[1].videos.quickUpload({ name: 'server 2' }) - await servers[0].commentsCommand.createThread({ videoId: servers[0].video.id, text: 'comment server 1' }) - await servers[1].commentsCommand.createThread({ videoId: servers[1].video.id, text: 'comment server 2' }) + await servers[0].comments.createThread({ videoId: servers[0].store.video.id, text: 'comment server 1' }) + await servers[1].comments.createThread({ videoId: servers[1].store.video.id, text: 'comment server 2' }) await waitJobs(servers) }) @@ -414,7 +414,7 @@ describe('Test abuses', function () { it('Should report abuse on a comment', async function () { this.timeout(15000) - const comment = await getComment(servers[0], servers[0].video.id) + const comment = await getComment(servers[0], servers[0].store.video.id) const reason = 'it is a bad comment' await commands[0].report({ commentId: comment.id, reason }) @@ -424,7 +424,7 @@ describe('Test abuses', function () { it('Should have 1 comment abuse on server 1 and 0 on server 2', async function () { { - const comment = await getComment(servers[0], servers[0].video.id) + const comment = await getComment(servers[0], servers[0].store.video.id) const body = await commands[0].getAdminList({ filter: 'comment' }) expect(body.total).to.equal(1) @@ -442,8 +442,8 @@ describe('Test abuses', function () { expect(abuse.comment.id).to.equal(comment.id) expect(abuse.comment.text).to.equal(comment.text) expect(abuse.comment.video.name).to.equal('server 1') - expect(abuse.comment.video.id).to.equal(servers[0].video.id) - expect(abuse.comment.video.uuid).to.equal(servers[0].video.uuid) + expect(abuse.comment.video.id).to.equal(servers[0].store.video.id) + expect(abuse.comment.video.uuid).to.equal(servers[0].store.video.uuid) expect(abuse.countReportsForReporter).to.equal(5) expect(abuse.countReportsForReportee).to.equal(5) @@ -459,7 +459,7 @@ describe('Test abuses', function () { it('Should report abuse on a remote comment', async function () { this.timeout(10000) - const comment = await getComment(servers[0], servers[1].video.uuid) + const comment = await getComment(servers[0], servers[1].store.video.uuid) const reason = 'it is a really bad comment' await commands[0].report({ commentId: comment.id, reason }) @@ -468,7 +468,7 @@ describe('Test abuses', function () { }) it('Should have 2 comment abuses on server 1 and 1 on server 2', async function () { - const commentServer2 = await getComment(servers[0], servers[1].video.id) + const commentServer2 = await getComment(servers[0], servers[1].store.video.id) { const body = await commands[0].getAdminList({ filter: 'comment' }) @@ -493,7 +493,7 @@ describe('Test abuses', function () { expect(abuse2.comment.id).to.equal(commentServer2.id) expect(abuse2.comment.text).to.equal(commentServer2.text) expect(abuse2.comment.video.name).to.equal('server 2') - expect(abuse2.comment.video.uuid).to.equal(servers[1].video.uuid) + expect(abuse2.comment.video.uuid).to.equal(servers[1].store.video.uuid) expect(abuse2.state.id).to.equal(AbuseState.PENDING) expect(abuse2.state.label).to.equal('Pending') @@ -527,9 +527,9 @@ describe('Test abuses', function () { it('Should keep the comment abuse when deleting the comment', async function () { this.timeout(10000) - const commentServer2 = await getComment(servers[0], servers[1].video.id) + const commentServer2 = await getComment(servers[0], servers[1].store.video.id) - await servers[0].commentsCommand.delete({ videoId: servers[1].video.uuid, commentId: commentServer2.id }) + await servers[0].comments.delete({ videoId: servers[1].store.video.uuid, commentId: commentServer2.id }) await waitJobs(servers) @@ -592,16 +592,16 @@ describe('Test abuses', function () { describe('Account abuses', function () { function getAccountFromServer (server: ServerInfo, targetName: string, targetServer: ServerInfo) { - return server.accountsCommand.get({ accountName: targetName + '@' + targetServer.host }) + return server.accounts.get({ accountName: targetName + '@' + targetServer.host }) } before(async function () { this.timeout(50000) - await servers[0].usersCommand.create({ username: 'user_1', password: 'donald' }) + await servers[0].users.create({ username: 'user_1', password: 'donald' }) - const token = await servers[1].usersCommand.generateUserAndToken('user_2') - await servers[1].videosCommand.upload({ token, attributes: { name: 'super video' } }) + const token = await servers[1].users.generateUserAndToken('user_2') + await servers[1].videos.upload({ token, attributes: { name: 'super video' } }) await waitJobs(servers) }) @@ -702,7 +702,7 @@ describe('Test abuses', function () { this.timeout(10000) const account = await getAccountFromServer(servers[1], 'user_2', servers[1]) - await servers[1].usersCommand.remove({ userId: account.userId }) + await servers[1].users.remove({ userId: account.userId }) await waitJobs(servers) @@ -759,11 +759,11 @@ describe('Test abuses', function () { let userAccessToken: string before(async function () { - userAccessToken = await servers[0].usersCommand.generateUserAndToken('user_42') + userAccessToken = await servers[0].users.generateUserAndToken('user_42') - await commands[0].report({ token: userAccessToken, videoId: servers[0].video.id, reason: 'user reason 1' }) + await commands[0].report({ token: userAccessToken, videoId: servers[0].store.video.id, reason: 'user reason 1' }) - const videoId = await servers[0].videosCommand.getId({ uuid: servers[1].video.uuid }) + const videoId = await servers[0].videos.getId({ uuid: servers[1].store.video.uuid }) await commands[0].report({ token: userAccessToken, videoId, reason: 'user reason 2' }) }) @@ -830,9 +830,9 @@ describe('Test abuses', function () { let abuseMessageModerationId: number before(async function () { - userToken = await servers[0].usersCommand.generateUserAndToken('user_43') + userToken = await servers[0].users.generateUserAndToken('user_43') - const body = await commands[0].report({ token: userToken, videoId: servers[0].video.id, reason: 'user 43 reason 1' }) + const body = await commands[0].report({ token: userToken, videoId: servers[0].store.video.id, reason: 'user 43 reason 1' }) abuseId = body.abuse.id }) diff --git a/server/tests/api/moderation/blocklist-notification.ts b/server/tests/api/moderation/blocklist-notification.ts index 92a0ec681..6b56fdd65 100644 --- a/server/tests/api/moderation/blocklist-notification.ts +++ b/server/tests/api/moderation/blocklist-notification.ts @@ -8,7 +8,7 @@ import { UserNotificationType } from '@shared/models' const expect = chai.expect async function checkNotifications (server: ServerInfo, token: string, expected: UserNotificationType[]) { - const { data } = await server.notificationsCommand.list({ token, start: 0, count: 10, unread: true }) + const { data } = await server.notifications.list({ token, start: 0, count: 10, unread: true }) expect(data).to.have.lengthOf(expected.length) for (const type of expected) { @@ -26,24 +26,24 @@ describe('Test blocklist', function () { async function resetState () { try { - await servers[1].subscriptionsCommand.remove({ token: remoteUserToken, uri: 'user1_channel@' + servers[0].host }) - await servers[1].subscriptionsCommand.remove({ token: remoteUserToken, uri: 'user2_channel@' + servers[0].host }) + await servers[1].subscriptions.remove({ token: remoteUserToken, uri: 'user1_channel@' + servers[0].host }) + await servers[1].subscriptions.remove({ token: remoteUserToken, uri: 'user2_channel@' + servers[0].host }) } catch {} await waitJobs(servers) - await servers[0].notificationsCommand.markAsReadAll({ token: userToken1 }) - await servers[0].notificationsCommand.markAsReadAll({ token: userToken2 }) + await servers[0].notifications.markAsReadAll({ token: userToken1 }) + await servers[0].notifications.markAsReadAll({ token: userToken2 }) { - const { uuid } = await servers[0].videosCommand.upload({ token: userToken1, attributes: { name: 'video' } }) + const { uuid } = await servers[0].videos.upload({ token: userToken1, attributes: { name: 'video' } }) videoUUID = uuid await waitJobs(servers) } { - await servers[1].commentsCommand.createThread({ + await servers[1].comments.createThread({ token: remoteUserToken, videoId: videoUUID, text: '@user2@' + servers[0].host + ' hello' @@ -52,8 +52,8 @@ describe('Test blocklist', function () { { - await servers[1].subscriptionsCommand.add({ token: remoteUserToken, targetUri: 'user1_channel@' + servers[0].host }) - await servers[1].subscriptionsCommand.add({ token: remoteUserToken, targetUri: 'user2_channel@' + servers[0].host }) + await servers[1].subscriptions.add({ token: remoteUserToken, targetUri: 'user1_channel@' + servers[0].host }) + await servers[1].subscriptions.add({ token: remoteUserToken, targetUri: 'user2_channel@' + servers[0].host }) } await waitJobs(servers) @@ -67,29 +67,29 @@ describe('Test blocklist', function () { { const user = { username: 'user1', password: 'password' } - await servers[0].usersCommand.create({ + await servers[0].users.create({ username: user.username, password: user.password, videoQuota: -1, videoQuotaDaily: -1 }) - userToken1 = await servers[0].loginCommand.getAccessToken(user) - await servers[0].videosCommand.upload({ token: userToken1, attributes: { name: 'video user 1' } }) + userToken1 = await servers[0].login.getAccessToken(user) + await servers[0].videos.upload({ token: userToken1, attributes: { name: 'video user 1' } }) } { const user = { username: 'user2', password: 'password' } - await servers[0].usersCommand.create({ username: user.username, password: user.password }) + await servers[0].users.create({ username: user.username, password: user.password }) - userToken2 = await servers[0].loginCommand.getAccessToken(user) + userToken2 = await servers[0].login.getAccessToken(user) } { const user = { username: 'user3', password: 'password' } - await servers[1].usersCommand.create({ username: user.username, password: user.password }) + await servers[1].users.create({ username: user.username, password: user.password }) - remoteUserToken = await servers[1].loginCommand.getAccessToken(user) + remoteUserToken = await servers[1].login.getAccessToken(user) } await doubleFollow(servers[0], servers[1]) @@ -111,7 +111,7 @@ describe('Test blocklist', function () { it('Should block an account', async function () { this.timeout(10000) - await servers[0].blocklistCommand.addToMyBlocklist({ token: userToken1, account: 'user3@' + servers[1].host }) + await servers[0].blocklist.addToMyBlocklist({ token: userToken1, account: 'user3@' + servers[1].host }) await waitJobs(servers) }) @@ -124,7 +124,7 @@ describe('Test blocklist', function () { await checkNotifications(servers[0], userToken2, notifs) - await servers[0].blocklistCommand.removeFromMyBlocklist({ token: userToken1, account: 'user3@' + servers[1].host }) + await servers[0].blocklist.removeFromMyBlocklist({ token: userToken1, account: 'user3@' + servers[1].host }) }) }) @@ -144,7 +144,7 @@ describe('Test blocklist', function () { it('Should block an account', async function () { this.timeout(10000) - await servers[0].blocklistCommand.addToMyBlocklist({ token: userToken1, server: servers[1].host }) + await servers[0].blocklist.addToMyBlocklist({ token: userToken1, server: servers[1].host }) await waitJobs(servers) }) @@ -157,7 +157,7 @@ describe('Test blocklist', function () { await checkNotifications(servers[0], userToken2, notifs) - await servers[0].blocklistCommand.removeFromMyBlocklist({ token: userToken1, server: servers[1].host }) + await servers[0].blocklist.removeFromMyBlocklist({ token: userToken1, server: servers[1].host }) }) }) @@ -184,7 +184,7 @@ describe('Test blocklist', function () { it('Should block an account', async function () { this.timeout(10000) - await servers[0].blocklistCommand.addToServerBlocklist({ account: 'user3@' + servers[1].host }) + await servers[0].blocklist.addToServerBlocklist({ account: 'user3@' + servers[1].host }) await waitJobs(servers) }) @@ -192,7 +192,7 @@ describe('Test blocklist', function () { await checkNotifications(servers[0], userToken1, []) await checkNotifications(servers[0], userToken2, []) - await servers[0].blocklistCommand.removeFromServerBlocklist({ account: 'user3@' + servers[1].host }) + await servers[0].blocklist.removeFromServerBlocklist({ account: 'user3@' + servers[1].host }) }) }) @@ -219,7 +219,7 @@ describe('Test blocklist', function () { it('Should block an account', async function () { this.timeout(10000) - await servers[0].blocklistCommand.addToServerBlocklist({ server: servers[1].host }) + await servers[0].blocklist.addToServerBlocklist({ server: servers[1].host }) await waitJobs(servers) }) diff --git a/server/tests/api/moderation/blocklist.ts b/server/tests/api/moderation/blocklist.ts index 3c3b2d6fd..9a4a3b3b9 100644 --- a/server/tests/api/moderation/blocklist.ts +++ b/server/tests/api/moderation/blocklist.ts @@ -18,24 +18,24 @@ const expect = chai.expect async function checkAllVideos (server: ServerInfo, token: string) { { - const { data } = await server.videosCommand.listWithToken({ token }) + const { data } = await server.videos.listWithToken({ token }) expect(data).to.have.lengthOf(5) } { - const { data } = await server.videosCommand.list() + const { data } = await server.videos.list() expect(data).to.have.lengthOf(5) } } async function checkAllComments (server: ServerInfo, token: string, videoUUID: string) { - const { data } = await server.commentsCommand.listThreads({ videoId: videoUUID, start: 0, count: 25, sort: '-createdAt', token }) + const { data } = await server.comments.listThreads({ videoId: videoUUID, start: 0, count: 25, sort: '-createdAt', token }) const threads = data.filter(t => t.isDeleted === false) expect(threads).to.have.lengthOf(2) for (const thread of threads) { - const tree = await server.commentsCommand.getThread({ videoId: videoUUID, threadId: thread.id, token }) + const tree = await server.comments.getThread({ videoId: videoUUID, threadId: thread.id, token }) expect(tree.children).to.have.lengthOf(1) } } @@ -45,13 +45,13 @@ async function checkCommentNotification ( comment: { server: ServerInfo, token: string, videoUUID: string, text: string }, check: 'presence' | 'absence' ) { - const command = comment.server.commentsCommand + const command = comment.server.comments const { threadId, createdAt } = await command.createThread({ token: comment.token, videoId: comment.videoUUID, text: comment.text }) await waitJobs([ mainServer, comment.server ]) - const { data } = await mainServer.notificationsCommand.list({ start: 0, count: 30 }) + const { data } = await mainServer.notifications.list({ start: 0, count: 30 }) const commentNotifications = data.filter(n => n.comment && n.comment.video.uuid === comment.videoUUID && n.createdAt >= createdAt) if (check === 'presence') expect(commentNotifications).to.have.lengthOf(1) @@ -80,44 +80,44 @@ describe('Test blocklist', function () { servers = await flushAndRunMultipleServers(3) await setAccessTokensToServers(servers) - command = servers[0].blocklistCommand - commentsCommand = servers.map(s => s.commentsCommand) + command = servers[0].blocklist + commentsCommand = servers.map(s => s.comments) { const user = { username: 'user1', password: 'password' } - await servers[0].usersCommand.create({ username: user.username, password: user.password }) + await servers[0].users.create({ username: user.username, password: user.password }) - userToken1 = await servers[0].loginCommand.getAccessToken(user) - await servers[0].videosCommand.upload({ token: userToken1, attributes: { name: 'video user 1' } }) + userToken1 = await servers[0].login.getAccessToken(user) + await servers[0].videos.upload({ token: userToken1, attributes: { name: 'video user 1' } }) } { const user = { username: 'moderator', password: 'password' } - await servers[0].usersCommand.create({ username: user.username, password: user.password }) + await servers[0].users.create({ username: user.username, password: user.password }) - userModeratorToken = await servers[0].loginCommand.getAccessToken(user) + userModeratorToken = await servers[0].login.getAccessToken(user) } { const user = { username: 'user2', password: 'password' } - await servers[1].usersCommand.create({ username: user.username, password: user.password }) + await servers[1].users.create({ username: user.username, password: user.password }) - userToken2 = await servers[1].loginCommand.getAccessToken(user) - await servers[1].videosCommand.upload({ token: userToken2, attributes: { name: 'video user 2' } }) + userToken2 = await servers[1].login.getAccessToken(user) + await servers[1].videos.upload({ token: userToken2, attributes: { name: 'video user 2' } }) } { - const { uuid } = await servers[0].videosCommand.upload({ attributes: { name: 'video server 1' } }) + const { uuid } = await servers[0].videos.upload({ attributes: { name: 'video server 1' } }) videoUUID1 = uuid } { - const { uuid } = await servers[1].videosCommand.upload({ attributes: { name: 'video server 2' } }) + const { uuid } = await servers[1].videos.upload({ attributes: { name: 'video server 2' } }) videoUUID2 = uuid } { - const { uuid } = await servers[0].videosCommand.upload({ attributes: { name: 'video 2 server 1' } }) + const { uuid } = await servers[0].videos.upload({ attributes: { name: 'video 2 server 1' } }) videoUUID3 = uuid } @@ -159,7 +159,7 @@ describe('Test blocklist', function () { }) it('Should hide its videos', async function () { - const { data } = await servers[0].videosCommand.listWithToken() + const { data } = await servers[0].videos.listWithToken() expect(data).to.have.lengthOf(4) @@ -172,7 +172,7 @@ describe('Test blocklist', function () { }) it('Should hide its videos', async function () { - const { data } = await servers[0].videosCommand.listWithToken() + const { data } = await servers[0].videos.listWithToken() expect(data).to.have.lengthOf(3) @@ -289,12 +289,12 @@ describe('Test blocklist', function () { // Server 1 and 3 should only have uploader comments for (const server of [ servers[0], servers[2] ]) { - const { data } = await server.commentsCommand.listThreads({ videoId: videoUUID3, count: 25, sort: '-createdAt' }) + const { data } = await server.comments.listThreads({ videoId: videoUUID3, count: 25, sort: '-createdAt' }) expect(data).to.have.lengthOf(1) expect(data[0].text).to.equal('uploader') - const tree = await server.commentsCommand.getThread({ videoId: videoUUID3, threadId: data[0].id }) + const tree = await server.comments.getThread({ videoId: videoUUID3, threadId: data[0].id }) if (server.serverNumber === 1) expect(tree.children).to.have.lengthOf(0) else expect(tree.children).to.have.lengthOf(1) @@ -306,7 +306,7 @@ describe('Test blocklist', function () { }) it('Should display its videos', async function () { - const { data } = await servers[0].videosCommand.listWithToken() + const { data } = await servers[0].videos.listWithToken() expect(data).to.have.lengthOf(4) const v = data.find(v => v.name === 'video user 2') @@ -315,7 +315,7 @@ describe('Test blocklist', function () { it('Should display its comments on my video', async function () { for (const server of servers) { - const { data } = await server.commentsCommand.listThreads({ videoId: videoUUID3, count: 25, sort: '-createdAt' }) + const { data } = await server.comments.listThreads({ videoId: videoUUID3, count: 25, sort: '-createdAt' }) // Server 3 should not have 2 comment threads, because server 1 did not forward the server 2 comment if (server.serverNumber === 3) { @@ -327,7 +327,7 @@ describe('Test blocklist', function () { expect(data[0].text).to.equal('uploader') expect(data[1].text).to.equal('comment user 2') - const tree = await server.commentsCommand.getThread({ videoId: videoUUID3, threadId: data[0].id }) + const tree = await server.comments.getThread({ videoId: videoUUID3, threadId: data[0].id }) expect(tree.children).to.have.lengthOf(1) expect(tree.children[0].comment.text).to.equal('reply by user 2') expect(tree.children[0].children).to.have.lengthOf(1) @@ -378,7 +378,7 @@ describe('Test blocklist', function () { }) it('Should hide its videos', async function () { - const { data } = await servers[0].videosCommand.listWithToken() + const { data } = await servers[0].videos.listWithToken() expect(data).to.have.lengthOf(3) @@ -488,7 +488,7 @@ describe('Test blocklist', function () { it('Should hide its videos', async function () { for (const token of [ userModeratorToken, servers[0].accessToken ]) { - const { data } = await servers[0].videosCommand.listWithToken({ token }) + const { data } = await servers[0].videos.listWithToken({ token }) expect(data).to.have.lengthOf(4) @@ -503,7 +503,7 @@ describe('Test blocklist', function () { it('Should hide its videos', async function () { for (const token of [ userModeratorToken, servers[0].accessToken ]) { - const { data } = await servers[0].videosCommand.listWithToken({ token }) + const { data } = await servers[0].videos.listWithToken({ token }) expect(data).to.have.lengthOf(3) @@ -581,7 +581,7 @@ describe('Test blocklist', function () { it('Should display its videos', async function () { for (const token of [ userModeratorToken, servers[0].accessToken ]) { - const { data } = await servers[0].videosCommand.listWithToken({ token }) + const { data } = await servers[0].videos.listWithToken({ token }) expect(data).to.have.lengthOf(4) const v = data.find(v => v.name === 'video user 2') @@ -639,8 +639,8 @@ describe('Test blocklist', function () { it('Should hide its videos', async function () { for (const token of [ userModeratorToken, servers[0].accessToken ]) { const requests = [ - servers[0].videosCommand.list(), - servers[0].videosCommand.listWithToken({ token }) + servers[0].videos.list(), + servers[0].videos.listWithToken({ token }) ] for (const req of requests) { @@ -688,13 +688,13 @@ describe('Test blocklist', function () { { const now = new Date() - await servers[1].followsCommand.unfollow({ target: servers[0] }) + await servers[1].follows.unfollow({ target: servers[0] }) await waitJobs(servers) - await servers[1].followsCommand.follow({ targets: [ servers[0].host ] }) + await servers[1].follows.follow({ targets: [ servers[0].host ] }) await waitJobs(servers) - const { data } = await servers[0].notificationsCommand.list({ start: 0, count: 30 }) + const { data } = await servers[0].notifications.list({ start: 0, count: 30 }) const commentNotifications = data.filter(n => { return n.type === UserNotificationType.NEW_INSTANCE_FOLLOWER && n.createdAt >= now.toISOString() }) @@ -749,13 +749,13 @@ describe('Test blocklist', function () { { const now = new Date() - await servers[1].followsCommand.unfollow({ target: servers[0] }) + await servers[1].follows.unfollow({ target: servers[0] }) await waitJobs(servers) - await servers[1].followsCommand.follow({ targets: [ servers[0].host ] }) + await servers[1].follows.follow({ targets: [ servers[0].host ] }) await waitJobs(servers) - const { data } = await servers[0].notificationsCommand.list({ start: 0, count: 30 }) + const { data } = await servers[0].notifications.list({ start: 0, count: 30 }) const commentNotifications = data.filter(n => { return n.type === UserNotificationType.NEW_INSTANCE_FOLLOWER && n.createdAt >= now.toISOString() }) diff --git a/server/tests/api/moderation/video-blacklist.ts b/server/tests/api/moderation/video-blacklist.ts index 2f2e678e7..d23d23bcb 100644 --- a/server/tests/api/moderation/video-blacklist.ts +++ b/server/tests/api/moderation/video-blacklist.ts @@ -25,10 +25,10 @@ describe('Test video blacklist', function () { let command: BlacklistCommand async function blacklistVideosOnServer (server: ServerInfo) { - const { data } = await server.videosCommand.list() + const { data } = await server.videos.list() for (const video of data) { - await server.blacklistCommand.add({ videoId: video.id, reason: 'super reason' }) + await server.blacklist.add({ videoId: video.id, reason: 'super reason' }) } } @@ -45,13 +45,13 @@ describe('Test video blacklist', function () { await doubleFollow(servers[0], servers[1]) // Upload 2 videos on server 2 - await servers[1].videosCommand.upload({ attributes: { name: 'My 1st video', description: 'A video on server 2' } }) - await servers[1].videosCommand.upload({ attributes: { name: 'My 2nd video', description: 'A video on server 2' } }) + await servers[1].videos.upload({ attributes: { name: 'My 1st video', description: 'A video on server 2' } }) + await servers[1].videos.upload({ attributes: { name: 'My 2nd video', description: 'A video on server 2' } }) // Wait videos propagation, server 2 has transcoding enabled await waitJobs(servers) - command = servers[0].blacklistCommand + command = servers[0].blacklist // Blacklist the two videos on server 1 await blacklistVideosOnServer(servers[0]) @@ -61,7 +61,7 @@ describe('Test video blacklist', function () { it('Should not have the video blacklisted in videos list/search on server 1', async function () { { - const { total, data } = await servers[0].videosCommand.list() + const { total, data } = await servers[0].videos.list() expect(total).to.equal(0) expect(data).to.be.an('array') @@ -69,7 +69,7 @@ describe('Test video blacklist', function () { } { - const body = await servers[0].searchCommand.searchVideos({ search: 'video' }) + const body = await servers[0].search.searchVideos({ search: 'video' }) expect(body.total).to.equal(0) expect(body.data).to.be.an('array') @@ -79,7 +79,7 @@ describe('Test video blacklist', function () { it('Should have the blacklisted video in videos list/search on server 2', async function () { { - const { total, data } = await servers[1].videosCommand.list() + const { total, data } = await servers[1].videos.list() expect(total).to.equal(2) expect(data).to.be.an('array') @@ -87,7 +87,7 @@ describe('Test video blacklist', function () { } { - const body = await servers[1].searchCommand.searchVideos({ search: 'video' }) + const body = await servers[1].search.searchVideos({ search: 'video' }) expect(body.total).to.equal(2) expect(body.data).to.be.an('array') @@ -181,7 +181,7 @@ describe('Test video blacklist', function () { it('Should display blacklisted videos', async function () { await blacklistVideosOnServer(servers[1]) - const { total, data } = await servers[1].videosCommand.listMyVideos() + const { total, data } = await servers[1].videos.listMyVideos() expect(total).to.equal(2) expect(data).to.have.lengthOf(2) @@ -198,7 +198,7 @@ describe('Test video blacklist', function () { let blacklist = [] it('Should not have any video in videos list on server 1', async function () { - const { total, data } = await servers[0].videosCommand.list() + const { total, data } = await servers[0].videos.list() expect(total).to.equal(0) expect(data).to.be.an('array') expect(data.length).to.equal(0) @@ -215,7 +215,7 @@ describe('Test video blacklist', function () { }) it('Should have the ex-blacklisted video in videos list on server 1', async function () { - const { total, data } = await servers[0].videosCommand.list() + const { total, data } = await servers[0].videos.list() expect(total).to.equal(1) expect(data).to.be.an('array') @@ -244,11 +244,11 @@ describe('Test video blacklist', function () { this.timeout(10000) { - const { uuid } = await servers[0].videosCommand.upload({ attributes: { name: 'Video 3' } }) + const { uuid } = await servers[0].videos.upload({ attributes: { name: 'Video 3' } }) video3UUID = uuid } { - const { uuid } = await servers[0].videosCommand.upload({ attributes: { name: 'Video 4' } }) + const { uuid } = await servers[0].videos.upload({ attributes: { name: 'Video 4' } }) video4UUID = uuid } @@ -263,12 +263,12 @@ describe('Test video blacklist', function () { await waitJobs(servers) { - const { data } = await servers[0].videosCommand.list() + const { data } = await servers[0].videos.list() expect(data.find(v => v.uuid === video3UUID)).to.be.undefined } { - const { data } = await servers[1].videosCommand.list() + const { data } = await servers[1].videos.list() expect(data.find(v => v.uuid === video3UUID)).to.not.be.undefined } }) @@ -281,7 +281,7 @@ describe('Test video blacklist', function () { await waitJobs(servers) for (const server of servers) { - const { data } = await server.videosCommand.list() + const { data } = await server.videos.list() expect(data.find(v => v.uuid === video4UUID)).to.be.undefined } }) @@ -289,12 +289,12 @@ describe('Test video blacklist', function () { it('Should have the video unfederated even after an Update AP message', async function () { this.timeout(10000) - await servers[0].videosCommand.update({ id: video4UUID, attributes: { description: 'super description' } }) + await servers[0].videos.update({ id: video4UUID, attributes: { description: 'super description' } }) await waitJobs(servers) for (const server of servers) { - const { data } = await server.videosCommand.list() + const { data } = await server.videos.list() expect(data.find(v => v.uuid === video4UUID)).to.be.undefined } }) @@ -318,7 +318,7 @@ describe('Test video blacklist', function () { await waitJobs(servers) for (const server of servers) { - const { data } = await server.videosCommand.list() + const { data } = await server.videos.list() expect(data.find(v => v.uuid === video4UUID)).to.not.be.undefined } }) @@ -348,36 +348,36 @@ describe('Test video blacklist', function () { { const user = { username: 'user_without_flag', password: 'password' } - await servers[0].usersCommand.create({ + await servers[0].users.create({ username: user.username, adminFlags: UserAdminFlag.NONE, password: user.password, role: UserRole.USER }) - userWithoutFlag = await servers[0].loginCommand.getAccessToken(user) + userWithoutFlag = await servers[0].login.getAccessToken(user) - const { videoChannels } = await servers[0].usersCommand.getMyInfo({ token: userWithoutFlag }) + const { videoChannels } = await servers[0].users.getMyInfo({ token: userWithoutFlag }) channelOfUserWithoutFlag = videoChannels[0].id } { const user = { username: 'user_with_flag', password: 'password' } - await servers[0].usersCommand.create({ + await servers[0].users.create({ username: user.username, adminFlags: UserAdminFlag.BYPASS_VIDEO_AUTO_BLACKLIST, password: user.password, role: UserRole.USER }) - userWithFlag = await servers[0].loginCommand.getAccessToken(user) + userWithFlag = await servers[0].login.getAccessToken(user) } await waitJobs(servers) }) it('Should auto blacklist a video on upload', async function () { - await servers[0].videosCommand.upload({ token: userWithoutFlag, attributes: { name: 'blacklisted' } }) + await servers[0].videos.upload({ token: userWithoutFlag, attributes: { name: 'blacklisted' } }) const body = await command.list({ type: VideoBlacklistType.AUTO_BEFORE_PUBLISHED }) expect(body.total).to.equal(1) @@ -392,7 +392,7 @@ describe('Test video blacklist', function () { name: 'URL import', channelId: channelOfUserWithoutFlag } - await servers[0].importsCommand.importVideo({ token: userWithoutFlag, attributes }) + await servers[0].imports.importVideo({ token: userWithoutFlag, attributes }) const body = await command.list({ sort: 'createdAt', type: VideoBlacklistType.AUTO_BEFORE_PUBLISHED }) expect(body.total).to.equal(2) @@ -405,7 +405,7 @@ describe('Test video blacklist', function () { name: 'Torrent import', channelId: channelOfUserWithoutFlag } - await servers[0].importsCommand.importVideo({ token: userWithoutFlag, attributes }) + await servers[0].imports.importVideo({ token: userWithoutFlag, attributes }) const body = await command.list({ sort: 'createdAt', type: VideoBlacklistType.AUTO_BEFORE_PUBLISHED }) expect(body.total).to.equal(3) @@ -413,7 +413,7 @@ describe('Test video blacklist', function () { }) it('Should not auto blacklist a video on upload if the user has the bypass blacklist flag', async function () { - await servers[0].videosCommand.upload({ token: userWithFlag, attributes: { name: 'not blacklisted' } }) + await servers[0].videos.upload({ token: userWithFlag, attributes: { name: 'not blacklisted' } }) const body = await command.list({ type: VideoBlacklistType.AUTO_BEFORE_PUBLISHED }) expect(body.total).to.equal(3) diff --git a/server/tests/api/notifications/admin-notifications.ts b/server/tests/api/notifications/admin-notifications.ts index 03fbe0b70..5a5bdb0c8 100644 --- a/server/tests/api/notifications/admin-notifications.ts +++ b/server/tests/api/notifications/admin-notifications.ts @@ -58,8 +58,8 @@ describe('Test admin notifications', function () { token: server.accessToken } - await server.pluginsCommand.install({ npmName: 'peertube-plugin-hello-world' }) - await server.pluginsCommand.install({ npmName: 'peertube-theme-background-red' }) + await server.plugins.install({ npmName: 'peertube-plugin-hello-world' }) + await server.plugins.install({ npmName: 'peertube-theme-background-red' }) }) describe('Latest PeerTube version notification', function () { @@ -118,8 +118,8 @@ describe('Test admin notifications', function () { it('Should send a notification to admins on new plugin version', async function () { this.timeout(30000) - await server.sqlCommand.setPluginVersion('hello-world', '0.0.1') - await server.sqlCommand.setPluginLatestVersion('hello-world', '0.0.1') + await server.sql.setPluginVersion('hello-world', '0.0.1') + await server.sql.setPluginLatestVersion('hello-world', '0.0.1') await wait(6000) await checkNewPluginVersion(baseParams, PluginType.PLUGIN, 'hello-world', 'presence') @@ -140,8 +140,8 @@ describe('Test admin notifications', function () { it('Should send a new notification after a new plugin release', async function () { this.timeout(30000) - await server.sqlCommand.setPluginVersion('hello-world', '0.0.1') - await server.sqlCommand.setPluginLatestVersion('hello-world', '0.0.1') + await server.sql.setPluginVersion('hello-world', '0.0.1') + await server.sql.setPluginLatestVersion('hello-world', '0.0.1') await wait(6000) expect(adminNotifications.filter(n => n.type === UserNotificationType.NEW_PEERTUBE_VERSION)).to.have.lengthOf(2) diff --git a/server/tests/api/notifications/comments-notifications.ts b/server/tests/api/notifications/comments-notifications.ts index a74b38e8a..133b6340f 100644 --- a/server/tests/api/notifications/comments-notifications.ts +++ b/server/tests/api/notifications/comments-notifications.ts @@ -52,9 +52,9 @@ describe('Test comments notifications', function () { it('Should not send a new comment notification after a comment on another video', async function () { this.timeout(20000) - const { uuid } = await servers[0].videosCommand.upload({ attributes: { name: 'super video' } }) + const { uuid } = await servers[0].videos.upload({ attributes: { name: 'super video' } }) - const created = await servers[0].commentsCommand.createThread({ videoId: uuid, text: 'comment' }) + const created = await servers[0].comments.createThread({ videoId: uuid, text: 'comment' }) const commentId = created.id await waitJobs(servers) @@ -64,9 +64,9 @@ describe('Test comments notifications', function () { it('Should not send a new comment notification if I comment my own video', async function () { this.timeout(20000) - const { uuid } = await servers[0].videosCommand.upload({ token: userToken, attributes: { name: 'super video' } }) + const { uuid } = await servers[0].videos.upload({ token: userToken, attributes: { name: 'super video' } }) - const created = await servers[0].commentsCommand.createThread({ token: userToken, videoId: uuid, text: 'comment' }) + const created = await servers[0].comments.createThread({ token: userToken, videoId: uuid, text: 'comment' }) const commentId = created.id await waitJobs(servers) @@ -76,25 +76,25 @@ describe('Test comments notifications', function () { it('Should not send a new comment notification if the account is muted', async function () { this.timeout(20000) - await servers[0].blocklistCommand.addToMyBlocklist({ token: userToken, account: 'root' }) + await servers[0].blocklist.addToMyBlocklist({ token: userToken, account: 'root' }) - const { uuid } = await servers[0].videosCommand.upload({ token: userToken, attributes: { name: 'super video' } }) + const { uuid } = await servers[0].videos.upload({ token: userToken, attributes: { name: 'super video' } }) - const created = await servers[0].commentsCommand.createThread({ videoId: uuid, text: 'comment' }) + const created = await servers[0].comments.createThread({ videoId: uuid, text: 'comment' }) const commentId = created.id await waitJobs(servers) await checkNewCommentOnMyVideo(baseParams, uuid, commentId, commentId, 'absence') - await servers[0].blocklistCommand.removeFromMyBlocklist({ token: userToken, account: 'root' }) + await servers[0].blocklist.removeFromMyBlocklist({ token: userToken, account: 'root' }) }) it('Should send a new comment notification after a local comment on my video', async function () { this.timeout(20000) - const { uuid } = await servers[0].videosCommand.upload({ token: userToken, attributes: { name: 'super video' } }) + const { uuid } = await servers[0].videos.upload({ token: userToken, attributes: { name: 'super video' } }) - const created = await servers[0].commentsCommand.createThread({ videoId: uuid, text: 'comment' }) + const created = await servers[0].comments.createThread({ videoId: uuid, text: 'comment' }) const commentId = created.id await waitJobs(servers) @@ -104,15 +104,15 @@ describe('Test comments notifications', function () { it('Should send a new comment notification after a remote comment on my video', async function () { this.timeout(20000) - const { uuid } = await servers[0].videosCommand.upload({ token: userToken, attributes: { name: 'super video' } }) + const { uuid } = await servers[0].videos.upload({ token: userToken, attributes: { name: 'super video' } }) await waitJobs(servers) - await servers[1].commentsCommand.createThread({ videoId: uuid, text: 'comment' }) + await servers[1].comments.createThread({ videoId: uuid, text: 'comment' }) await waitJobs(servers) - const { data } = await servers[0].commentsCommand.listThreads({ videoId: uuid }) + const { data } = await servers[0].comments.listThreads({ videoId: uuid }) expect(data).to.have.lengthOf(1) const commentId = data[0].id @@ -122,11 +122,11 @@ describe('Test comments notifications', function () { it('Should send a new comment notification after a local reply on my video', async function () { this.timeout(20000) - const { uuid } = await servers[0].videosCommand.upload({ token: userToken, attributes: { name: 'super video' } }) + const { uuid } = await servers[0].videos.upload({ token: userToken, attributes: { name: 'super video' } }) - const { id: threadId } = await servers[0].commentsCommand.createThread({ videoId: uuid, text: 'comment' }) + const { id: threadId } = await servers[0].comments.createThread({ videoId: uuid, text: 'comment' }) - const { id: commentId } = await servers[0].commentsCommand.addReply({ videoId: uuid, toCommentId: threadId, text: 'reply' }) + const { id: commentId } = await servers[0].comments.addReply({ videoId: uuid, toCommentId: threadId, text: 'reply' }) await waitJobs(servers) await checkNewCommentOnMyVideo(baseParams, uuid, commentId, threadId, 'presence') @@ -135,22 +135,22 @@ describe('Test comments notifications', function () { it('Should send a new comment notification after a remote reply on my video', async function () { this.timeout(20000) - const { uuid } = await servers[0].videosCommand.upload({ token: userToken, attributes: { name: 'super video' } }) + const { uuid } = await servers[0].videos.upload({ token: userToken, attributes: { name: 'super video' } }) await waitJobs(servers) { - const created = await servers[1].commentsCommand.createThread({ videoId: uuid, text: 'comment' }) + const created = await servers[1].comments.createThread({ videoId: uuid, text: 'comment' }) const threadId = created.id - await servers[1].commentsCommand.addReply({ videoId: uuid, toCommentId: threadId, text: 'reply' }) + await servers[1].comments.addReply({ videoId: uuid, toCommentId: threadId, text: 'reply' }) } await waitJobs(servers) - const { data } = await servers[0].commentsCommand.listThreads({ videoId: uuid }) + const { data } = await servers[0].comments.listThreads({ videoId: uuid }) expect(data).to.have.lengthOf(1) const threadId = data[0].id - const tree = await servers[0].commentsCommand.getThread({ videoId: uuid, threadId }) + const tree = await servers[0].comments.getThread({ videoId: uuid, threadId }) expect(tree.children).to.have.lengthOf(1) const commentId = tree.children[0].comment.id @@ -161,9 +161,9 @@ describe('Test comments notifications', function () { it('Should convert markdown in comment to html', async function () { this.timeout(20000) - const { uuid } = await servers[0].videosCommand.upload({ token: userToken, attributes: { name: 'cool video' } }) + const { uuid } = await servers[0].videos.upload({ token: userToken, attributes: { name: 'cool video' } }) - await servers[0].commentsCommand.createThread({ videoId: uuid, text: commentText }) + await servers[0].comments.createThread({ videoId: uuid, text: commentText }) await waitJobs(servers) @@ -183,16 +183,16 @@ describe('Test comments notifications', function () { token: userToken } - await servers[0].usersCommand.updateMe({ displayName: 'super root name' }) - await servers[1].usersCommand.updateMe({ displayName: 'super root 2 name' }) + await servers[0].users.updateMe({ displayName: 'super root name' }) + await servers[1].users.updateMe({ displayName: 'super root 2 name' }) }) it('Should not send a new mention comment notification if I mention the video owner', async function () { this.timeout(10000) - const { uuid } = await servers[0].videosCommand.upload({ token: userToken, attributes: { name: 'super video' } }) + const { uuid } = await servers[0].videos.upload({ token: userToken, attributes: { name: 'super video' } }) - const { id: commentId } = await servers[0].commentsCommand.createThread({ videoId: uuid, text: '@user_1 hello' }) + const { id: commentId } = await servers[0].comments.createThread({ videoId: uuid, text: '@user_1 hello' }) await waitJobs(servers) await checkCommentMention(baseParams, uuid, commentId, commentId, 'super root name', 'absence') @@ -201,9 +201,9 @@ describe('Test comments notifications', function () { it('Should not send a new mention comment notification if I mention myself', async function () { this.timeout(10000) - const { uuid } = await servers[0].videosCommand.upload({ attributes: { name: 'super video' } }) + const { uuid } = await servers[0].videos.upload({ attributes: { name: 'super video' } }) - const { id: commentId } = await servers[0].commentsCommand.createThread({ token: userToken, videoId: uuid, text: '@user_1 hello' }) + const { id: commentId } = await servers[0].comments.createThread({ token: userToken, videoId: uuid, text: '@user_1 hello' }) await waitJobs(servers) await checkCommentMention(baseParams, uuid, commentId, commentId, 'super root name', 'absence') @@ -212,25 +212,25 @@ describe('Test comments notifications', function () { it('Should not send a new mention notification if the account is muted', async function () { this.timeout(10000) - await servers[0].blocklistCommand.addToMyBlocklist({ token: userToken, account: 'root' }) + await servers[0].blocklist.addToMyBlocklist({ token: userToken, account: 'root' }) - const { uuid } = await servers[0].videosCommand.upload({ attributes: { name: 'super video' } }) + const { uuid } = await servers[0].videos.upload({ attributes: { name: 'super video' } }) - const { id: commentId } = await servers[0].commentsCommand.createThread({ videoId: uuid, text: '@user_1 hello' }) + const { id: commentId } = await servers[0].comments.createThread({ videoId: uuid, text: '@user_1 hello' }) await waitJobs(servers) await checkCommentMention(baseParams, uuid, commentId, commentId, 'super root name', 'absence') - await servers[0].blocklistCommand.removeFromMyBlocklist({ token: userToken, account: 'root' }) + await servers[0].blocklist.removeFromMyBlocklist({ token: userToken, account: 'root' }) }) it('Should not send a new mention notification if the remote account mention a local account', async function () { this.timeout(20000) - const { uuid } = await servers[0].videosCommand.upload({ attributes: { name: 'super video' } }) + const { uuid } = await servers[0].videos.upload({ attributes: { name: 'super video' } }) await waitJobs(servers) - const { id: threadId } = await servers[1].commentsCommand.createThread({ videoId: uuid, text: '@user_1 hello' }) + const { id: threadId } = await servers[1].comments.createThread({ videoId: uuid, text: '@user_1 hello' }) await waitJobs(servers) await checkCommentMention(baseParams, uuid, threadId, threadId, 'super root 2 name', 'absence') @@ -239,14 +239,14 @@ describe('Test comments notifications', function () { it('Should send a new mention notification after local comments', async function () { this.timeout(10000) - const { uuid } = await servers[0].videosCommand.upload({ attributes: { name: 'super video' } }) + const { uuid } = await servers[0].videos.upload({ attributes: { name: 'super video' } }) - const { id: threadId } = await servers[0].commentsCommand.createThread({ videoId: uuid, text: '@user_1 hellotext: 1' }) + const { id: threadId } = await servers[0].comments.createThread({ videoId: uuid, text: '@user_1 hellotext: 1' }) await waitJobs(servers) await checkCommentMention(baseParams, uuid, threadId, threadId, 'super root name', 'presence') - const { id: commentId } = await servers[0].commentsCommand.addReply({ videoId: uuid, toCommentId: threadId, text: 'hello 2 @user_1' }) + const { id: commentId } = await servers[0].comments.addReply({ videoId: uuid, toCommentId: threadId, text: 'hello 2 @user_1' }) await waitJobs(servers) await checkCommentMention(baseParams, uuid, commentId, threadId, 'super root name', 'presence') @@ -255,27 +255,27 @@ describe('Test comments notifications', function () { it('Should send a new mention notification after remote comments', async function () { this.timeout(20000) - const { uuid } = await servers[0].videosCommand.upload({ attributes: { name: 'super video' } }) + const { uuid } = await servers[0].videos.upload({ attributes: { name: 'super video' } }) await waitJobs(servers) const text1 = `hello @user_1@localhost:${servers[0].port} 1` - const { id: server2ThreadId } = await servers[1].commentsCommand.createThread({ videoId: uuid, text: text1 }) + const { id: server2ThreadId } = await servers[1].comments.createThread({ videoId: uuid, text: text1 }) await waitJobs(servers) - const { data } = await servers[0].commentsCommand.listThreads({ videoId: uuid }) + const { data } = await servers[0].comments.listThreads({ videoId: uuid }) expect(data).to.have.lengthOf(1) const server1ThreadId = data[0].id await checkCommentMention(baseParams, uuid, server1ThreadId, server1ThreadId, 'super root 2 name', 'presence') const text2 = `@user_1@localhost:${servers[0].port} hello 2 @root@localhost:${servers[0].port}` - await servers[1].commentsCommand.addReply({ videoId: uuid, toCommentId: server2ThreadId, text: text2 }) + await servers[1].comments.addReply({ videoId: uuid, toCommentId: server2ThreadId, text: text2 }) await waitJobs(servers) - const tree = await servers[0].commentsCommand.getThread({ videoId: uuid, threadId: server1ThreadId }) + const tree = await servers[0].comments.getThread({ videoId: uuid, threadId: server1ThreadId }) expect(tree.children).to.have.lengthOf(1) const commentId = tree.children[0].comment.id @@ -286,11 +286,11 @@ describe('Test comments notifications', function () { it('Should convert markdown in comment to html', async function () { this.timeout(10000) - const { uuid } = await servers[0].videosCommand.upload({ attributes: { name: 'super video' } }) + const { uuid } = await servers[0].videos.upload({ attributes: { name: 'super video' } }) - const { id: threadId } = await servers[0].commentsCommand.createThread({ videoId: uuid, text: '@user_1 hello 1' }) + const { id: threadId } = await servers[0].comments.createThread({ videoId: uuid, text: '@user_1 hello 1' }) - await servers[0].commentsCommand.addReply({ videoId: uuid, toCommentId: threadId, text: '@user_1 ' + commentText }) + await servers[0].comments.addReply({ videoId: uuid, toCommentId: threadId, text: '@user_1 ' + commentText }) await waitJobs(servers) diff --git a/server/tests/api/notifications/moderation-notifications.ts b/server/tests/api/notifications/moderation-notifications.ts index 91a2b4fa5..e7c5badd2 100644 --- a/server/tests/api/notifications/moderation-notifications.ts +++ b/server/tests/api/notifications/moderation-notifications.ts @@ -62,9 +62,9 @@ describe('Test moderation notifications', function () { this.timeout(20000) const name = 'video for abuse ' + buildUUID() - const video = await servers[0].videosCommand.upload({ token: userAccessToken, attributes: { name } }) + const video = await servers[0].videos.upload({ token: userAccessToken, attributes: { name } }) - await servers[0].abusesCommand.report({ videoId: video.id, reason: 'super reason' }) + await servers[0].abuses.report({ videoId: video.id, reason: 'super reason' }) await waitJobs(servers) await checkNewVideoAbuseForModerators(baseParams, video.uuid, name, 'presence') @@ -74,12 +74,12 @@ describe('Test moderation notifications', function () { this.timeout(20000) const name = 'video for abuse ' + buildUUID() - const video = await servers[0].videosCommand.upload({ token: userAccessToken, attributes: { name } }) + const video = await servers[0].videos.upload({ token: userAccessToken, attributes: { name } }) await waitJobs(servers) - const videoId = await servers[1].videosCommand.getId({ uuid: video.uuid }) - await servers[1].abusesCommand.report({ videoId, reason: 'super reason' }) + const videoId = await servers[1].videos.getId({ uuid: video.uuid }) + await servers[1].abuses.report({ videoId, reason: 'super reason' }) await waitJobs(servers) await checkNewVideoAbuseForModerators(baseParams, video.uuid, name, 'presence') @@ -89,8 +89,8 @@ describe('Test moderation notifications', function () { this.timeout(20000) const name = 'video for abuse ' + buildUUID() - const video = await servers[0].videosCommand.upload({ token: userAccessToken, attributes: { name } }) - const comment = await servers[0].commentsCommand.createThread({ + const video = await servers[0].videos.upload({ token: userAccessToken, attributes: { name } }) + const comment = await servers[0].comments.createThread({ token: userAccessToken, videoId: video.id, text: 'comment abuse ' + buildUUID() @@ -98,7 +98,7 @@ describe('Test moderation notifications', function () { await waitJobs(servers) - await servers[0].abusesCommand.report({ commentId: comment.id, reason: 'super reason' }) + await servers[0].abuses.report({ commentId: comment.id, reason: 'super reason' }) await waitJobs(servers) await checkNewCommentAbuseForModerators(baseParams, video.uuid, name, 'presence') @@ -108,9 +108,9 @@ describe('Test moderation notifications', function () { this.timeout(20000) const name = 'video for abuse ' + buildUUID() - const video = await servers[0].videosCommand.upload({ token: userAccessToken, attributes: { name } }) + const video = await servers[0].videos.upload({ token: userAccessToken, attributes: { name } }) - await servers[0].commentsCommand.createThread({ + await servers[0].comments.createThread({ token: userAccessToken, videoId: video.id, text: 'comment abuse ' + buildUUID() @@ -118,9 +118,9 @@ describe('Test moderation notifications', function () { await waitJobs(servers) - const { data } = await servers[1].commentsCommand.listThreads({ videoId: video.uuid }) + const { data } = await servers[1].comments.listThreads({ videoId: video.uuid }) const commentId = data[0].id - await servers[1].abusesCommand.report({ commentId, reason: 'super reason' }) + await servers[1].abuses.report({ commentId, reason: 'super reason' }) await waitJobs(servers) await checkNewCommentAbuseForModerators(baseParams, video.uuid, name, 'presence') @@ -130,10 +130,10 @@ describe('Test moderation notifications', function () { this.timeout(20000) const username = 'user' + new Date().getTime() - const { account } = await servers[0].usersCommand.create({ username, password: 'donald' }) + const { account } = await servers[0].users.create({ username, password: 'donald' }) const accountId = account.id - await servers[0].abusesCommand.report({ accountId, reason: 'super reason' }) + await servers[0].abuses.report({ accountId, reason: 'super reason' }) await waitJobs(servers) await checkNewAccountAbuseForModerators(baseParams, username, 'presence') @@ -143,13 +143,13 @@ describe('Test moderation notifications', function () { this.timeout(20000) const username = 'user' + new Date().getTime() - const tmpToken = await servers[0].usersCommand.generateUserAndToken(username) - await servers[0].videosCommand.upload({ token: tmpToken, attributes: { name: 'super video' } }) + const tmpToken = await servers[0].users.generateUserAndToken(username) + await servers[0].videos.upload({ token: tmpToken, attributes: { name: 'super video' } }) await waitJobs(servers) - const account = await servers[1].accountsCommand.get({ accountName: username + '@' + servers[0].host }) - await servers[1].abusesCommand.report({ accountId: account.id, reason: 'super reason' }) + const account = await servers[1].accounts.get({ accountName: username + '@' + servers[0].host }) + await servers[1].abuses.report({ accountId: account.id, reason: 'super reason' }) await waitJobs(servers) await checkNewAccountAbuseForModerators(baseParams, username, 'presence') @@ -169,16 +169,16 @@ describe('Test moderation notifications', function () { } const name = 'abuse ' + buildUUID() - const video = await servers[0].videosCommand.upload({ token: userAccessToken, attributes: { name } }) + const video = await servers[0].videos.upload({ token: userAccessToken, attributes: { name } }) - const body = await servers[0].abusesCommand.report({ token: userAccessToken, videoId: video.id, reason: 'super reason' }) + const body = await servers[0].abuses.report({ token: userAccessToken, videoId: video.id, reason: 'super reason' }) abuseId = body.abuse.id }) it('Should send a notification to reporter if the abuse has been accepted', async function () { this.timeout(10000) - await servers[0].abusesCommand.update({ abuseId, body: { state: AbuseState.ACCEPTED } }) + await servers[0].abuses.update({ abuseId, body: { state: AbuseState.ACCEPTED } }) await waitJobs(servers) await checkAbuseStateChange(baseParams, abuseId, AbuseState.ACCEPTED, 'presence') @@ -187,7 +187,7 @@ describe('Test moderation notifications', function () { it('Should send a notification to reporter if the abuse has been rejected', async function () { this.timeout(10000) - await servers[0].abusesCommand.update({ abuseId, body: { state: AbuseState.REJECTED } }) + await servers[0].abuses.update({ abuseId, body: { state: AbuseState.REJECTED } }) await waitJobs(servers) await checkAbuseStateChange(baseParams, abuseId, AbuseState.REJECTED, 'presence') @@ -216,15 +216,15 @@ describe('Test moderation notifications', function () { } const name = 'abuse ' + buildUUID() - const video = await servers[0].videosCommand.upload({ token: userAccessToken, attributes: { name } }) + const video = await servers[0].videos.upload({ token: userAccessToken, attributes: { name } }) { - const body = await servers[0].abusesCommand.report({ token: userAccessToken, videoId: video.id, reason: 'super reason' }) + const body = await servers[0].abuses.report({ token: userAccessToken, videoId: video.id, reason: 'super reason' }) abuseId = body.abuse.id } { - const body = await servers[0].abusesCommand.report({ token: userAccessToken, videoId: video.id, reason: 'super reason 2' }) + const body = await servers[0].abuses.report({ token: userAccessToken, videoId: video.id, reason: 'super reason 2' }) abuseId2 = body.abuse.id } }) @@ -233,7 +233,7 @@ describe('Test moderation notifications', function () { this.timeout(10000) const message = 'my super message to users' - await servers[0].abusesCommand.addMessage({ abuseId, message }) + await servers[0].abuses.addMessage({ abuseId, message }) await waitJobs(servers) await checkNewAbuseMessage(baseParamsUser, abuseId, message, 'user_1@example.com', 'presence') @@ -243,7 +243,7 @@ describe('Test moderation notifications', function () { this.timeout(10000) const message = 'my super message that should not be sent to the admin' - await servers[0].abusesCommand.addMessage({ abuseId, message }) + await servers[0].abuses.addMessage({ abuseId, message }) await waitJobs(servers) await checkNewAbuseMessage(baseParamsAdmin, abuseId, message, 'admin' + servers[0].internalServerNumber + '@example.com', 'absence') @@ -253,7 +253,7 @@ describe('Test moderation notifications', function () { this.timeout(10000) const message = 'my super message to moderators' - await servers[0].abusesCommand.addMessage({ token: userAccessToken, abuseId: abuseId2, message }) + await servers[0].abuses.addMessage({ token: userAccessToken, abuseId: abuseId2, message }) await waitJobs(servers) await checkNewAbuseMessage(baseParamsAdmin, abuseId2, message, 'admin' + servers[0].internalServerNumber + '@example.com', 'presence') @@ -263,7 +263,7 @@ describe('Test moderation notifications', function () { this.timeout(10000) const message = 'my super message that should not be sent to reporter' - await servers[0].abusesCommand.addMessage({ token: userAccessToken, abuseId: abuseId2, message }) + await servers[0].abuses.addMessage({ token: userAccessToken, abuseId: abuseId2, message }) await waitJobs(servers) await checkNewAbuseMessage(baseParamsUser, abuseId2, message, 'user_1@example.com', 'absence') @@ -286,9 +286,9 @@ describe('Test moderation notifications', function () { this.timeout(10000) const name = 'video for abuse ' + buildUUID() - const { uuid } = await servers[0].videosCommand.upload({ token: userAccessToken, attributes: { name } }) + const { uuid } = await servers[0].videos.upload({ token: userAccessToken, attributes: { name } }) - await servers[0].blacklistCommand.add({ videoId: uuid }) + await servers[0].blacklist.add({ videoId: uuid }) await waitJobs(servers) await checkNewBlacklistOnMyVideo(baseParams, uuid, name, 'blacklist') @@ -298,12 +298,12 @@ describe('Test moderation notifications', function () { this.timeout(10000) const name = 'video for abuse ' + buildUUID() - const { uuid } = await servers[0].videosCommand.upload({ token: userAccessToken, attributes: { name } }) + const { uuid } = await servers[0].videos.upload({ token: userAccessToken, attributes: { name } }) - await servers[0].blacklistCommand.add({ videoId: uuid }) + await servers[0].blacklist.add({ videoId: uuid }) await waitJobs(servers) - await servers[0].blacklistCommand.remove({ videoId: uuid }) + await servers[0].blacklist.remove({ videoId: uuid }) await waitJobs(servers) await wait(500) @@ -326,7 +326,7 @@ describe('Test moderation notifications', function () { it('Should send a notification only to moderators when a user registers on the instance', async function () { this.timeout(10000) - await servers[0].usersCommand.register({ username: 'user_45' }) + await servers[0].users.register({ username: 'user_45' }) await waitJobs(servers) @@ -368,7 +368,7 @@ describe('Test moderation notifications', function () { it('Should send a notification only to admin when there is a new instance follower', async function () { this.timeout(20000) - await servers[2].followsCommand.follow({ targets: [ servers[0].url ] }) + await servers[2].follows.follow({ targets: [ servers[0].url ] }) await waitJobs(servers) @@ -381,7 +381,7 @@ describe('Test moderation notifications', function () { it('Should send a notification on auto follow back', async function () { this.timeout(40000) - await servers[2].followsCommand.unfollow({ target: servers[0] }) + await servers[2].follows.unfollow({ target: servers[0] }) await waitJobs(servers) const config = { @@ -391,9 +391,9 @@ describe('Test moderation notifications', function () { } } } - await servers[0].configCommand.updateCustomSubConfig({ newConfig: config }) + await servers[0].config.updateCustomSubConfig({ newConfig: config }) - await servers[2].followsCommand.follow({ targets: [ servers[0].url ] }) + await servers[2].follows.follow({ targets: [ servers[0].url ] }) await waitJobs(servers) @@ -405,16 +405,16 @@ describe('Test moderation notifications', function () { await checkAutoInstanceFollowing({ ...baseParams, ...userOverride }, followerHost, followingHost, 'absence') config.followings.instance.autoFollowBack.enabled = false - await servers[0].configCommand.updateCustomSubConfig({ newConfig: config }) - await servers[0].followsCommand.unfollow({ target: servers[2] }) - await servers[2].followsCommand.unfollow({ target: servers[0] }) + await servers[0].config.updateCustomSubConfig({ newConfig: config }) + await servers[0].follows.unfollow({ target: servers[2] }) + await servers[2].follows.unfollow({ target: servers[0] }) }) it('Should send a notification on auto instances index follow', async function () { this.timeout(30000) - await servers[0].followsCommand.unfollow({ target: servers[1] }) + await servers[0].follows.unfollow({ target: servers[1] }) - await servers[0].configCommand.updateCustomSubConfig({ newConfig: config }) + await servers[0].config.updateCustomSubConfig({ newConfig: config }) await wait(5000) await waitJobs(servers) @@ -424,8 +424,8 @@ describe('Test moderation notifications', function () { await checkAutoInstanceFollowing(baseParams, followerHost, followingHost, 'presence') config.followings.instance.autoFollowIndex.enabled = false - await servers[0].configCommand.updateCustomSubConfig({ newConfig: config }) - await servers[0].followsCommand.unfollow({ target: servers[1] }) + await servers[0].config.updateCustomSubConfig({ newConfig: config }) + await servers[0].follows.unfollow({ target: servers[1] }) }) }) @@ -460,7 +460,7 @@ describe('Test moderation notifications', function () { token: userAccessToken } - currentCustomConfig = await servers[0].configCommand.getCustomConfig() + currentCustomConfig = await servers[0].config.getCustomConfig() const autoBlacklistTestsCustomConfig = { ...currentCustomConfig, @@ -476,10 +476,10 @@ describe('Test moderation notifications', function () { // enable transcoding otherwise own publish notification after transcoding not expected autoBlacklistTestsCustomConfig.transcoding.enabled = true - await servers[0].configCommand.updateCustomConfig({ newCustomConfig: autoBlacklistTestsCustomConfig }) + await servers[0].config.updateCustomConfig({ newCustomConfig: autoBlacklistTestsCustomConfig }) - await servers[0].subscriptionsCommand.add({ targetUri: 'user_1_channel@localhost:' + servers[0].port }) - await servers[1].subscriptionsCommand.add({ targetUri: 'user_1_channel@localhost:' + servers[0].port }) + await servers[0].subscriptions.add({ targetUri: 'user_1_channel@localhost:' + servers[0].port }) + await servers[1].subscriptions.add({ targetUri: 'user_1_channel@localhost:' + servers[0].port }) }) @@ -487,7 +487,7 @@ describe('Test moderation notifications', function () { this.timeout(40000) videoName = 'video with auto-blacklist ' + buildUUID() - const { uuid } = await servers[0].videosCommand.upload({ token: userAccessToken, attributes: { name: videoName } }) + const { uuid } = await servers[0].videos.upload({ token: userAccessToken, attributes: { name: videoName } }) videoUUID = uuid await waitJobs(servers) @@ -509,7 +509,7 @@ describe('Test moderation notifications', function () { it('Should send video published and unblacklist after video unblacklisted', async function () { this.timeout(40000) - await servers[0].blacklistCommand.remove({ videoId: videoUUID }) + await servers[0].blacklist.remove({ videoId: videoUUID }) await waitJobs(servers) @@ -543,9 +543,9 @@ describe('Test moderation notifications', function () { } } - const { uuid } = await servers[0].videosCommand.upload({ token: userAccessToken, attributes }) + const { uuid } = await servers[0].videos.upload({ token: userAccessToken, attributes }) - await servers[0].blacklistCommand.remove({ videoId: uuid }) + await servers[0].blacklist.remove({ videoId: uuid }) await waitJobs(servers) await checkNewBlacklistOnMyVideo(userBaseParams, uuid, name, 'unblacklist') @@ -575,7 +575,7 @@ describe('Test moderation notifications', function () { } } - const { uuid } = await servers[0].videosCommand.upload({ token: userAccessToken, attributes }) + const { uuid } = await servers[0].videos.upload({ token: userAccessToken, attributes }) await wait(6000) await checkVideoIsPublished(userBaseParams, name, uuid, 'absence') @@ -589,17 +589,17 @@ describe('Test moderation notifications', function () { const name = 'video without auto-blacklist ' + buildUUID() // admin with blacklist right will not be auto-blacklisted - const { uuid } = await servers[0].videosCommand.upload({ attributes: { name } }) + const { uuid } = await servers[0].videos.upload({ attributes: { name } }) await waitJobs(servers) await checkVideoAutoBlacklistForModerators(adminBaseParamsServer1, uuid, name, 'absence') }) after(async () => { - await servers[0].configCommand.updateCustomConfig({ newCustomConfig: currentCustomConfig }) + await servers[0].config.updateCustomConfig({ newCustomConfig: currentCustomConfig }) - await servers[0].subscriptionsCommand.remove({ uri: 'user_1_channel@localhost:' + servers[0].port }) - await servers[1].subscriptionsCommand.remove({ uri: 'user_1_channel@localhost:' + servers[0].port }) + await servers[0].subscriptions.remove({ uri: 'user_1_channel@localhost:' + servers[0].port }) + await servers[1].subscriptions.remove({ uri: 'user_1_channel@localhost:' + servers[0].port }) }) }) diff --git a/server/tests/api/notifications/notifications-api.ts b/server/tests/api/notifications/notifications-api.ts index 41e1b8015..647d783b5 100644 --- a/server/tests/api/notifications/notifications-api.ts +++ b/server/tests/api/notifications/notifications-api.ts @@ -31,10 +31,10 @@ describe('Test notifications API', function () { userNotifications = res.userNotifications server = res.servers[0] - await server.subscriptionsCommand.add({ token: userToken, targetUri: 'root_channel@localhost:' + server.port }) + await server.subscriptions.add({ token: userToken, targetUri: 'root_channel@localhost:' + server.port }) for (let i = 0; i < 10; i++) { - await server.videosCommand.randomUpload({ wait: false }) + await server.videos.randomUpload({ wait: false }) } await waitJobs([ server ]) @@ -43,14 +43,14 @@ describe('Test notifications API', function () { describe('Mark as read', function () { it('Should mark as read some notifications', async function () { - const { data } = await server.notificationsCommand.list({ token: userToken, start: 2, count: 3 }) + const { data } = await server.notifications.list({ token: userToken, start: 2, count: 3 }) const ids = data.map(n => n.id) - await server.notificationsCommand.markAsRead({ token: userToken, ids }) + await server.notifications.markAsRead({ token: userToken, ids }) }) it('Should have the notifications marked as read', async function () { - const { data } = await server.notificationsCommand.list({ token: userToken, start: 0, count: 10 }) + const { data } = await server.notifications.list({ token: userToken, start: 0, count: 10 }) expect(data[0].read).to.be.false expect(data[1].read).to.be.false @@ -61,7 +61,7 @@ describe('Test notifications API', function () { }) it('Should only list read notifications', async function () { - const { data } = await server.notificationsCommand.list({ token: userToken, start: 0, count: 10, unread: false }) + const { data } = await server.notifications.list({ token: userToken, start: 0, count: 10, unread: false }) for (const notification of data) { expect(notification.read).to.be.true @@ -69,7 +69,7 @@ describe('Test notifications API', function () { }) it('Should only list unread notifications', async function () { - const { data } = await server.notificationsCommand.list({ token: userToken, start: 0, count: 10, unread: true }) + const { data } = await server.notifications.list({ token: userToken, start: 0, count: 10, unread: true }) for (const notification of data) { expect(notification.read).to.be.false @@ -77,9 +77,9 @@ describe('Test notifications API', function () { }) it('Should mark as read all notifications', async function () { - await server.notificationsCommand.markAsReadAll({ token: userToken }) + await server.notifications.markAsReadAll({ token: userToken }) - const body = await server.notificationsCommand.list({ token: userToken, start: 0, count: 10, unread: true }) + const body = await server.notifications.list({ token: userToken, start: 0, count: 10, unread: true }) expect(body.total).to.equal(0) expect(body.data).to.have.lengthOf(0) @@ -101,17 +101,17 @@ describe('Test notifications API', function () { it('Should not have notifications', async function () { this.timeout(20000) - await server.notificationsCommand.updateMySettings({ + await server.notifications.updateMySettings({ token: userToken, settings: { ...getAllNotificationsSettings(), newVideoFromSubscription: UserNotificationSettingValue.NONE } }) { - const info = await server.usersCommand.getMyInfo({ token: userToken }) + const info = await server.users.getMyInfo({ token: userToken }) expect(info.notificationSettings.newVideoFromSubscription).to.equal(UserNotificationSettingValue.NONE) } - const { name, uuid } = await server.videosCommand.randomUpload() + const { name, uuid } = await server.videos.randomUpload() const check = { web: true, mail: true } await checkNewVideoFromSubscription({ ...baseParams, check }, name, uuid, 'absence') @@ -120,17 +120,17 @@ describe('Test notifications API', function () { it('Should only have web notifications', async function () { this.timeout(20000) - await server.notificationsCommand.updateMySettings({ + await server.notifications.updateMySettings({ token: userToken, settings: { ...getAllNotificationsSettings(), newVideoFromSubscription: UserNotificationSettingValue.WEB } }) { - const info = await server.usersCommand.getMyInfo({ token: userToken }) + const info = await server.users.getMyInfo({ token: userToken }) expect(info.notificationSettings.newVideoFromSubscription).to.equal(UserNotificationSettingValue.WEB) } - const { name, uuid } = await server.videosCommand.randomUpload() + const { name, uuid } = await server.videos.randomUpload() { const check = { mail: true, web: false } @@ -146,17 +146,17 @@ describe('Test notifications API', function () { it('Should only have mail notifications', async function () { this.timeout(20000) - await server.notificationsCommand.updateMySettings({ + await server.notifications.updateMySettings({ token: userToken, settings: { ...getAllNotificationsSettings(), newVideoFromSubscription: UserNotificationSettingValue.EMAIL } }) { - const info = await server.usersCommand.getMyInfo({ token: userToken }) + const info = await server.users.getMyInfo({ token: userToken }) expect(info.notificationSettings.newVideoFromSubscription).to.equal(UserNotificationSettingValue.EMAIL) } - const { name, uuid } = await server.videosCommand.randomUpload() + const { name, uuid } = await server.videos.randomUpload() { const check = { mail: false, web: true } @@ -172,7 +172,7 @@ describe('Test notifications API', function () { it('Should have email and web notifications', async function () { this.timeout(20000) - await server.notificationsCommand.updateMySettings({ + await server.notifications.updateMySettings({ token: userToken, settings: { ...getAllNotificationsSettings(), @@ -181,13 +181,13 @@ describe('Test notifications API', function () { }) { - const info = await server.usersCommand.getMyInfo({ token: userToken }) + const info = await server.users.getMyInfo({ token: userToken }) expect(info.notificationSettings.newVideoFromSubscription).to.equal( UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL ) } - const { name, uuid } = await server.videosCommand.randomUpload() + const { name, uuid } = await server.videos.randomUpload() await checkNewVideoFromSubscription(baseParams, name, uuid, 'presence') }) diff --git a/server/tests/api/notifications/user-notifications.ts b/server/tests/api/notifications/user-notifications.ts index 4db8c1576..53f8c7594 100644 --- a/server/tests/api/notifications/user-notifications.ts +++ b/server/tests/api/notifications/user-notifications.ts @@ -61,7 +61,7 @@ describe('Test user notifications', function () { await uploadRandomVideoOnServers(servers, 1) - const notification = await servers[0].notificationsCommand.getLastest({ token: userAccessToken }) + const notification = await servers[0].notifications.getLastest({ token: userAccessToken }) expect(notification).to.be.undefined expect(emails).to.have.lengthOf(0) @@ -71,7 +71,7 @@ describe('Test user notifications', function () { it('Should send a new video notification if the user follows the local video publisher', async function () { this.timeout(15000) - await servers[0].subscriptionsCommand.add({ token: userAccessToken, targetUri: 'root_channel@localhost:' + servers[0].port }) + await servers[0].subscriptions.add({ token: userAccessToken, targetUri: 'root_channel@localhost:' + servers[0].port }) await waitJobs(servers) const { name, uuid } = await uploadRandomVideoOnServers(servers, 1) @@ -81,7 +81,7 @@ describe('Test user notifications', function () { it('Should send a new video notification from a remote account', async function () { this.timeout(150000) // Server 2 has transcoding enabled - await servers[0].subscriptionsCommand.add({ token: userAccessToken, targetUri: 'root_channel@localhost:' + servers[1].port }) + await servers[0].subscriptions.add({ token: userAccessToken, targetUri: 'root_channel@localhost:' + servers[1].port }) await waitJobs(servers) const { name, uuid } = await uploadRandomVideoOnServers(servers, 2) @@ -153,7 +153,7 @@ describe('Test user notifications', function () { await checkNewVideoFromSubscription(baseParams, name, uuid, 'absence') - await servers[0].videosCommand.update({ id: uuid, attributes: { privacy: VideoPrivacy.PUBLIC } }) + await servers[0].videos.update({ id: uuid, attributes: { privacy: VideoPrivacy.PUBLIC } }) await waitJobs(servers) await checkNewVideoFromSubscription(baseParams, name, uuid, 'presence') @@ -167,7 +167,7 @@ describe('Test user notifications', function () { await checkNewVideoFromSubscription(baseParams, name, uuid, 'absence') - await servers[1].videosCommand.update({ id: uuid, attributes: { privacy: VideoPrivacy.PUBLIC } }) + await servers[1].videos.update({ id: uuid, attributes: { privacy: VideoPrivacy.PUBLIC } }) await waitJobs(servers) await checkNewVideoFromSubscription(baseParams, name, uuid, 'presence') @@ -179,7 +179,7 @@ describe('Test user notifications', function () { const data = { privacy: VideoPrivacy.PRIVATE } const { name, uuid } = await uploadRandomVideoOnServers(servers, 1, data) - await servers[0].videosCommand.update({ id: uuid, attributes: { privacy: VideoPrivacy.UNLISTED } }) + await servers[0].videos.update({ id: uuid, attributes: { privacy: VideoPrivacy.UNLISTED } }) await checkNewVideoFromSubscription(baseParams, name, uuid, 'absence') }) @@ -190,7 +190,7 @@ describe('Test user notifications', function () { const data = { privacy: VideoPrivacy.PRIVATE } const { name, uuid } = await uploadRandomVideoOnServers(servers, 2, data) - await servers[1].videosCommand.update({ id: uuid, attributes: { privacy: VideoPrivacy.UNLISTED } }) + await servers[1].videos.update({ id: uuid, attributes: { privacy: VideoPrivacy.UNLISTED } }) await waitJobs(servers) await checkNewVideoFromSubscription(baseParams, name, uuid, 'absence') @@ -207,7 +207,7 @@ describe('Test user notifications', function () { privacy: VideoPrivacy.PUBLIC, targetUrl: ImportsCommand.getGoodVideoUrl() } - const { video } = await servers[0].importsCommand.importVideo({ attributes }) + const { video } = await servers[0].imports.importVideo({ attributes }) await waitJobs(servers) @@ -242,7 +242,7 @@ describe('Test user notifications', function () { await uploadRandomVideoOnServers(servers, 2, { waitTranscoding: false }) await waitJobs(servers) - const notification = await servers[0].notificationsCommand.getLastest({ token: userAccessToken }) + const notification = await servers[0].notifications.getLastest({ token: userAccessToken }) if (notification) { expect(notification.type).to.not.equal(UserNotificationType.MY_VIDEO_PUBLISHED) } @@ -278,7 +278,7 @@ describe('Test user notifications', function () { targetUrl: ImportsCommand.getGoodVideoUrl(), waitTranscoding: true } - const { video } = await servers[1].importsCommand.importVideo({ attributes }) + const { video } = await servers[1].imports.importVideo({ attributes }) await waitJobs(servers) await checkVideoIsPublished(baseParams, name, video.uuid, 'presence') @@ -345,7 +345,7 @@ describe('Test user notifications', function () { privacy: VideoPrivacy.PRIVATE, targetUrl: ImportsCommand.getBadVideoUrl() } - const { video } = await servers[0].importsCommand.importVideo({ attributes }) + const { video } = await servers[0].imports.importVideo({ attributes }) await waitJobs(servers) await checkMyVideoImportIsFinished(baseParams, name, video.uuid, ImportsCommand.getBadVideoUrl(), false, 'presence') @@ -362,7 +362,7 @@ describe('Test user notifications', function () { privacy: VideoPrivacy.PRIVATE, targetUrl: ImportsCommand.getGoodVideoUrl() } - const { video } = await servers[0].importsCommand.importVideo({ attributes }) + const { video } = await servers[0].imports.importVideo({ attributes }) await waitJobs(servers) await checkMyVideoImportIsFinished(baseParams, name, video.uuid, ImportsCommand.getGoodVideoUrl(), true, 'presence') @@ -382,16 +382,16 @@ describe('Test user notifications', function () { token: userAccessToken } - await servers[0].usersCommand.updateMe({ displayName: 'super root name' }) + await servers[0].users.updateMe({ displayName: 'super root name' }) - await servers[0].usersCommand.updateMe({ + await servers[0].users.updateMe({ token: userAccessToken, displayName: myUserName }) - await servers[1].usersCommand.updateMe({ displayName: 'super root 2 name' }) + await servers[1].users.updateMe({ displayName: 'super root 2 name' }) - await servers[0].channelsCommand.update({ + await servers[0].channels.update({ token: userAccessToken, channelName: 'user_1_channel', attributes: { displayName: myChannelName } @@ -401,23 +401,23 @@ describe('Test user notifications', function () { it('Should notify when a local channel is following one of our channel', async function () { this.timeout(50000) - await servers[0].subscriptionsCommand.add({ targetUri: 'user_1_channel@localhost:' + servers[0].port }) + await servers[0].subscriptions.add({ targetUri: 'user_1_channel@localhost:' + servers[0].port }) await waitJobs(servers) await checkNewActorFollow(baseParams, 'channel', 'root', 'super root name', myChannelName, 'presence') - await servers[0].subscriptionsCommand.remove({ uri: 'user_1_channel@localhost:' + servers[0].port }) + await servers[0].subscriptions.remove({ uri: 'user_1_channel@localhost:' + servers[0].port }) }) it('Should notify when a remote channel is following one of our channel', async function () { this.timeout(50000) - await servers[1].subscriptionsCommand.add({ targetUri: 'user_1_channel@localhost:' + servers[0].port }) + await servers[1].subscriptions.add({ targetUri: 'user_1_channel@localhost:' + servers[0].port }) await waitJobs(servers) await checkNewActorFollow(baseParams, 'channel', 'root', 'super root 2 name', myChannelName, 'presence') - await servers[1].subscriptionsCommand.remove({ uri: 'user_1_channel@localhost:' + servers[0].port }) + await servers[1].subscriptions.remove({ uri: 'user_1_channel@localhost:' + servers[0].port }) }) // PeerTube does not support accout -> account follows diff --git a/server/tests/api/redundancy/manage-redundancy.ts b/server/tests/api/redundancy/manage-redundancy.ts index efb60dc56..e193b968e 100644 --- a/server/tests/api/redundancy/manage-redundancy.ts +++ b/server/tests/api/redundancy/manage-redundancy.ts @@ -53,15 +53,15 @@ describe('Test manage videos redundancy', function () { // Get the access tokens await setAccessTokensToServers(servers) - commands = servers.map(s => s.redundancyCommand) + commands = servers.map(s => s.redundancy) { - const { uuid } = await servers[1].videosCommand.upload({ attributes: { name: 'video 1 server 2' } }) + const { uuid } = await servers[1].videos.upload({ attributes: { name: 'video 1 server 2' } }) video1Server2UUID = uuid } { - const { uuid } = await servers[1].videosCommand.upload({ attributes: { name: 'video 2 server 2' } }) + const { uuid } = await servers[1].videos.upload({ attributes: { name: 'video 2 server 2' } }) video2Server2UUID = uuid } @@ -87,7 +87,7 @@ describe('Test manage videos redundancy', function () { this.timeout(120000) await waitJobs(servers) - await servers[0].serversCommand.waitUntilLog('Duplicated ', 10) + await servers[0].servers.waitUntilLog('Duplicated ', 10) await waitJobs(servers) const body = await commands[1].listVideos({ target: 'remote-videos' }) @@ -203,14 +203,14 @@ describe('Test manage videos redundancy', function () { it('Should manually add a redundancy and list it', async function () { this.timeout(120000) - const uuid = (await servers[1].videosCommand.quickUpload({ name: 'video 3 server 2', privacy: VideoPrivacy.UNLISTED })).uuid + const uuid = (await servers[1].videos.quickUpload({ name: 'video 3 server 2', privacy: VideoPrivacy.UNLISTED })).uuid await waitJobs(servers) - const videoId = await servers[0].videosCommand.getId({ uuid }) + const videoId = await servers[0].videos.getId({ uuid }) await commands[0].addVideo({ videoId }) await waitJobs(servers) - await servers[0].serversCommand.waitUntilLog('Duplicated ', 15) + await servers[0].servers.waitUntilLog('Duplicated ', 15) await waitJobs(servers) { diff --git a/server/tests/api/redundancy/redundancy-constraints.ts b/server/tests/api/redundancy/redundancy-constraints.ts index b3f6ed160..0378cc122 100644 --- a/server/tests/api/redundancy/redundancy-constraints.ts +++ b/server/tests/api/redundancy/redundancy-constraints.ts @@ -36,21 +36,21 @@ describe('Test redundancy constraints', function () { async function uploadWrapper (videoName: string) { // Wait for transcoding - const { id } = await localServer.videosCommand.upload({ attributes: { name: 'to transcode', privacy: VideoPrivacy.PRIVATE } }) + const { id } = await localServer.videos.upload({ attributes: { name: 'to transcode', privacy: VideoPrivacy.PRIVATE } }) await waitJobs([ localServer ]) // Update video to schedule a federation - await localServer.videosCommand.update({ id, attributes: { name: videoName, privacy: VideoPrivacy.PUBLIC } }) + await localServer.videos.update({ id, attributes: { name: videoName, privacy: VideoPrivacy.PUBLIC } }) } async function getTotalRedundanciesLocalServer () { - const body = await localServer.redundancyCommand.listVideos({ target: 'my-videos' }) + const body = await localServer.redundancy.listVideos({ target: 'my-videos' }) return body.total } async function getTotalRedundanciesRemoteServer () { - const body = await remoteServer.redundancyCommand.listVideos({ target: 'remote-videos' }) + const body = await remoteServer.redundancy.listVideos({ target: 'remote-videos' }) return body.total } @@ -78,14 +78,14 @@ describe('Test redundancy constraints', function () { // Get the access tokens await setAccessTokensToServers(servers) - await localServer.videosCommand.upload({ attributes: { name: 'video 1 server 2' } }) + await localServer.videos.upload({ attributes: { name: 'video 1 server 2' } }) await waitJobs(servers) // Server 1 and server 2 follow each other - await remoteServer.followsCommand.follow({ targets: [ localServer.url ] }) + await remoteServer.follows.follow({ targets: [ localServer.url ] }) await waitJobs(servers) - await remoteServer.redundancyCommand.updateRedundancy({ host: localServer.host, redundancyAllowed: true }) + await remoteServer.redundancy.updateRedundancy({ host: localServer.host, redundancyAllowed: true }) await waitJobs(servers) }) @@ -94,7 +94,7 @@ describe('Test redundancy constraints', function () { this.timeout(120000) await waitJobs(servers) - await remoteServer.serversCommand.waitUntilLog('Duplicated ', 5) + await remoteServer.servers.waitUntilLog('Duplicated ', 5) await waitJobs(servers) { @@ -123,7 +123,7 @@ describe('Test redundancy constraints', function () { await uploadWrapper('video 2 server 2') - await remoteServer.serversCommand.waitUntilLog('Duplicated ', 10) + await remoteServer.servers.waitUntilLog('Duplicated ', 10) await waitJobs(servers) { @@ -152,7 +152,7 @@ describe('Test redundancy constraints', function () { await uploadWrapper('video 3 server 2') - await remoteServer.serversCommand.waitUntilLog('Duplicated ', 15) + await remoteServer.servers.waitUntilLog('Duplicated ', 15) await waitJobs(servers) { @@ -169,11 +169,11 @@ describe('Test redundancy constraints', function () { it('Should have redundancy on server 1 and on server 2 with followings filter now server 2 follows server 1', async function () { this.timeout(120000) - await localServer.followsCommand.follow({ targets: [ remoteServer.url ] }) + await localServer.follows.follow({ targets: [ remoteServer.url ] }) await waitJobs(servers) await uploadWrapper('video 4 server 2') - await remoteServer.serversCommand.waitUntilLog('Duplicated ', 20) + await remoteServer.servers.waitUntilLog('Duplicated ', 20) await waitJobs(servers) { diff --git a/server/tests/api/redundancy/redundancy.ts b/server/tests/api/redundancy/redundancy.ts index 6ca9c9303..77ea2278e 100644 --- a/server/tests/api/redundancy/redundancy.ts +++ b/server/tests/api/redundancy/redundancy.ts @@ -78,11 +78,11 @@ async function flushAndRunServers (strategy: VideoRedundancyStrategy | null, add await setAccessTokensToServers(servers) { - const { uuid, id } = await servers[1].videosCommand.upload({ attributes: { name: 'video 1 server 2' } }) + const { uuid, id } = await servers[1].videos.upload({ attributes: { name: 'video 1 server 2' } }) video1Server2UUID = uuid video1Server2Id = id - await servers[1].videosCommand.view({ id: video1Server2UUID }) + await servers[1].videos.view({ id: video1Server2UUID }) } await waitJobs(servers) @@ -106,7 +106,7 @@ async function check1WebSeed (videoUUID?: string) { for (const server of servers) { // With token to avoid issues with video follow constraints - const video = await server.videosCommand.getWithToken({ id: videoUUID }) + const video = await server.videos.getWithToken({ id: videoUUID }) for (const f of video.files) { checkMagnetWebseeds(f, webseeds, server) @@ -123,7 +123,7 @@ async function check2Webseeds (videoUUID?: string) { ] for (const server of servers) { - const video = await server.videosCommand.get({ id: videoUUID }) + const video = await server.videos.get({ id: videoUUID }) for (const file of video.files) { checkMagnetWebseeds(file, webseeds, server) @@ -163,7 +163,7 @@ async function check0PlaylistRedundancies (videoUUID?: string) { for (const server of servers) { // With token to avoid issues with video follow constraints - const video = await server.videosCommand.getWithToken({ id: videoUUID }) + const video = await server.videos.getWithToken({ id: videoUUID }) expect(video.streamingPlaylists).to.be.an('array') expect(video.streamingPlaylists).to.have.lengthOf(1) @@ -175,7 +175,7 @@ async function check1PlaylistRedundancies (videoUUID?: string) { if (!videoUUID) videoUUID = video1Server2UUID for (const server of servers) { - const video = await server.videosCommand.get({ id: videoUUID }) + const video = await server.videos.get({ id: videoUUID }) expect(video.streamingPlaylists).to.have.lengthOf(1) expect(video.streamingPlaylists[0].redundancies).to.have.lengthOf(1) @@ -188,7 +188,7 @@ async function check1PlaylistRedundancies (videoUUID?: string) { const baseUrlPlaylist = servers[1].url + '/static/streaming-playlists/hls' const baseUrlSegment = servers[0].url + '/static/redundancy/hls' - const video = await servers[0].videosCommand.get({ id: videoUUID }) + const video = await servers[0].videos.get({ id: videoUUID }) const hlsPlaylist = video.streamingPlaylists[0] for (const resolution of [ 240, 360, 480, 720 ]) { @@ -221,7 +221,7 @@ async function checkStatsGlobal (strategy: VideoRedundancyStrategyWithManual) { statsLength = 2 } - const data = await servers[0].statsCommand.get() + const data = await servers[0].stats.get() expect(data.videosRedundancy).to.have.lengthOf(statsLength) const stat = data.videosRedundancy[0] @@ -248,7 +248,7 @@ async function checkStatsWithoutRedundancy (strategy: VideoRedundancyStrategyWit } async function findServerFollows () { - const body = await servers[0].followsCommand.getFollowings({ start: 0, count: 5, sort: '-createdAt' }) + const body = await servers[0].follows.getFollowings({ start: 0, count: 5, sort: '-createdAt' }) const follows = body.data const server2 = follows.find(f => f.following.host === `localhost:${servers[1].port}`) const server3 = follows.find(f => f.following.host === `localhost:${servers[2].port}`) @@ -257,7 +257,7 @@ async function findServerFollows () { } async function enableRedundancyOnServer1 () { - await servers[0].redundancyCommand.updateRedundancy({ host: servers[1].host, redundancyAllowed: true }) + await servers[0].redundancy.updateRedundancy({ host: servers[1].host, redundancyAllowed: true }) const { server2, server3 } = await findServerFollows() @@ -269,7 +269,7 @@ async function enableRedundancyOnServer1 () { } async function disableRedundancyOnServer1 () { - await servers[0].redundancyCommand.updateRedundancy({ host: servers[1].host, redundancyAllowed: false }) + await servers[0].redundancy.updateRedundancy({ host: servers[1].host, redundancyAllowed: false }) const { server2, server3 } = await findServerFollows() @@ -305,7 +305,7 @@ describe('Test videos redundancy', function () { this.timeout(80000) await waitJobs(servers) - await servers[0].serversCommand.waitUntilLog('Duplicated ', 5) + await servers[0].servers.waitUntilLog('Duplicated ', 5) await waitJobs(servers) await check2Webseeds() @@ -355,7 +355,7 @@ describe('Test videos redundancy', function () { this.timeout(80000) await waitJobs(servers) - await servers[0].serversCommand.waitUntilLog('Duplicated ', 5) + await servers[0].servers.waitUntilLog('Duplicated ', 5) await waitJobs(servers) await check2Webseeds() @@ -366,7 +366,7 @@ describe('Test videos redundancy', function () { it('Should unfollow on server 1 and remove duplicated videos', async function () { this.timeout(80000) - await servers[0].followsCommand.unfollow({ target: servers[1] }) + await servers[0].follows.unfollow({ target: servers[1] }) await waitJobs(servers) await wait(5000) @@ -416,8 +416,8 @@ describe('Test videos redundancy', function () { it('Should view 2 times the first video to have > min_views config', async function () { this.timeout(80000) - await servers[0].videosCommand.view({ id: video1Server2UUID }) - await servers[2].videosCommand.view({ id: video1Server2UUID }) + await servers[0].videos.view({ id: video1Server2UUID }) + await servers[2].videos.view({ id: video1Server2UUID }) await wait(10000) await waitJobs(servers) @@ -427,7 +427,7 @@ describe('Test videos redundancy', function () { this.timeout(80000) await waitJobs(servers) - await servers[0].serversCommand.waitUntilLog('Duplicated ', 5) + await servers[0].servers.waitUntilLog('Duplicated ', 5) await waitJobs(servers) await check2Webseeds() @@ -438,7 +438,7 @@ describe('Test videos redundancy', function () { it('Should remove the video and the redundancy files', async function () { this.timeout(20000) - await servers[1].videosCommand.remove({ id: video1Server2UUID }) + await servers[1].videos.remove({ id: video1Server2UUID }) await waitJobs(servers) @@ -484,14 +484,14 @@ describe('Test videos redundancy', function () { it('Should have 1 redundancy on the first video', async function () { this.timeout(160000) - await servers[0].videosCommand.view({ id: video1Server2UUID }) - await servers[2].videosCommand.view({ id: video1Server2UUID }) + await servers[0].videos.view({ id: video1Server2UUID }) + await servers[2].videos.view({ id: video1Server2UUID }) await wait(10000) await waitJobs(servers) await waitJobs(servers) - await servers[0].serversCommand.waitUntilLog('Duplicated ', 1) + await servers[0].servers.waitUntilLog('Duplicated ', 1) await waitJobs(servers) await check1PlaylistRedundancies() @@ -501,7 +501,7 @@ describe('Test videos redundancy', function () { it('Should remove the video and the redundancy files', async function () { this.timeout(20000) - await servers[1].videosCommand.remove({ id: video1Server2UUID }) + await servers[1].videos.remove({ id: video1Server2UUID }) await waitJobs(servers) @@ -529,14 +529,14 @@ describe('Test videos redundancy', function () { }) it('Should create a redundancy on first video', async function () { - await servers[0].redundancyCommand.addVideo({ videoId: video1Server2Id }) + await servers[0].redundancy.addVideo({ videoId: video1Server2Id }) }) it('Should have 2 webseeds on the first video', async function () { this.timeout(80000) await waitJobs(servers) - await servers[0].serversCommand.waitUntilLog('Duplicated ', 5) + await servers[0].servers.waitUntilLog('Duplicated ', 5) await waitJobs(servers) await check2Webseeds() @@ -547,7 +547,7 @@ describe('Test videos redundancy', function () { it('Should manually remove redundancies on server 1 and remove duplicated videos', async function () { this.timeout(80000) - const body = await servers[0].redundancyCommand.listVideos({ target: 'remote-videos' }) + const body = await servers[0].redundancy.listVideos({ target: 'remote-videos' }) const videos = body.data expect(videos).to.have.lengthOf(1) @@ -555,7 +555,7 @@ describe('Test videos redundancy', function () { const video = videos[0] for (const r of video.redundancies.files.concat(video.redundancies.streamingPlaylists)) { - await servers[0].redundancyCommand.removeVideo({ redundancyId: r.id }) + await servers[0].redundancy.removeVideo({ redundancyId: r.id }) } await waitJobs(servers) @@ -577,7 +577,7 @@ describe('Test videos redundancy', function () { async function checkContains (servers: ServerInfo[], str: string) { for (const server of servers) { - const video = await server.videosCommand.get({ id: video1Server2UUID }) + const video = await server.videos.get({ id: video1Server2UUID }) for (const f of video.files) { expect(f.magnetUri).to.contain(str) @@ -587,7 +587,7 @@ describe('Test videos redundancy', function () { async function checkNotContains (servers: ServerInfo[], str: string) { for (const server of servers) { - const video = await server.videosCommand.get({ id: video1Server2UUID }) + const video = await server.videos.get({ id: video1Server2UUID }) for (const f of video.files) { expect(f.magnetUri).to.not.contain(str) @@ -645,20 +645,20 @@ describe('Test videos redundancy', function () { await enableRedundancyOnServer1() await waitJobs(servers) - await servers[0].serversCommand.waitUntilLog('Duplicated ', 5) + await servers[0].servers.waitUntilLog('Duplicated ', 5) await waitJobs(servers) await check2Webseeds(video1Server2UUID) await check1PlaylistRedundancies(video1Server2UUID) await checkStatsWith1Redundancy(strategy) - const { uuid } = await servers[1].videosCommand.upload({ attributes: { name: 'video 2 server 2', privacy: VideoPrivacy.PRIVATE } }) + const { uuid } = await servers[1].videos.upload({ attributes: { name: 'video 2 server 2', privacy: VideoPrivacy.PRIVATE } }) video2Server2UUID = uuid // Wait transcoding before federation await waitJobs(servers) - await servers[1].videosCommand.update({ id: video2Server2UUID, attributes: { privacy: VideoPrivacy.PUBLIC } }) + await servers[1].videos.update({ id: video2Server2UUID, attributes: { privacy: VideoPrivacy.PUBLIC } }) }) it('Should cache video 2 webseeds on the first video', async function () { diff --git a/server/tests/api/search/search-activitypub-video-channels.ts b/server/tests/api/search/search-activitypub-video-channels.ts index 75794402d..71e9367e5 100644 --- a/server/tests/api/search/search-activitypub-video-channels.ts +++ b/server/tests/api/search/search-activitypub-video-channels.ts @@ -30,34 +30,34 @@ describe('Test ActivityPub video channels search', function () { await setAccessTokensToServers(servers) { - await servers[0].usersCommand.create({ username: 'user1_server1', password: 'password' }) + await servers[0].users.create({ username: 'user1_server1', password: 'password' }) const channel = { name: 'channel1_server1', displayName: 'Channel 1 server 1' } - await servers[0].channelsCommand.create({ attributes: channel }) + await servers[0].channels.create({ attributes: channel }) } { const user = { username: 'user1_server2', password: 'password' } - await servers[1].usersCommand.create({ username: user.username, password: user.password }) - userServer2Token = await servers[1].loginCommand.getAccessToken(user) + await servers[1].users.create({ username: user.username, password: user.password }) + userServer2Token = await servers[1].login.getAccessToken(user) const channel = { name: 'channel1_server2', displayName: 'Channel 1 server 2' } - const created = await servers[1].channelsCommand.create({ token: userServer2Token, attributes: channel }) + const created = await servers[1].channels.create({ token: userServer2Token, attributes: channel }) channelIdServer2 = created.id const attributes = { name: 'video 1 server 2', channelId: channelIdServer2 } - const { uuid } = await servers[1].videosCommand.upload({ token: userServer2Token, attributes }) + const { uuid } = await servers[1].videos.upload({ token: userServer2Token, attributes }) videoServer2UUID = uuid } await waitJobs(servers) - command = servers[0].searchCommand + command = servers[0].search }) it('Should not find a remote video channel', async function () { @@ -134,7 +134,7 @@ describe('Test ActivityPub video channels search', function () { }) it('Should not list this remote video channel', async function () { - const body = await servers[0].channelsCommand.list() + const body = await servers[0].channels.list() expect(body.total).to.equal(3) expect(body.data).to.have.lengthOf(3) expect(body.data[0].name).to.equal('channel1_server1') @@ -147,7 +147,7 @@ describe('Test ActivityPub video channels search', function () { await waitJobs(servers) - const { total, data } = await servers[0].videosCommand.listByChannel({ + const { total, data } = await servers[0].videos.listByChannel({ token: null, videoChannelName: 'channel1_server2@localhost:' + servers[1].port }) @@ -156,7 +156,7 @@ describe('Test ActivityPub video channels search', function () { }) it('Should list video channel videos of server 2 with token', async function () { - const { total, data } = await servers[0].videosCommand.listByChannel({ + const { total, data } = await servers[0].videos.listByChannel({ videoChannelName: 'channel1_server2@localhost:' + servers[1].port }) @@ -167,12 +167,12 @@ describe('Test ActivityPub video channels search', function () { it('Should update video channel of server 2, and refresh it on server 1', async function () { this.timeout(60000) - await servers[1].channelsCommand.update({ + await servers[1].channels.update({ token: userServer2Token, channelName: 'channel1_server2', attributes: { displayName: 'channel updated' } }) - await servers[1].usersCommand.updateMe({ token: userServer2Token, displayName: 'user updated' }) + await servers[1].users.updateMe({ token: userServer2Token, displayName: 'user updated' }) await waitJobs(servers) // Expire video channel @@ -193,8 +193,8 @@ describe('Test ActivityPub video channels search', function () { it('Should update and add a video on server 2, and update it on server 1 after a search', async function () { this.timeout(60000) - await servers[1].videosCommand.update({ token: userServer2Token, id: videoServer2UUID, attributes: { name: 'video 1 updated' } }) - await servers[1].videosCommand.upload({ token: userServer2Token, attributes: { name: 'video 2 server 2', channelId: channelIdServer2 } }) + await servers[1].videos.update({ token: userServer2Token, id: videoServer2UUID, attributes: { name: 'video 1 updated' } }) + await servers[1].videos.upload({ token: userServer2Token, attributes: { name: 'video 2 server 2', channelId: channelIdServer2 } }) await waitJobs(servers) @@ -207,7 +207,7 @@ describe('Test ActivityPub video channels search', function () { await waitJobs(servers) const videoChannelName = 'channel1_server2@localhost:' + servers[1].port - const { total, data } = await servers[0].videosCommand.listByChannel({ videoChannelName, sort: '-createdAt' }) + const { total, data } = await servers[0].videos.listByChannel({ videoChannelName, sort: '-createdAt' }) expect(total).to.equal(2) expect(data[0].name).to.equal('video 2 server 2') @@ -217,7 +217,7 @@ describe('Test ActivityPub video channels search', function () { it('Should delete video channel of server 2, and delete it on server 1', async function () { this.timeout(60000) - await servers[1].channelsCommand.delete({ token: userServer2Token, channelName: 'channel1_server2' }) + await servers[1].channels.delete({ token: userServer2Token, channelName: 'channel1_server2' }) await waitJobs(servers) // Expire video diff --git a/server/tests/api/search/search-activitypub-video-playlists.ts b/server/tests/api/search/search-activitypub-video-playlists.ts index 46105c12c..7c99b954b 100644 --- a/server/tests/api/search/search-activitypub-video-playlists.ts +++ b/server/tests/api/search/search-activitypub-video-playlists.ts @@ -33,40 +33,40 @@ describe('Test ActivityPub playlists search', function () { await setDefaultVideoChannel(servers) { - const video1 = (await servers[0].videosCommand.quickUpload({ name: 'video 1' })).uuid - const video2 = (await servers[0].videosCommand.quickUpload({ name: 'video 2' })).uuid + const video1 = (await servers[0].videos.quickUpload({ name: 'video 1' })).uuid + const video2 = (await servers[0].videos.quickUpload({ name: 'video 2' })).uuid const attributes = { displayName: 'playlist 1 on server 1', privacy: VideoPlaylistPrivacy.PUBLIC, - videoChannelId: servers[0].videoChannel.id + videoChannelId: servers[0].store.channel.id } - const created = await servers[0].playlistsCommand.create({ attributes }) + const created = await servers[0].playlists.create({ attributes }) playlistServer1UUID = created.uuid for (const videoId of [ video1, video2 ]) { - await servers[0].playlistsCommand.addElement({ playlistId: playlistServer1UUID, attributes: { videoId } }) + await servers[0].playlists.addElement({ playlistId: playlistServer1UUID, attributes: { videoId } }) } } { - const videoId = (await servers[1].videosCommand.quickUpload({ name: 'video 1' })).uuid - video2Server2 = (await servers[1].videosCommand.quickUpload({ name: 'video 2' })).uuid + const videoId = (await servers[1].videos.quickUpload({ name: 'video 1' })).uuid + video2Server2 = (await servers[1].videos.quickUpload({ name: 'video 2' })).uuid const attributes = { displayName: 'playlist 1 on server 2', privacy: VideoPlaylistPrivacy.PUBLIC, - videoChannelId: servers[1].videoChannel.id + videoChannelId: servers[1].store.channel.id } - const created = await servers[1].playlistsCommand.create({ attributes }) + const created = await servers[1].playlists.create({ attributes }) playlistServer2UUID = created.uuid - await servers[1].playlistsCommand.addElement({ playlistId: playlistServer2UUID, attributes: { videoId } }) + await servers[1].playlists.addElement({ playlistId: playlistServer2UUID, attributes: { videoId } }) } await waitJobs(servers) - command = servers[0].searchCommand + command = servers[0].search }) it('Should not find a remote playlist', async function () { @@ -139,7 +139,7 @@ describe('Test ActivityPub playlists search', function () { }) it('Should not list this remote playlist', async function () { - const body = await servers[0].playlistsCommand.list({ start: 0, count: 10 }) + const body = await servers[0].playlists.list({ start: 0, count: 10 }) expect(body.total).to.equal(1) expect(body.data).to.have.lengthOf(1) expect(body.data[0].displayName).to.equal('playlist 1 on server 1') @@ -148,7 +148,7 @@ describe('Test ActivityPub playlists search', function () { it('Should update the playlist of server 2, and refresh it on server 1', async function () { this.timeout(60000) - await servers[1].playlistsCommand.addElement({ playlistId: playlistServer2UUID, attributes: { videoId: video2Server2 } }) + await servers[1].playlists.addElement({ playlistId: playlistServer2UUID, attributes: { videoId: video2Server2 } }) await waitJobs(servers) // Expire playlist @@ -172,7 +172,7 @@ describe('Test ActivityPub playlists search', function () { it('Should delete playlist of server 2, and delete it on server 1', async function () { this.timeout(60000) - await servers[1].playlistsCommand.delete({ playlistId: playlistServer2UUID }) + await servers[1].playlists.delete({ playlistId: playlistServer2UUID }) await waitJobs(servers) // Expiration diff --git a/server/tests/api/search/search-activitypub-videos.ts b/server/tests/api/search/search-activitypub-videos.ts index 19b4d5ed8..0dfc63446 100644 --- a/server/tests/api/search/search-activitypub-videos.ts +++ b/server/tests/api/search/search-activitypub-videos.ts @@ -30,18 +30,18 @@ describe('Test ActivityPub videos search', function () { await setAccessTokensToServers(servers) { - const { uuid } = await servers[0].videosCommand.upload({ attributes: { name: 'video 1 on server 1' } }) + const { uuid } = await servers[0].videos.upload({ attributes: { name: 'video 1 on server 1' } }) videoServer1UUID = uuid } { - const { uuid } = await servers[1].videosCommand.upload({ attributes: { name: 'video 1 on server 2' } }) + const { uuid } = await servers[1].videos.upload({ attributes: { name: 'video 1 on server 2' } }) videoServer2UUID = uuid } await waitJobs(servers) - command = servers[0].searchCommand + command = servers[0].search }) it('Should not find a remote video', async function () { @@ -105,7 +105,7 @@ describe('Test ActivityPub videos search', function () { }) it('Should not list this remote video', async function () { - const { total, data } = await servers[0].videosCommand.list() + const { total, data } = await servers[0].videos.list() expect(total).to.equal(1) expect(data).to.have.lengthOf(1) expect(data[0].name).to.equal('video 1 on server 1') @@ -118,7 +118,7 @@ describe('Test ActivityPub videos search', function () { name: 'super_channel', displayName: 'super channel' } - const created = await servers[1].channelsCommand.create({ attributes: channelAttributes }) + const created = await servers[1].channels.create({ attributes: channelAttributes }) const videoChannelId = created.id const attributes = { @@ -127,7 +127,7 @@ describe('Test ActivityPub videos search', function () { privacy: VideoPrivacy.UNLISTED, channelId: videoChannelId } - await servers[1].videosCommand.update({ id: videoServer2UUID, attributes }) + await servers[1].videos.update({ id: videoServer2UUID, attributes }) await waitJobs(servers) // Expire video @@ -153,7 +153,7 @@ describe('Test ActivityPub videos search', function () { it('Should delete video of server 2, and delete it on server 1', async function () { this.timeout(120000) - await servers[1].videosCommand.remove({ id: videoServer2UUID }) + await servers[1].videos.remove({ id: videoServer2UUID }) await waitJobs(servers) // Expire video diff --git a/server/tests/api/search/search-channels.ts b/server/tests/api/search/search-channels.ts index 4d2104708..7035fbd62 100644 --- a/server/tests/api/search/search-channels.ts +++ b/server/tests/api/search/search-channels.ts @@ -19,15 +19,15 @@ describe('Test channels search', function () { await setAccessTokensToServers([ server ]) { - await server.usersCommand.create({ username: 'user1', password: 'password' }) + await server.users.create({ username: 'user1', password: 'password' }) const channel = { name: 'squall_channel', displayName: 'Squall channel' } - await server.channelsCommand.create({ attributes: channel }) + await server.channels.create({ attributes: channel }) } - command = server.searchCommand + command = server.search }) it('Should make a simple search and not have results', async function () { diff --git a/server/tests/api/search/search-index.ts b/server/tests/api/search/search-index.ts index d5dc40f60..b54c0da22 100644 --- a/server/tests/api/search/search-index.ts +++ b/server/tests/api/search/search-index.ts @@ -20,9 +20,9 @@ describe('Test videos search', function () { await setAccessTokensToServers([ server ]) - await server.videosCommand.upload({ attributes: { name: localVideoName } }) + await server.videos.upload({ attributes: { name: localVideoName } }) - command = server.searchCommand + command = server.search }) describe('Default search', async function () { @@ -30,7 +30,7 @@ describe('Test videos search', function () { it('Should make a local videos search by default', async function () { this.timeout(10000) - await server.configCommand.updateCustomSubConfig({ + await server.config.updateCustomSubConfig({ newConfig: { search: { searchIndex: { @@ -57,7 +57,7 @@ describe('Test videos search', function () { }) it('Should make an index videos search by default', async function () { - await server.configCommand.updateCustomSubConfig({ + await server.config.updateCustomSubConfig({ newConfig: { search: { searchIndex: { @@ -79,7 +79,7 @@ describe('Test videos search', function () { }) it('Should make an index videos search if local search is disabled', async function () { - await server.configCommand.updateCustomSubConfig({ + await server.config.updateCustomSubConfig({ newConfig: { search: { searchIndex: { @@ -213,7 +213,7 @@ describe('Test videos search', function () { let nsfwUUID: string { - await server.configCommand.updateCustomSubConfig({ + await server.config.updateCustomSubConfig({ newConfig: { instance: { defaultNSFWPolicy: 'display' } } @@ -229,7 +229,7 @@ describe('Test videos search', function () { } { - await server.configCommand.updateCustomSubConfig({ + await server.config.updateCustomSubConfig({ newConfig: { instance: { defaultNSFWPolicy: 'do_not_list' } } diff --git a/server/tests/api/search/search-playlists.ts b/server/tests/api/search/search-playlists.ts index 2e4773ed6..e15128c8e 100644 --- a/server/tests/api/search/search-playlists.ts +++ b/server/tests/api/search/search-playlists.ts @@ -26,40 +26,40 @@ describe('Test playlists search', function () { await setAccessTokensToServers([ server ]) await setDefaultVideoChannel([ server ]) - const videoId = (await server.videosCommand.quickUpload({ name: 'video' })).uuid + const videoId = (await server.videos.quickUpload({ name: 'video' })).uuid { const attributes = { displayName: 'Dr. Kenzo Tenma hospital videos', privacy: VideoPlaylistPrivacy.PUBLIC, - videoChannelId: server.videoChannel.id + videoChannelId: server.store.channel.id } - const created = await server.playlistsCommand.create({ attributes }) + const created = await server.playlists.create({ attributes }) - await server.playlistsCommand.addElement({ playlistId: created.id, attributes: { videoId } }) + await server.playlists.addElement({ playlistId: created.id, attributes: { videoId } }) } { const attributes = { displayName: 'Johan & Anna Libert musics', privacy: VideoPlaylistPrivacy.PUBLIC, - videoChannelId: server.videoChannel.id + videoChannelId: server.store.channel.id } - const created = await server.playlistsCommand.create({ attributes }) + const created = await server.playlists.create({ attributes }) - await server.playlistsCommand.addElement({ playlistId: created.id, attributes: { videoId } }) + await server.playlists.addElement({ playlistId: created.id, attributes: { videoId } }) } { const attributes = { displayName: 'Inspector Lunge playlist', privacy: VideoPlaylistPrivacy.PUBLIC, - videoChannelId: server.videoChannel.id + videoChannelId: server.store.channel.id } - await server.playlistsCommand.create({ attributes }) + await server.playlists.create({ attributes }) } - command = server.searchCommand + command = server.search }) it('Should make a simple search and not have results', async function () { diff --git a/server/tests/api/search/search-videos.ts b/server/tests/api/search/search-videos.ts index 148499d5f..478ebafc9 100644 --- a/server/tests/api/search/search-videos.ts +++ b/server/tests/api/search/search-videos.ts @@ -40,24 +40,24 @@ describe('Test videos search', function () { nsfw: false, language: 'fr' } - await server.videosCommand.upload({ attributes: attributes1 }) + await server.videos.upload({ attributes: attributes1 }) const attributes2 = { ...attributes1, name: attributes1.name + ' - 2', fixture: 'video_short.mp4' } - await server.videosCommand.upload({ attributes: attributes2 }) + await server.videos.upload({ attributes: attributes2 }) { const attributes3 = { ...attributes1, name: attributes1.name + ' - 3', language: undefined } - const { id, uuid } = await server.videosCommand.upload({ attributes: attributes3 }) + const { id, uuid } = await server.videos.upload({ attributes: attributes3 }) videoUUID = uuid - await server.captionsCommand.createVideoCaption({ + await server.captions.createVideoCaption({ language: 'en', videoId: id, fixture: 'subtitle-good2.vtt', mimeType: 'application/octet-stream' }) - await server.captionsCommand.createVideoCaption({ + await server.captions.createVideoCaption({ language: 'aa', videoId: id, fixture: 'subtitle-good2.vtt', @@ -66,23 +66,23 @@ describe('Test videos search', function () { } const attributes4 = { ...attributes1, name: attributes1.name + ' - 4', language: 'pl', nsfw: true } - await server.videosCommand.upload({ attributes: attributes4 }) + await server.videos.upload({ attributes: attributes4 }) await wait(1000) startDate = new Date().toISOString() const attributes5 = { ...attributes1, name: attributes1.name + ' - 5', licence: 2, language: undefined } - await server.videosCommand.upload({ attributes: attributes5 }) + await server.videos.upload({ attributes: attributes5 }) const attributes6 = { ...attributes1, name: attributes1.name + ' - 6', tags: [ 't1', 't2' ] } - await server.videosCommand.upload({ attributes: attributes6 }) + await server.videos.upload({ attributes: attributes6 }) const attributes7 = { ...attributes1, name: attributes1.name + ' - 7', originallyPublishedAt: '2019-02-12T09:58:08.286Z' } - await server.videosCommand.upload({ attributes: attributes7 }) + await server.videos.upload({ attributes: attributes7 }) const attributes8 = { ...attributes1, name: attributes1.name + ' - 8', licence: 4 } - await server.videosCommand.upload({ attributes: attributes8 }) + await server.videos.upload({ attributes: attributes8 }) } { @@ -93,9 +93,9 @@ describe('Test videos search', function () { licence: 2, language: 'en' } - await server.videosCommand.upload({ attributes: attributes }) + await server.videos.upload({ attributes: attributes }) - await server.videosCommand.upload({ attributes: { ...attributes, name: attributes.name + ' duplicate' } }) + await server.videos.upload({ attributes: { ...attributes, name: attributes.name + ' duplicate' } }) } { @@ -106,7 +106,7 @@ describe('Test videos search', function () { licence: 3, language: 'pl' } - await server.videosCommand.upload({ attributes: attributes }) + await server.videos.upload({ attributes: attributes }) } { @@ -115,11 +115,11 @@ describe('Test videos search', function () { tags: [ 'aaaa', 'bbbb', 'cccc' ], category: 1 } - await server.videosCommand.upload({ attributes: attributes1 }) - await server.videosCommand.upload({ attributes: { ...attributes1, category: 2 } }) + await server.videos.upload({ attributes: attributes1 }) + await server.videos.upload({ attributes: { ...attributes1, category: 2 } }) - await server.videosCommand.upload({ attributes: { ...attributes1, tags: [ 'cccc', 'dddd' ] } }) - await server.videosCommand.upload({ attributes: { ...attributes1, tags: [ 'eeee', 'ffff' ] } }) + await server.videos.upload({ attributes: { ...attributes1, tags: [ 'cccc', 'dddd' ] } }) + await server.videos.upload({ attributes: { ...attributes1, tags: [ 'eeee', 'ffff' ] } }) } { @@ -127,11 +127,11 @@ describe('Test videos search', function () { name: 'aaaa 2', category: 1 } - await server.videosCommand.upload({ attributes: attributes1 }) - await server.videosCommand.upload({ attributes: { ...attributes1, category: 2 } }) + await server.videos.upload({ attributes: attributes1 }) + await server.videos.upload({ attributes: { ...attributes1, category: 2 } }) } - command = server.searchCommand + command = server.search }) it('Should make a simple search and not have results', async function () { @@ -479,7 +479,7 @@ describe('Test videos search', function () { }, live: { enabled: true } } - await server.configCommand.updateCustomSubConfig({ newConfig }) + await server.config.updateCustomSubConfig({ newConfig }) } { @@ -490,9 +490,9 @@ describe('Test videos search', function () { } { - const liveCommand = server.liveCommand + const liveCommand = server.live - const liveAttributes = { name: 'live', privacy: VideoPrivacy.PUBLIC, channelId: server.videoChannel.id } + const liveAttributes = { name: 'live', privacy: VideoPrivacy.PUBLIC, channelId: server.store.channel.id } const live = await liveCommand.create({ fields: liveAttributes }) const ffmpegCommand = await liveCommand.sendRTMPStreamInVideo({ videoId: live.id }) diff --git a/server/tests/api/server/auto-follows.ts b/server/tests/api/server/auto-follows.ts index 34c4f6882..e9fb5b4b1 100644 --- a/server/tests/api/server/auto-follows.ts +++ b/server/tests/api/server/auto-follows.ts @@ -16,7 +16,7 @@ const expect = chai.expect async function checkFollow (follower: ServerInfo, following: ServerInfo, exists: boolean) { { - const body = await following.followsCommand.getFollowers({ start: 0, count: 5, sort: '-createdAt' }) + const body = await following.follows.getFollowers({ start: 0, count: 5, sort: '-createdAt' }) const follow = body.data.find(f => f.follower.host === follower.host && f.state === 'accepted') if (exists === true) expect(follow).to.exist @@ -24,7 +24,7 @@ async function checkFollow (follower: ServerInfo, following: ServerInfo, exists: } { - const body = await follower.followsCommand.getFollowings({ start: 0, count: 5, sort: '-createdAt' }) + const body = await follower.follows.getFollowings({ start: 0, count: 5, sort: '-createdAt' }) const follow = body.data.find(f => f.following.host === following.host && f.state === 'accepted') if (exists === true) expect(follow).to.exist @@ -33,15 +33,15 @@ async function checkFollow (follower: ServerInfo, following: ServerInfo, exists: } async function server1Follows2 (servers: ServerInfo[]) { - await servers[0].followsCommand.follow({ targets: [ servers[1].host ] }) + await servers[0].follows.follow({ targets: [ servers[1].host ] }) await waitJobs(servers) } async function resetFollows (servers: ServerInfo[]) { try { - await servers[0].followsCommand.unfollow({ target: servers[1] }) - await servers[1].followsCommand.unfollow({ target: servers[0] }) + await servers[0].follows.unfollow({ target: servers[1] }) + await servers[1].follows.unfollow({ target: servers[0] }) } catch { /* empty */ } @@ -86,7 +86,7 @@ describe('Test auto follows', function () { } } } - await servers[1].configCommand.updateCustomSubConfig({ newConfig: config }) + await servers[1].config.updateCustomSubConfig({ newConfig: config }) await server1Follows2(servers) @@ -111,14 +111,14 @@ describe('Test auto follows', function () { } } } - await servers[1].configCommand.updateCustomSubConfig({ newConfig: config }) + await servers[1].config.updateCustomSubConfig({ newConfig: config }) await server1Follows2(servers) await checkFollow(servers[0], servers[1], false) await checkFollow(servers[1], servers[0], false) - await servers[1].followsCommand.acceptFollower({ follower: 'peertube@' + servers[0].host }) + await servers[1].follows.acceptFollower({ follower: 'peertube@' + servers[0].host }) await waitJobs(servers) await checkFollow(servers[0], servers[1], true) @@ -128,7 +128,7 @@ describe('Test auto follows', function () { config.followings.instance.autoFollowBack.enabled = false config.followers.instance.manualApproval = false - await servers[1].configCommand.updateCustomSubConfig({ newConfig: config }) + await servers[1].config.updateCustomSubConfig({ newConfig: config }) }) }) @@ -165,7 +165,7 @@ describe('Test auto follows', function () { } } } - await servers[0].configCommand.updateCustomSubConfig({ newConfig: config }) + await servers[0].config.updateCustomSubConfig({ newConfig: config }) await wait(5000) await waitJobs(servers) diff --git a/server/tests/api/server/bulk.ts b/server/tests/api/server/bulk.ts index c83bcfb22..acc17092d 100644 --- a/server/tests/api/server/bulk.ts +++ b/server/tests/api/server/bulk.ts @@ -34,23 +34,23 @@ describe('Test bulk actions', function () { { const user = { username: 'user1', password: 'password' } - await servers[0].usersCommand.create({ username: user.username, password: user.password }) + await servers[0].users.create({ username: user.username, password: user.password }) - user1Token = await servers[0].loginCommand.getAccessToken(user) + user1Token = await servers[0].login.getAccessToken(user) } { const user = { username: 'user2', password: 'password' } - await servers[0].usersCommand.create({ username: user.username, password: user.password }) + await servers[0].users.create({ username: user.username, password: user.password }) - user2Token = await servers[0].loginCommand.getAccessToken(user) + user2Token = await servers[0].login.getAccessToken(user) } { const user = { username: 'user3', password: 'password' } - await servers[1].usersCommand.create({ username: user.username, password: user.password }) + await servers[1].users.create({ username: user.username, password: user.password }) - user3Token = await servers[1].loginCommand.getAccessToken(user) + user3Token = await servers[1].login.getAccessToken(user) } await doubleFollow(servers[0], servers[1]) @@ -61,11 +61,11 @@ describe('Test bulk actions', function () { describe('Bulk remove comments', function () { async function checkInstanceCommentsRemoved () { { - const { data } = await servers[0].videosCommand.list() + const { data } = await servers[0].videos.list() // Server 1 should not have these comments anymore for (const video of data) { - const { data } = await servers[0].commentsCommand.listThreads({ videoId: video.id }) + const { data } = await servers[0].comments.listThreads({ videoId: video.id }) const comment = data.find(c => c.text === 'comment by user 3') expect(comment).to.not.exist @@ -73,11 +73,11 @@ describe('Test bulk actions', function () { } { - const { data } = await servers[1].videosCommand.list() + const { data } = await servers[1].videos.list() // Server 1 should not have these comments on videos of server 1 for (const video of data) { - const { data } = await servers[1].commentsCommand.listThreads({ videoId: video.id }) + const { data } = await servers[1].comments.listThreads({ videoId: video.id }) const comment = data.find(c => c.text === 'comment by user 3') if (video.account.host === 'localhost:' + servers[0].port) { @@ -92,30 +92,30 @@ describe('Test bulk actions', function () { before(async function () { this.timeout(120000) - await servers[0].videosCommand.upload({ attributes: { name: 'video 1 server 1' } }) - await servers[0].videosCommand.upload({ attributes: { name: 'video 2 server 1' } }) - await servers[0].videosCommand.upload({ token: user1Token, attributes: { name: 'video 3 server 1' } }) + await servers[0].videos.upload({ attributes: { name: 'video 1 server 1' } }) + await servers[0].videos.upload({ attributes: { name: 'video 2 server 1' } }) + await servers[0].videos.upload({ token: user1Token, attributes: { name: 'video 3 server 1' } }) - await servers[1].videosCommand.upload({ attributes: { name: 'video 1 server 2' } }) + await servers[1].videos.upload({ attributes: { name: 'video 1 server 2' } }) await waitJobs(servers) { - const { data } = await servers[0].videosCommand.list() + const { data } = await servers[0].videos.list() for (const video of data) { - await servers[0].commentsCommand.createThread({ videoId: video.id, text: 'comment by root server 1' }) - await servers[0].commentsCommand.createThread({ token: user1Token, videoId: video.id, text: 'comment by user 1' }) - await servers[0].commentsCommand.createThread({ token: user2Token, videoId: video.id, text: 'comment by user 2' }) + await servers[0].comments.createThread({ videoId: video.id, text: 'comment by root server 1' }) + await servers[0].comments.createThread({ token: user1Token, videoId: video.id, text: 'comment by user 1' }) + await servers[0].comments.createThread({ token: user2Token, videoId: video.id, text: 'comment by user 2' }) } } { - const { data } = await servers[1].videosCommand.list() + const { data } = await servers[1].videos.list() for (const video of data) { - await servers[1].commentsCommand.createThread({ videoId: video.id, text: 'comment by root server 2' }) + await servers[1].comments.createThread({ videoId: video.id, text: 'comment by root server 2' }) - const comment = await servers[1].commentsCommand.createThread({ token: user3Token, videoId: video.id, text: 'comment by user 3' }) + const comment = await servers[1].comments.createThread({ token: user3Token, videoId: video.id, text: 'comment by user 3' }) commentsUser3.push({ videoId: video.id, commentId: comment.id }) } } @@ -137,10 +137,10 @@ describe('Test bulk actions', function () { await waitJobs(servers) for (const server of servers) { - const { data } = await server.videosCommand.list() + const { data } = await server.videos.list() for (const video of data) { - const { data } = await server.commentsCommand.listThreads({ videoId: video.id }) + const { data } = await server.comments.listThreads({ videoId: video.id }) const comment = data.find(c => c.text === 'comment by user 2') if (video.name === 'video 3 server 1') expect(comment).to.not.exist @@ -168,7 +168,7 @@ describe('Test bulk actions', function () { this.timeout(60000) for (const obj of commentsUser3) { - await servers[1].commentsCommand.addReply({ + await servers[1].comments.addReply({ token: user3Token, videoId: obj.videoId, toCommentId: obj.commentId, diff --git a/server/tests/api/server/config.ts b/server/tests/api/server/config.ts index c613511ed..479e177a8 100644 --- a/server/tests/api/server/config.ts +++ b/server/tests/api/server/config.ts @@ -214,7 +214,7 @@ describe('Test config', function () { }) it('Should have a correct config on a server with registration enabled', async function () { - const data = await server.configCommand.getConfig() + const data = await server.config.getConfig() expect(data.signup.allowed).to.be.true }) @@ -223,32 +223,32 @@ describe('Test config', function () { this.timeout(5000) await Promise.all([ - server.usersCommand.register({ username: 'user1' }), - server.usersCommand.register({ username: 'user2' }), - server.usersCommand.register({ username: 'user3' }) + server.users.register({ username: 'user1' }), + server.users.register({ username: 'user2' }), + server.users.register({ username: 'user3' }) ]) - const data = await server.configCommand.getConfig() + const data = await server.config.getConfig() expect(data.signup.allowed).to.be.false }) it('Should have the correct video allowed extensions', async function () { - const data = await server.configCommand.getConfig() + const data = await server.config.getConfig() expect(data.video.file.extensions).to.have.lengthOf(3) expect(data.video.file.extensions).to.contain('.mp4') expect(data.video.file.extensions).to.contain('.webm') expect(data.video.file.extensions).to.contain('.ogv') - await server.videosCommand.upload({ attributes: { fixture: 'video_short.mkv' }, expectedStatus: HttpStatusCode.UNSUPPORTED_MEDIA_TYPE_415 }) - await server.videosCommand.upload({ attributes: { fixture: 'sample.ogg' }, expectedStatus: HttpStatusCode.UNSUPPORTED_MEDIA_TYPE_415 }) + await server.videos.upload({ attributes: { fixture: 'video_short.mkv' }, expectedStatus: HttpStatusCode.UNSUPPORTED_MEDIA_TYPE_415 }) + await server.videos.upload({ attributes: { fixture: 'sample.ogg' }, expectedStatus: HttpStatusCode.UNSUPPORTED_MEDIA_TYPE_415 }) expect(data.contactForm.enabled).to.be.true }) it('Should get the customized configuration', async function () { - const data = await server.configCommand.getCustomConfig() + const data = await server.config.getCustomConfig() checkInitialConfig(server, data) }) @@ -425,16 +425,16 @@ describe('Test config', function () { } } } - await server.configCommand.updateCustomConfig({ newCustomConfig }) + await server.config.updateCustomConfig({ newCustomConfig }) - const data = await server.configCommand.getCustomConfig() + const data = await server.config.getCustomConfig() checkUpdatedConfig(data) }) it('Should have the correct updated video allowed extensions', async function () { this.timeout(10000) - const data = await server.configCommand.getConfig() + const data = await server.config.getConfig() expect(data.video.file.extensions).to.have.length.above(4) expect(data.video.file.extensions).to.contain('.mp4') @@ -447,8 +447,8 @@ describe('Test config', function () { expect(data.video.file.extensions).to.contain('.ogg') expect(data.video.file.extensions).to.contain('.flac') - await server.videosCommand.upload({ attributes: { fixture: 'video_short.mkv' }, expectedStatus: HttpStatusCode.OK_200 }) - await server.videosCommand.upload({ attributes: { fixture: 'sample.ogg' }, expectedStatus: HttpStatusCode.OK_200 }) + await server.videos.upload({ attributes: { fixture: 'video_short.mkv' }, expectedStatus: HttpStatusCode.OK_200 }) + await server.videos.upload({ attributes: { fixture: 'sample.ogg' }, expectedStatus: HttpStatusCode.OK_200 }) }) it('Should have the configuration updated after a restart', async function () { @@ -458,13 +458,13 @@ describe('Test config', function () { await reRunServer(server) - const data = await server.configCommand.getCustomConfig() + const data = await server.config.getCustomConfig() checkUpdatedConfig(data) }) it('Should fetch the about information', async function () { - const data = await server.configCommand.getAbout() + const data = await server.config.getAbout() expect(data.instance.name).to.equal('PeerTube updated') expect(data.instance.shortDescription).to.equal('my short description') @@ -486,9 +486,9 @@ describe('Test config', function () { it('Should remove the custom configuration', async function () { this.timeout(10000) - await server.configCommand.deleteCustomConfig() + await server.config.deleteCustomConfig() - const data = await server.configCommand.getCustomConfig() + const data = await server.config.getCustomConfig() checkInitialConfig(server, data) }) diff --git a/server/tests/api/server/contact-form.ts b/server/tests/api/server/contact-form.ts index 79c4c6748..353fed80a 100644 --- a/server/tests/api/server/contact-form.ts +++ b/server/tests/api/server/contact-form.ts @@ -27,7 +27,7 @@ describe('Test contact form', function () { server = await flushAndRunServer(1, overrideConfig) await setAccessTokensToServers([ server ]) - command = server.contactFormCommand + command = server.contactForm }) it('Should send a contact form', async function () { diff --git a/server/tests/api/server/email.ts b/server/tests/api/server/email.ts index aeda5fddb..258e835e7 100644 --- a/server/tests/api/server/email.ts +++ b/server/tests/api/server/email.ts @@ -43,15 +43,15 @@ describe('Test emails', function () { await setAccessTokensToServers([ server ]) { - const created = await server.usersCommand.create({ username: user.username, password: user.password }) + const created = await server.users.create({ username: user.username, password: user.password }) userId = created.id - userAccessToken = await server.loginCommand.getAccessToken(user) + userAccessToken = await server.login.getAccessToken(user) } { const attributes = { name: 'my super user video' } - const { uuid } = await server.videosCommand.upload({ token: userAccessToken, attributes }) + const { uuid } = await server.videos.upload({ token: userAccessToken, attributes }) videoUserUUID = uuid } @@ -59,7 +59,7 @@ describe('Test emails', function () { const attributes = { name: 'my super name' } - const { uuid, id } = await server.videosCommand.upload({ attributes }) + const { uuid, id } = await server.videos.upload({ attributes }) videoUUID = uuid videoId = id } @@ -70,7 +70,7 @@ describe('Test emails', function () { it('Should ask to reset the password', async function () { this.timeout(10000) - await server.usersCommand.askResetPassword({ email: 'user_1@example.com' }) + await server.users.askResetPassword({ email: 'user_1@example.com' }) await waitJobs(server) expect(emails).to.have.lengthOf(1) @@ -96,7 +96,7 @@ describe('Test emails', function () { }) it('Should not reset the password with an invalid verification string', async function () { - await server.usersCommand.resetPassword({ + await server.users.resetPassword({ userId, verificationString: verificationString + 'b', password: 'super_password2', @@ -105,11 +105,11 @@ describe('Test emails', function () { }) it('Should reset the password', async function () { - await server.usersCommand.resetPassword({ userId, verificationString, password: 'super_password2' }) + await server.users.resetPassword({ userId, verificationString, password: 'super_password2' }) }) it('Should not reset the password with the same verification string', async function () { - await server.usersCommand.resetPassword({ + await server.users.resetPassword({ userId, verificationString, password: 'super_password3', @@ -120,7 +120,7 @@ describe('Test emails', function () { it('Should login with this new password', async function () { user.password = 'super_password2' - await server.loginCommand.getAccessToken(user) + await server.login.getAccessToken(user) }) }) @@ -129,7 +129,7 @@ describe('Test emails', function () { it('Should send a create password email', async function () { this.timeout(10000) - await server.usersCommand.create({ username: 'create_password', password: '' }) + await server.users.create({ username: 'create_password', password: '' }) await waitJobs(server) expect(emails).to.have.lengthOf(2) @@ -155,7 +155,7 @@ describe('Test emails', function () { }) it('Should not reset the password with an invalid verification string', async function () { - await server.usersCommand.resetPassword({ + await server.users.resetPassword({ userId: userId2, verificationString: verificationString2 + 'c', password: 'newly_created_password', @@ -164,7 +164,7 @@ describe('Test emails', function () { }) it('Should reset the password', async function () { - await server.usersCommand.resetPassword({ + await server.users.resetPassword({ userId: userId2, verificationString: verificationString2, password: 'newly_created_password' @@ -172,7 +172,7 @@ describe('Test emails', function () { }) it('Should login with this new password', async function () { - await server.loginCommand.getAccessToken({ + await server.login.getAccessToken({ username: 'create_password', password: 'newly_created_password' }) @@ -184,7 +184,7 @@ describe('Test emails', function () { this.timeout(10000) const reason = 'my super bad reason' - await server.abusesCommand.report({ videoId, reason }) + await server.abuses.report({ videoId, reason }) await waitJobs(server) expect(emails).to.have.lengthOf(3) @@ -205,7 +205,7 @@ describe('Test emails', function () { this.timeout(10000) const reason = 'my super bad reason' - await server.usersCommand.banUser({ userId, reason }) + await server.users.banUser({ userId, reason }) await waitJobs(server) expect(emails).to.have.lengthOf(4) @@ -223,7 +223,7 @@ describe('Test emails', function () { it('Should send the notification email when unblocking a user', async function () { this.timeout(10000) - await server.usersCommand.unbanUser({ userId }) + await server.users.unbanUser({ userId }) await waitJobs(server) expect(emails).to.have.lengthOf(5) @@ -243,7 +243,7 @@ describe('Test emails', function () { this.timeout(10000) const reason = 'my super reason' - await server.blacklistCommand.add({ videoId: videoUserUUID, reason }) + await server.blacklist.add({ videoId: videoUserUUID, reason }) await waitJobs(server) expect(emails).to.have.lengthOf(6) @@ -261,7 +261,7 @@ describe('Test emails', function () { it('Should send the notification email', async function () { this.timeout(10000) - await server.blacklistCommand.remove({ videoId: videoUserUUID }) + await server.blacklist.remove({ videoId: videoUserUUID }) await waitJobs(server) expect(emails).to.have.lengthOf(7) @@ -286,7 +286,7 @@ describe('Test emails', function () { it('Should ask to send the verification email', async function () { this.timeout(10000) - await server.usersCommand.askSendVerifyEmail({ email: 'user_1@example.com' }) + await server.users.askSendVerifyEmail({ email: 'user_1@example.com' }) await waitJobs(server) expect(emails).to.have.lengthOf(8) @@ -312,7 +312,7 @@ describe('Test emails', function () { }) it('Should not verify the email with an invalid verification string', async function () { - await server.usersCommand.verifyEmail({ + await server.users.verifyEmail({ userId, verificationString: verificationString + 'b', isPendingEmail: false, @@ -321,7 +321,7 @@ describe('Test emails', function () { }) it('Should verify the email', async function () { - await server.usersCommand.verifyEmail({ userId, verificationString }) + await server.users.verifyEmail({ userId, verificationString }) }) }) diff --git a/server/tests/api/server/follow-constraints.ts b/server/tests/api/server/follow-constraints.ts index f9014aeee..887e400e9 100644 --- a/server/tests/api/server/follow-constraints.ts +++ b/server/tests/api/server/follow-constraints.ts @@ -23,11 +23,11 @@ describe('Test follow constraints', function () { await setAccessTokensToServers(servers) { - const { uuid } = await servers[0].videosCommand.upload({ attributes: { name: 'video server 1' } }) + const { uuid } = await servers[0].videos.upload({ attributes: { name: 'video server 1' } }) video1UUID = uuid } { - const { uuid } = await servers[1].videosCommand.upload({ attributes: { name: 'video server 2' } }) + const { uuid } = await servers[1].videos.upload({ attributes: { name: 'video server 2' } }) video2UUID = uuid } @@ -35,8 +35,8 @@ describe('Test follow constraints', function () { username: 'user1', password: 'super_password' } - await servers[0].usersCommand.create({ username: user.username, password: user.password }) - userToken = await servers[0].loginCommand.getAccessToken(user) + await servers[0].users.create({ username: user.username, password: user.password }) + userToken = await servers[0].login.getAccessToken(user) await doubleFollow(servers[0], servers[1]) }) @@ -46,22 +46,22 @@ describe('Test follow constraints', function () { describe('With an unlogged user', function () { it('Should get the local video', async function () { - await servers[0].videosCommand.get({ id: video1UUID }) + await servers[0].videos.get({ id: video1UUID }) }) it('Should get the remote video', async function () { - await servers[0].videosCommand.get({ id: video2UUID }) + await servers[0].videos.get({ id: video2UUID }) }) it('Should list local account videos', async function () { - const { total, data } = await servers[0].videosCommand.listByAccount({ accountName: 'root@localhost:' + servers[0].port }) + const { total, data } = await servers[0].videos.listByAccount({ accountName: 'root@localhost:' + servers[0].port }) expect(total).to.equal(1) expect(data).to.have.lengthOf(1) }) it('Should list remote account videos', async function () { - const { total, data } = await servers[0].videosCommand.listByAccount({ accountName: 'root@localhost:' + servers[1].port }) + const { total, data } = await servers[0].videos.listByAccount({ accountName: 'root@localhost:' + servers[1].port }) expect(total).to.equal(1) expect(data).to.have.lengthOf(1) @@ -69,7 +69,7 @@ describe('Test follow constraints', function () { it('Should list local channel videos', async function () { const videoChannelName = 'root_channel@localhost:' + servers[0].port - const { total, data } = await servers[0].videosCommand.listByChannel({ videoChannelName }) + const { total, data } = await servers[0].videos.listByChannel({ videoChannelName }) expect(total).to.equal(1) expect(data).to.have.lengthOf(1) @@ -77,7 +77,7 @@ describe('Test follow constraints', function () { it('Should list remote channel videos', async function () { const videoChannelName = 'root_channel@localhost:' + servers[1].port - const { total, data } = await servers[0].videosCommand.listByChannel({ videoChannelName }) + const { total, data } = await servers[0].videos.listByChannel({ videoChannelName }) expect(total).to.equal(1) expect(data).to.have.lengthOf(1) @@ -86,22 +86,22 @@ describe('Test follow constraints', function () { describe('With a logged user', function () { it('Should get the local video', async function () { - await servers[0].videosCommand.getWithToken({ token: userToken, id: video1UUID }) + await servers[0].videos.getWithToken({ token: userToken, id: video1UUID }) }) it('Should get the remote video', async function () { - await servers[0].videosCommand.getWithToken({ token: userToken, id: video2UUID }) + await servers[0].videos.getWithToken({ token: userToken, id: video2UUID }) }) it('Should list local account videos', async function () { - const { total, data } = await servers[0].videosCommand.listByAccount({ token: userToken, accountName: 'root@localhost:' + servers[0].port }) + const { total, data } = await servers[0].videos.listByAccount({ token: userToken, accountName: 'root@localhost:' + servers[0].port }) expect(total).to.equal(1) expect(data).to.have.lengthOf(1) }) it('Should list remote account videos', async function () { - const { total, data } = await servers[0].videosCommand.listByAccount({ token: userToken, accountName: 'root@localhost:' + servers[1].port }) + const { total, data } = await servers[0].videos.listByAccount({ token: userToken, accountName: 'root@localhost:' + servers[1].port }) expect(total).to.equal(1) expect(data).to.have.lengthOf(1) @@ -109,7 +109,7 @@ describe('Test follow constraints', function () { it('Should list local channel videos', async function () { const videoChannelName = 'root_channel@localhost:' + servers[0].port - const { total, data } = await servers[0].videosCommand.listByChannel({ token: userToken, videoChannelName }) + const { total, data } = await servers[0].videos.listByChannel({ token: userToken, videoChannelName }) expect(total).to.equal(1) expect(data).to.have.lengthOf(1) @@ -117,7 +117,7 @@ describe('Test follow constraints', function () { it('Should list remote channel videos', async function () { const videoChannelName = 'root_channel@localhost:' + servers[1].port - const { total, data } = await servers[0].videosCommand.listByChannel({ token: userToken, videoChannelName }) + const { total, data } = await servers[0].videos.listByChannel({ token: userToken, videoChannelName }) expect(total).to.equal(1) expect(data).to.have.lengthOf(1) @@ -130,17 +130,17 @@ describe('Test follow constraints', function () { before(async function () { this.timeout(30000) - await servers[0].followsCommand.unfollow({ target: servers[1] }) + await servers[0].follows.unfollow({ target: servers[1] }) }) describe('With an unlogged user', function () { it('Should get the local video', async function () { - await servers[0].videosCommand.get({ id: video1UUID }) + await servers[0].videos.get({ id: video1UUID }) }) it('Should not get the remote video', async function () { - const body = await servers[0].videosCommand.get({ id: video2UUID, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) + const body = await servers[0].videos.get({ id: video2UUID, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) const error = body as unknown as PeerTubeProblemDocument const doc = 'https://docs.joinpeertube.org/api-rest-reference.html#section/Errors/does_not_respect_follow_constraints' @@ -156,7 +156,7 @@ describe('Test follow constraints', function () { }) it('Should list local account videos', async function () { - const { total, data } = await servers[0].videosCommand.listByAccount({ + const { total, data } = await servers[0].videos.listByAccount({ token: undefined, accountName: 'root@localhost:' + servers[0].port }) @@ -166,7 +166,7 @@ describe('Test follow constraints', function () { }) it('Should not list remote account videos', async function () { - const { total, data } = await servers[0].videosCommand.listByAccount({ + const { total, data } = await servers[0].videos.listByAccount({ token: undefined, accountName: 'root@localhost:' + servers[1].port }) @@ -177,7 +177,7 @@ describe('Test follow constraints', function () { it('Should list local channel videos', async function () { const videoChannelName = 'root_channel@localhost:' + servers[0].port - const { total, data } = await servers[0].videosCommand.listByChannel({ token: undefined, videoChannelName }) + const { total, data } = await servers[0].videos.listByChannel({ token: undefined, videoChannelName }) expect(total).to.equal(1) expect(data).to.have.lengthOf(1) @@ -185,7 +185,7 @@ describe('Test follow constraints', function () { it('Should not list remote channel videos', async function () { const videoChannelName = 'root_channel@localhost:' + servers[1].port - const { total, data } = await servers[0].videosCommand.listByChannel({ token: undefined, videoChannelName }) + const { total, data } = await servers[0].videos.listByChannel({ token: undefined, videoChannelName }) expect(total).to.equal(0) expect(data).to.have.lengthOf(0) @@ -194,22 +194,22 @@ describe('Test follow constraints', function () { describe('With a logged user', function () { it('Should get the local video', async function () { - await servers[0].videosCommand.getWithToken({ token: userToken, id: video1UUID }) + await servers[0].videos.getWithToken({ token: userToken, id: video1UUID }) }) it('Should get the remote video', async function () { - await servers[0].videosCommand.getWithToken({ token: userToken, id: video2UUID }) + await servers[0].videos.getWithToken({ token: userToken, id: video2UUID }) }) it('Should list local account videos', async function () { - const { total, data } = await servers[0].videosCommand.listByAccount({ token: userToken, accountName: 'root@localhost:' + servers[0].port }) + const { total, data } = await servers[0].videos.listByAccount({ token: userToken, accountName: 'root@localhost:' + servers[0].port }) expect(total).to.equal(1) expect(data).to.have.lengthOf(1) }) it('Should list remote account videos', async function () { - const { total, data } = await servers[0].videosCommand.listByAccount({ token: userToken, accountName: 'root@localhost:' + servers[1].port }) + const { total, data } = await servers[0].videos.listByAccount({ token: userToken, accountName: 'root@localhost:' + servers[1].port }) expect(total).to.equal(1) expect(data).to.have.lengthOf(1) @@ -217,7 +217,7 @@ describe('Test follow constraints', function () { it('Should list local channel videos', async function () { const videoChannelName = 'root_channel@localhost:' + servers[0].port - const { total, data } = await servers[0].videosCommand.listByChannel({ token: userToken, videoChannelName }) + const { total, data } = await servers[0].videos.listByChannel({ token: userToken, videoChannelName }) expect(total).to.equal(1) expect(data).to.have.lengthOf(1) @@ -225,7 +225,7 @@ describe('Test follow constraints', function () { it('Should list remote channel videos', async function () { const videoChannelName = 'root_channel@localhost:' + servers[1].port - const { total, data } = await servers[0].videosCommand.listByChannel({ token: userToken, videoChannelName }) + const { total, data } = await servers[0].videos.listByChannel({ token: userToken, videoChannelName }) expect(total).to.equal(1) expect(data).to.have.lengthOf(1) diff --git a/server/tests/api/server/follows-moderation.ts b/server/tests/api/server/follows-moderation.ts index 6d6eca9a8..045024544 100644 --- a/server/tests/api/server/follows-moderation.ts +++ b/server/tests/api/server/follows-moderation.ts @@ -15,8 +15,8 @@ const expect = chai.expect async function checkServer1And2HasFollowers (servers: ServerInfo[], state = 'accepted') { const fns = [ - servers[0].followsCommand.getFollowings.bind(servers[0].followsCommand), - servers[1].followsCommand.getFollowers.bind(servers[1].followsCommand) + servers[0].follows.getFollowings.bind(servers[0].follows), + servers[1].follows.getFollowers.bind(servers[1].follows) ] for (const fn of fns) { @@ -32,8 +32,8 @@ async function checkServer1And2HasFollowers (servers: ServerInfo[], state = 'acc async function checkNoFollowers (servers: ServerInfo[]) { const fns = [ - servers[0].followsCommand.getFollowings.bind(servers[0].followsCommand), - servers[1].followsCommand.getFollowers.bind(servers[1].followsCommand) + servers[0].follows.getFollowings.bind(servers[0].follows), + servers[1].follows.getFollowers.bind(servers[1].follows) ] for (const fn of fns) { @@ -54,7 +54,7 @@ describe('Test follows moderation', function () { // Get the access tokens await setAccessTokensToServers(servers) - commands = servers.map(s => s.followsCommand) + commands = servers.map(s => s.follows) }) it('Should have server 1 following server 2', async function () { @@ -93,7 +93,7 @@ describe('Test follows moderation', function () { } } - await servers[1].configCommand.updateCustomSubConfig({ newConfig: subConfig }) + await servers[1].config.updateCustomSubConfig({ newConfig: subConfig }) await commands[0].follow({ targets: [ servers[1].url ] }) await waitJobs(servers) @@ -113,7 +113,7 @@ describe('Test follows moderation', function () { } } - await servers[1].configCommand.updateCustomSubConfig({ newConfig: subConfig }) + await servers[1].config.updateCustomSubConfig({ newConfig: subConfig }) await commands[0].follow({ targets: [ servers[1].url ] }) await waitJobs(servers) @@ -136,8 +136,8 @@ describe('Test follows moderation', function () { } } - await servers[1].configCommand.updateCustomSubConfig({ newConfig: subConfig }) - await servers[2].configCommand.updateCustomSubConfig({ newConfig: subConfig }) + await servers[1].config.updateCustomSubConfig({ newConfig: subConfig }) + await servers[2].config.updateCustomSubConfig({ newConfig: subConfig }) await commands[0].follow({ targets: [ servers[1].url ] }) await waitJobs(servers) diff --git a/server/tests/api/server/follows.ts b/server/tests/api/server/follows.ts index 5ce8938fa..d43064689 100644 --- a/server/tests/api/server/follows.ts +++ b/server/tests/api/server/follows.ts @@ -26,7 +26,7 @@ describe('Test follows', function () { this.timeout(30000) servers = await flushAndRunMultipleServers(3) - followsCommands = servers.map(s => s.followsCommand) + followsCommands = servers.map(s => s.follows) // Get the access tokens await setAccessTokensToServers(servers) @@ -34,7 +34,7 @@ describe('Test follows', function () { it('Should not have followers', async function () { for (const server of servers) { - const body = await server.followsCommand.getFollowers({ start: 0, count: 5, sort: 'createdAt' }) + const body = await server.follows.getFollowers({ start: 0, count: 5, sort: 'createdAt' }) expect(body.total).to.equal(0) const follows = body.data @@ -45,7 +45,7 @@ describe('Test follows', function () { it('Should not have following', async function () { for (const server of servers) { - const body = await server.followsCommand.getFollowings({ start: 0, count: 5, sort: 'createdAt' }) + const body = await server.follows.getFollowings({ start: 0, count: 5, sort: 'createdAt' }) expect(body.total).to.equal(0) const follows = body.data @@ -141,7 +141,7 @@ describe('Test follows', function () { it('Should have 0 followings on server 2 and 3', async function () { for (const server of [ servers[1], servers[2] ]) { - const body = await server.followsCommand.getFollowings({ start: 0, count: 5, sort: 'createdAt' }) + const body = await server.follows.getFollowings({ start: 0, count: 5, sort: 'createdAt' }) expect(body.total).to.equal(0) const follows = body.data @@ -152,7 +152,7 @@ describe('Test follows', function () { it('Should have 1 followers on server 2 and 3', async function () { for (const server of [ servers[1], servers[2] ]) { - const body = await server.followsCommand.getFollowers({ start: 0, count: 1, sort: 'createdAt' }) + const body = await server.follows.getFollowers({ start: 0, count: 1, sort: 'createdAt' }) expect(body.total).to.equal(1) const follows = body.data @@ -284,25 +284,25 @@ describe('Test follows', function () { it('Should upload a video on server 2 and 3 and propagate only the video of server 2', async function () { this.timeout(60000) - await servers[1].videosCommand.upload({ attributes: { name: 'server2' } }) - await servers[2].videosCommand.upload({ attributes: { name: 'server3' } }) + await servers[1].videos.upload({ attributes: { name: 'server2' } }) + await servers[2].videos.upload({ attributes: { name: 'server3' } }) await waitJobs(servers) { - const { total, data } = await servers[0].videosCommand.list() + const { total, data } = await servers[0].videos.list() expect(total).to.equal(1) expect(data[0].name).to.equal('server2') } { - const { total, data } = await servers[1].videosCommand.list() + const { total, data } = await servers[1].videos.list() expect(total).to.equal(1) expect(data[0].name).to.equal('server2') } { - const { total, data } = await servers[2].videosCommand.list() + const { total, data } = await servers[2].videos.list() expect(total).to.equal(1) expect(data[0].name).to.equal('server3') } @@ -322,60 +322,60 @@ describe('Test follows', function () { tags: [ 'tag1', 'tag2', 'tag3' ] } - await servers[2].videosCommand.upload({ attributes: { name: 'server3-2' } }) - await servers[2].videosCommand.upload({ attributes: { name: 'server3-3' } }) - await servers[2].videosCommand.upload({ attributes: video4Attributes }) - await servers[2].videosCommand.upload({ attributes: { name: 'server3-5' } }) - await servers[2].videosCommand.upload({ attributes: { name: 'server3-6' } }) + await servers[2].videos.upload({ attributes: { name: 'server3-2' } }) + await servers[2].videos.upload({ attributes: { name: 'server3-3' } }) + await servers[2].videos.upload({ attributes: video4Attributes }) + await servers[2].videos.upload({ attributes: { name: 'server3-5' } }) + await servers[2].videos.upload({ attributes: { name: 'server3-6' } }) { - const userAccessToken = await servers[2].usersCommand.generateUserAndToken('captain') + const userAccessToken = await servers[2].users.generateUserAndToken('captain') - const { data } = await servers[2].videosCommand.list() + const { data } = await servers[2].videos.list() video4 = data.find(v => v.name === 'server3-4') { - await servers[2].videosCommand.rate({ id: video4.id, rating: 'like' }) - await servers[2].videosCommand.rate({ token: userAccessToken, id: video4.id, rating: 'dislike' }) + await servers[2].videos.rate({ id: video4.id, rating: 'like' }) + await servers[2].videos.rate({ token: userAccessToken, id: video4.id, rating: 'dislike' }) } { { const text = 'my super first comment' - const created = await servers[2].commentsCommand.createThread({ videoId: video4.id, text }) + const created = await servers[2].comments.createThread({ videoId: video4.id, text }) const threadId = created.id const text1 = 'my super answer to thread 1' - const childComment = await servers[2].commentsCommand.addReply({ videoId: video4.id, toCommentId: threadId, text: text1 }) + const childComment = await servers[2].comments.addReply({ videoId: video4.id, toCommentId: threadId, text: text1 }) const text2 = 'my super answer to answer of thread 1' - await servers[2].commentsCommand.addReply({ videoId: video4.id, toCommentId: childComment.id, text: text2 }) + await servers[2].comments.addReply({ videoId: video4.id, toCommentId: childComment.id, text: text2 }) const text3 = 'my second answer to thread 1' - await servers[2].commentsCommand.addReply({ videoId: video4.id, toCommentId: threadId, text: text3 }) + await servers[2].comments.addReply({ videoId: video4.id, toCommentId: threadId, text: text3 }) } { const text = 'will be deleted' - const created = await servers[2].commentsCommand.createThread({ videoId: video4.id, text }) + const created = await servers[2].comments.createThread({ videoId: video4.id, text }) const threadId = created.id const text1 = 'answer to deleted' - await servers[2].commentsCommand.addReply({ videoId: video4.id, toCommentId: threadId, text: text1 }) + await servers[2].comments.addReply({ videoId: video4.id, toCommentId: threadId, text: text1 }) const text2 = 'will also be deleted' - const childComment = await servers[2].commentsCommand.addReply({ videoId: video4.id, toCommentId: threadId, text: text2 }) + const childComment = await servers[2].comments.addReply({ videoId: video4.id, toCommentId: threadId, text: text2 }) const text3 = 'my second answer to deleted' - await servers[2].commentsCommand.addReply({ videoId: video4.id, toCommentId: childComment.id, text: text3 }) + await servers[2].comments.addReply({ videoId: video4.id, toCommentId: childComment.id, text: text3 }) - await servers[2].commentsCommand.delete({ videoId: video4.id, commentId: threadId }) - await servers[2].commentsCommand.delete({ videoId: video4.id, commentId: childComment.id }) + await servers[2].comments.delete({ videoId: video4.id, commentId: threadId }) + await servers[2].comments.delete({ videoId: video4.id, commentId: childComment.id }) } } { - await servers[2].captionsCommand.createVideoCaption({ + await servers[2].captions.createVideoCaption({ language: 'ar', videoId: video4.id, fixture: 'subtitle-good2.vtt' @@ -404,7 +404,7 @@ describe('Test follows', function () { }) it('Should have propagated videos', async function () { - const { total, data } = await servers[0].videosCommand.list() + const { total, data } = await servers[0].videos.list() expect(total).to.equal(7) const video2 = data.find(v => v.name === 'server3-2') @@ -454,7 +454,7 @@ describe('Test follows', function () { }) it('Should have propagated comments', async function () { - const { total, data } = await servers[0].commentsCommand.listThreads({ videoId: video4.id, sort: 'createdAt' }) + const { total, data } = await servers[0].comments.listThreads({ videoId: video4.id, sort: 'createdAt' }) expect(total).to.equal(2) expect(data).to.be.an('array') @@ -474,7 +474,7 @@ describe('Test follows', function () { const threadId = comment.threadId - const tree = await servers[0].commentsCommand.getThread({ videoId: video4.id, threadId }) + const tree = await servers[0].comments.getThread({ videoId: video4.id, threadId }) expect(tree.comment.text).equal('my super first comment') expect(tree.children).to.have.lengthOf(2) @@ -502,7 +502,7 @@ describe('Test follows', function () { expect(deletedComment.totalReplies).to.equal(2) expect(dateIsValid(deletedComment.deletedAt as string)).to.be.true - const tree = await servers[0].commentsCommand.getThread({ videoId: video4.id, threadId: deletedComment.threadId }) + const tree = await servers[0].comments.getThread({ videoId: video4.id, threadId: deletedComment.threadId }) const [ commentRoot, deletedChildRoot ] = tree.children expect(deletedChildRoot).to.not.be.undefined @@ -527,7 +527,7 @@ describe('Test follows', function () { }) it('Should have propagated captions', async function () { - const body = await servers[0].captionsCommand.listVideoCaptions({ videoId: video4.id }) + const body = await servers[0].captions.listVideoCaptions({ videoId: video4.id }) expect(body.total).to.equal(1) expect(body.data).to.have.lengthOf(1) @@ -545,7 +545,7 @@ describe('Test follows', function () { await waitJobs(servers) - const { total } = await servers[0].videosCommand.list() + const { total } = await servers[0].videos.list() expect(total).to.equal(1) }) diff --git a/server/tests/api/server/handle-down.ts b/server/tests/api/server/handle-down.ts index 35b905a8c..de3dee826 100644 --- a/server/tests/api/server/handle-down.ts +++ b/server/tests/api/server/handle-down.ts @@ -55,7 +55,7 @@ describe('Test handle downs', function () { this.timeout(30000) servers = await flushAndRunMultipleServers(3) - commentCommands = servers.map(s => s.commentsCommand) + commentCommands = servers.map(s => s.comments) checkAttributes = { name: 'my super name for server 1', @@ -99,19 +99,19 @@ describe('Test handle downs', function () { this.timeout(240000) // Server 2 and 3 follow server 1 - await servers[1].followsCommand.follow({ targets: [ servers[0].url ] }) - await servers[2].followsCommand.follow({ targets: [ servers[0].url ] }) + await servers[1].follows.follow({ targets: [ servers[0].url ] }) + await servers[2].follows.follow({ targets: [ servers[0].url ] }) await waitJobs(servers) // Upload a video to server 1 - await servers[0].videosCommand.upload({ attributes: videoAttributes }) + await servers[0].videos.upload({ attributes: videoAttributes }) await waitJobs(servers) // And check all servers have this video for (const server of servers) { - const { data } = await server.videosCommand.list() + const { data } = await server.videos.list() expect(data).to.be.an('array') expect(data).to.have.lengthOf(1) } @@ -121,7 +121,7 @@ describe('Test handle downs', function () { // Remove server 2 follower for (let i = 0; i < 10; i++) { - await servers[0].videosCommand.upload({ attributes: videoAttributes }) + await servers[0].videos.upload({ attributes: videoAttributes }) } await waitJobs([ servers[0], servers[2] ]) @@ -129,12 +129,12 @@ describe('Test handle downs', function () { // Kill server 3 await killallServers([ servers[2] ]) - missedVideo1 = await servers[0].videosCommand.upload({ attributes: videoAttributes }) + missedVideo1 = await servers[0].videos.upload({ attributes: videoAttributes }) - missedVideo2 = await servers[0].videosCommand.upload({ attributes: videoAttributes }) + missedVideo2 = await servers[0].videos.upload({ attributes: videoAttributes }) // Unlisted video - unlistedVideo = await servers[0].videosCommand.upload({ attributes: unlistedVideoAttributes }) + unlistedVideo = await servers[0].videos.upload({ attributes: unlistedVideoAttributes }) // Add comments to video 2 { @@ -153,7 +153,7 @@ describe('Test handle downs', function () { await wait(11000) // Only server 3 is still a follower of server 1 - const body = await servers[0].followsCommand.getFollowers({ start: 0, count: 2, sort: 'createdAt' }) + const body = await servers[0].follows.getFollowers({ start: 0, count: 2, sort: 'createdAt' }) expect(body.data).to.be.an('array') expect(body.data).to.have.lengthOf(1) expect(body.data[0].follower.host).to.equal('localhost:' + servers[2].port) @@ -163,7 +163,7 @@ describe('Test handle downs', function () { const states: JobState[] = [ 'waiting', 'active' ] for (const state of states) { - const body = await servers[0].jobsCommand.getJobsList({ + const body = await servers[0].jobs.getJobsList({ state: state, start: 0, count: 50, @@ -179,14 +179,14 @@ describe('Test handle downs', function () { await reRunServer(servers[1]) await reRunServer(servers[2]) - await servers[1].followsCommand.unfollow({ target: servers[0] }) + await servers[1].follows.unfollow({ target: servers[0] }) await waitJobs(servers) - await servers[1].followsCommand.follow({ targets: [ servers[0].url ] }) + await servers[1].follows.follow({ targets: [ servers[0].url ] }) await waitJobs(servers) - const body = await servers[0].followsCommand.getFollowers({ start: 0, count: 2, sort: 'createdAt' }) + const body = await servers[0].follows.getFollowers({ start: 0, count: 2, sort: 'createdAt' }) expect(body.data).to.be.an('array') expect(body.data).to.have.lengthOf(2) }) @@ -195,25 +195,25 @@ describe('Test handle downs', function () { this.timeout(15000) { - const { data } = await servers[2].videosCommand.list() + const { data } = await servers[2].videos.list() expect(data).to.be.an('array') expect(data).to.have.lengthOf(11) } - await servers[0].videosCommand.update({ id: missedVideo1.uuid }) - await servers[0].videosCommand.update({ id: unlistedVideo.uuid }) + await servers[0].videos.update({ id: missedVideo1.uuid }) + await servers[0].videos.update({ id: unlistedVideo.uuid }) await waitJobs(servers) { - const { data } = await servers[2].videosCommand.list() + const { data } = await servers[2].videos.list() expect(data).to.be.an('array') // 1 video is unlisted expect(data).to.have.lengthOf(12) } // Check unlisted video - const video = await servers[2].videosCommand.get({ id: unlistedVideo.uuid }) + const video = await servers[2].videos.get({ id: unlistedVideo.uuid }) await completeVideoCheck(servers[2], video, unlistedCheckAttributes) }) @@ -224,16 +224,16 @@ describe('Test handle downs', function () { await waitJobs(servers) - await servers[2].videosCommand.get({ id: missedVideo2.uuid }) + await servers[2].videos.get({ id: missedVideo2.uuid }) { - const { data } = await servers[2].commentsCommand.listThreads({ videoId: missedVideo2.uuid }) + const { data } = await servers[2].comments.listThreads({ videoId: missedVideo2.uuid }) expect(data).to.be.an('array') expect(data).to.have.lengthOf(1) threadIdServer2 = data[0].id - const tree = await servers[2].commentsCommand.getThread({ videoId: missedVideo2.uuid, threadId: threadIdServer2 }) + const tree = await servers[2].comments.getThread({ videoId: missedVideo2.uuid, threadId: threadIdServer2 }) expect(tree.comment.text).equal('thread 1') expect(tree.children).to.have.lengthOf(1) @@ -256,7 +256,7 @@ describe('Test handle downs', function () { it('Should correctly reply to the comment', async function () { this.timeout(15000) - await servers[2].commentsCommand.addReply({ videoId: missedVideo2.uuid, toCommentId: commentIdServer2, text: 'comment 1-4' }) + await servers[2].comments.addReply({ videoId: missedVideo2.uuid, toCommentId: commentIdServer2, text: 'comment 1-4' }) await waitJobs(servers) @@ -286,24 +286,24 @@ describe('Test handle downs', function () { this.timeout(120000) for (let i = 0; i < 10; i++) { - const uuid = (await servers[0].videosCommand.quickUpload({ name: 'video ' + i })).uuid + const uuid = (await servers[0].videos.quickUpload({ name: 'video ' + i })).uuid videoIdsServer1.push(uuid) } await waitJobs(servers) for (const id of videoIdsServer1) { - await servers[1].videosCommand.get({ id }) + await servers[1].videos.get({ id }) } await waitJobs(servers) - await servers[1].sqlCommand.setActorFollowScores(20) + await servers[1].sql.setActorFollowScores(20) // Wait video expiration await wait(11000) // Refresh video -> score + 10 = 30 - await servers[1].videosCommand.get({ id: videoIdsServer1[0] }) + await servers[1].videos.get({ id: videoIdsServer1[0] }) await waitJobs(servers) }) @@ -318,14 +318,14 @@ describe('Test handle downs', function () { for (let i = 0; i < 5; i++) { try { - await servers[1].videosCommand.get({ id: videoIdsServer1[i] }) + await servers[1].videos.get({ id: videoIdsServer1[i] }) await waitJobs([ servers[1] ]) await wait(1500) } catch {} } for (const id of videoIdsServer1) { - await servers[1].videosCommand.get({ id, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) + await servers[1].videos.get({ id, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) } }) diff --git a/server/tests/api/server/homepage.ts b/server/tests/api/server/homepage.ts index 18b9edc31..aac075321 100644 --- a/server/tests/api/server/homepage.ts +++ b/server/tests/api/server/homepage.ts @@ -16,7 +16,7 @@ import { const expect = chai.expect async function getHomepageState (server: ServerInfo) { - const config = await server.configCommand.getConfig() + const config = await server.config.getConfig() return config.homepage.enabled } @@ -31,7 +31,7 @@ describe('Test instance homepage actions', function () { server = await flushAndRunServer(1) await setAccessTokensToServers([ server ]) - command = server.customPageCommand + command = server.customPage }) it('Should not have a homepage', async function () { diff --git a/server/tests/api/server/jobs.ts b/server/tests/api/server/jobs.ts index aa4c7587b..0c44e4dad 100644 --- a/server/tests/api/server/jobs.ts +++ b/server/tests/api/server/jobs.ts @@ -31,21 +31,21 @@ describe('Test jobs', function () { it('Should create some jobs', async function () { this.timeout(120000) - await servers[1].videosCommand.upload({ attributes: { name: 'video1' } }) - await servers[1].videosCommand.upload({ attributes: { name: 'video2' } }) + await servers[1].videos.upload({ attributes: { name: 'video1' } }) + await servers[1].videos.upload({ attributes: { name: 'video2' } }) await waitJobs(servers) }) it('Should list jobs', async function () { - const body = await servers[1].jobsCommand.getJobsList({ state: 'completed' }) + const body = await servers[1].jobs.getJobsList({ state: 'completed' }) expect(body.total).to.be.above(2) expect(body.data).to.have.length.above(2) }) it('Should list jobs with sort, pagination and job type', async function () { { - const body = await servers[1].jobsCommand.getJobsList({ + const body = await servers[1].jobs.getJobsList({ state: 'completed', start: 1, count: 2, @@ -66,7 +66,7 @@ describe('Test jobs', function () { } { - const body = await servers[1].jobsCommand.getJobsList({ + const body = await servers[1].jobs.getJobsList({ state: 'completed', start: 0, count: 100, @@ -82,7 +82,7 @@ describe('Test jobs', function () { }) it('Should list all jobs', async function () { - const body = await servers[1].jobsCommand.getJobsList() + const body = await servers[1].jobs.getJobsList() expect(body.total).to.be.above(2) const jobs = body.data diff --git a/server/tests/api/server/logs.ts b/server/tests/api/server/logs.ts index e7bef5a4a..2d141fd8c 100644 --- a/server/tests/api/server/logs.ts +++ b/server/tests/api/server/logs.ts @@ -25,7 +25,7 @@ describe('Test logs', function () { server = await flushAndRunServer(1) await setAccessTokensToServers([ server ]) - logsCommand = server.logsCommand + logsCommand = server.logs }) describe('With the standard log file', function () { @@ -33,12 +33,12 @@ describe('Test logs', function () { it('Should get logs with a start date', async function () { this.timeout(20000) - await server.videosCommand.upload({ attributes: { name: 'video 1' } }) + await server.videos.upload({ attributes: { name: 'video 1' } }) await waitJobs([ server ]) const now = new Date() - await server.videosCommand.upload({ attributes: { name: 'video 2' } }) + await server.videos.upload({ attributes: { name: 'video 2' } }) await waitJobs([ server ]) const body = await logsCommand.getLogs({ startDate: now }) @@ -51,17 +51,17 @@ describe('Test logs', function () { it('Should get logs with an end date', async function () { this.timeout(30000) - await server.videosCommand.upload({ attributes: { name: 'video 3' } }) + await server.videos.upload({ attributes: { name: 'video 3' } }) await waitJobs([ server ]) const now1 = new Date() - await server.videosCommand.upload({ attributes: { name: 'video 4' } }) + await server.videos.upload({ attributes: { name: 'video 4' } }) await waitJobs([ server ]) const now2 = new Date() - await server.videosCommand.upload({ attributes: { name: 'video 5' } }) + await server.videos.upload({ attributes: { name: 'video 5' } }) await waitJobs([ server ]) const body = await logsCommand.getLogs({ startDate: now1, endDate: now2 }) @@ -77,7 +77,7 @@ describe('Test logs', function () { const now = new Date() - await server.videosCommand.upload({ attributes: { name: 'video 6' } }) + await server.videos.upload({ attributes: { name: 'video 6' } }) await waitJobs([ server ]) { @@ -100,7 +100,7 @@ describe('Test logs', function () { const now = new Date() - await server.serversCommand.ping() + await server.servers.ping() const body = await logsCommand.getLogs({ startDate: now, level: 'info' }) const logsString = JSON.stringify(body) @@ -117,7 +117,7 @@ describe('Test logs', function () { const now = new Date() - await server.serversCommand.ping() + await server.servers.ping() const body = await logsCommand.getLogs({ startDate: now, level: 'info' }) const logsString = JSON.stringify(body) @@ -130,12 +130,12 @@ describe('Test logs', function () { it('Should get logs with a start date', async function () { this.timeout(20000) - await server.videosCommand.upload({ attributes: { name: 'video 7' } }) + await server.videos.upload({ attributes: { name: 'video 7' } }) await waitJobs([ server ]) const now = new Date() - await server.videosCommand.upload({ attributes: { name: 'video 8' } }) + await server.videos.upload({ attributes: { name: 'video 8' } }) await waitJobs([ server ]) const body = await logsCommand.getAuditLogs({ startDate: now }) @@ -156,17 +156,17 @@ describe('Test logs', function () { it('Should get logs with an end date', async function () { this.timeout(30000) - await server.videosCommand.upload({ attributes: { name: 'video 9' } }) + await server.videos.upload({ attributes: { name: 'video 9' } }) await waitJobs([ server ]) const now1 = new Date() - await server.videosCommand.upload({ attributes: { name: 'video 10' } }) + await server.videos.upload({ attributes: { name: 'video 10' } }) await waitJobs([ server ]) const now2 = new Date() - await server.videosCommand.upload({ attributes: { name: 'video 11' } }) + await server.videos.upload({ attributes: { name: 'video 11' } }) await waitJobs([ server ]) const body = await logsCommand.getAuditLogs({ startDate: now1, endDate: now2 }) diff --git a/server/tests/api/server/plugins.ts b/server/tests/api/server/plugins.ts index 1fd5e613b..45a22e48d 100644 --- a/server/tests/api/server/plugins.ts +++ b/server/tests/api/server/plugins.ts @@ -33,7 +33,7 @@ describe('Test plugins', function () { server = await flushAndRunServer(1, configOverride) await setAccessTokensToServers([ server ]) - command = server.pluginsCommand + command = server.plugins }) it('Should list and search available plugins and themes', async function () { @@ -97,7 +97,7 @@ describe('Test plugins', function () { }) it('Should have the plugin loaded in the configuration', async function () { - const config = await server.configCommand.getConfig() + const config = await server.config.getConfig() const theme = config.theme.registered.find(r => r.name === 'background-red') expect(theme).to.not.be.undefined @@ -107,20 +107,20 @@ describe('Test plugins', function () { }) it('Should update the default theme in the configuration', async function () { - await server.configCommand.updateCustomSubConfig({ + await server.config.updateCustomSubConfig({ newConfig: { theme: { default: 'background-red' } } }) - const config = await server.configCommand.getConfig() + const config = await server.config.getConfig() expect(config.theme.default).to.equal('background-red') }) it('Should update my default theme', async function () { - await server.usersCommand.updateMe({ theme: 'background-red' }) + await server.users.updateMe({ theme: 'background-red' }) - const user = await server.usersCommand.getMyInfo() + const user = await server.users.getMyInfo() expect(user.theme).to.equal('background-red') }) @@ -187,7 +187,7 @@ describe('Test plugins', function () { it('Should have watched settings changes', async function () { this.timeout(10000) - await server.serversCommand.waitUntilLog('Settings changed!') + await server.servers.waitUntilLog('Settings changed!') }) it('Should get a plugin and a theme', async function () { @@ -234,7 +234,7 @@ describe('Test plugins', function () { await wait(6000) // Fake update our plugin version - await server.sqlCommand.setPluginVersion('hello-world', '0.0.1') + await server.sql.setPluginVersion('hello-world', '0.0.1') // Fake update package.json const packageJSON = await command.getPackageJSON('peertube-plugin-hello-world') @@ -293,7 +293,7 @@ describe('Test plugins', function () { }) it('Should have updated the configuration', async function () { - const config = await server.configCommand.getConfig() + const config = await server.config.getConfig() expect(config.theme.default).to.equal('default') @@ -305,7 +305,7 @@ describe('Test plugins', function () { }) it('Should have updated the user theme', async function () { - const user = await server.usersCommand.getMyInfo() + const user = await server.users.getMyInfo() expect(user.theme).to.equal('instance-default') }) diff --git a/server/tests/api/server/reverse-proxy.ts b/server/tests/api/server/reverse-proxy.ts index 5a6491430..de3cf02f2 100644 --- a/server/tests/api/server/reverse-proxy.ts +++ b/server/tests/api/server/reverse-proxy.ts @@ -33,59 +33,59 @@ describe('Test application behind a reverse proxy', function () { server = await flushAndRunServer(1, config) await setAccessTokensToServers([ server ]) - const { uuid } = await server.videosCommand.upload() + const { uuid } = await server.videos.upload() videoId = uuid }) it('Should view a video only once with the same IP by default', async function () { this.timeout(20000) - await server.videosCommand.view({ id: videoId }) - await server.videosCommand.view({ id: videoId }) + await server.videos.view({ id: videoId }) + await server.videos.view({ id: videoId }) // Wait the repeatable job await wait(8000) - const video = await server.videosCommand.get({ id: videoId }) + const video = await server.videos.get({ id: videoId }) expect(video.views).to.equal(1) }) it('Should view a video 2 times with the X-Forwarded-For header set', async function () { this.timeout(20000) - await server.videosCommand.view({ id: videoId, xForwardedFor: '0.0.0.1,127.0.0.1' }) - await server.videosCommand.view({ id: videoId, xForwardedFor: '0.0.0.2,127.0.0.1' }) + await server.videos.view({ id: videoId, xForwardedFor: '0.0.0.1,127.0.0.1' }) + await server.videos.view({ id: videoId, xForwardedFor: '0.0.0.2,127.0.0.1' }) // Wait the repeatable job await wait(8000) - const video = await server.videosCommand.get({ id: videoId }) + const video = await server.videos.get({ id: videoId }) expect(video.views).to.equal(3) }) it('Should view a video only once with the same client IP in the X-Forwarded-For header', async function () { this.timeout(20000) - await server.videosCommand.view({ id: videoId, xForwardedFor: '0.0.0.4,0.0.0.3,::ffff:127.0.0.1' }) - await server.videosCommand.view({ id: videoId, xForwardedFor: '0.0.0.5,0.0.0.3,127.0.0.1' }) + await server.videos.view({ id: videoId, xForwardedFor: '0.0.0.4,0.0.0.3,::ffff:127.0.0.1' }) + await server.videos.view({ id: videoId, xForwardedFor: '0.0.0.5,0.0.0.3,127.0.0.1' }) // Wait the repeatable job await wait(8000) - const video = await server.videosCommand.get({ id: videoId }) + const video = await server.videos.get({ id: videoId }) expect(video.views).to.equal(4) }) it('Should view a video two times with a different client IP in the X-Forwarded-For header', async function () { this.timeout(20000) - await server.videosCommand.view({ id: videoId, xForwardedFor: '0.0.0.8,0.0.0.6,127.0.0.1' }) - await server.videosCommand.view({ id: videoId, xForwardedFor: '0.0.0.8,0.0.0.7,127.0.0.1' }) + await server.videos.view({ id: videoId, xForwardedFor: '0.0.0.8,0.0.0.6,127.0.0.1' }) + await server.videos.view({ id: videoId, xForwardedFor: '0.0.0.8,0.0.0.7,127.0.0.1' }) // Wait the repeatable job await wait(8000) - const video = await server.videosCommand.get({ id: videoId }) + const video = await server.videos.get({ id: videoId }) expect(video.views).to.equal(6) }) @@ -93,22 +93,22 @@ describe('Test application behind a reverse proxy', function () { const user = { username: 'root', password: 'fail' } for (let i = 0; i < 19; i++) { - await server.loginCommand.login({ user, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) + await server.login.login({ user, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) } - await server.loginCommand.login({ user, expectedStatus: HttpStatusCode.TOO_MANY_REQUESTS_429 }) + await server.login.login({ user, expectedStatus: HttpStatusCode.TOO_MANY_REQUESTS_429 }) }) it('Should rate limit signup', async function () { for (let i = 0; i < 10; i++) { try { - await server.usersCommand.register({ username: 'test' + i }) + await server.users.register({ username: 'test' + i }) } catch { // empty } } - await server.usersCommand.register({ username: 'test42', expectedStatus: HttpStatusCode.TOO_MANY_REQUESTS_429 }) + await server.users.register({ username: 'test42', expectedStatus: HttpStatusCode.TOO_MANY_REQUESTS_429 }) }) it('Should not rate limit failed signup', async function () { @@ -117,10 +117,10 @@ describe('Test application behind a reverse proxy', function () { await wait(7000) for (let i = 0; i < 3; i++) { - await server.usersCommand.register({ username: 'test' + i, expectedStatus: HttpStatusCode.CONFLICT_409 }) + await server.users.register({ username: 'test' + i, expectedStatus: HttpStatusCode.CONFLICT_409 }) } - await server.usersCommand.register({ username: 'test43', expectedStatus: HttpStatusCode.NO_CONTENT_204 }) + await server.users.register({ username: 'test43', expectedStatus: HttpStatusCode.NO_CONTENT_204 }) }) @@ -131,13 +131,13 @@ describe('Test application behind a reverse proxy', function () { for (let i = 0; i < 100; i++) { try { - await server.videosCommand.get({ id: videoId }) + await server.videos.get({ id: videoId }) } catch { // don't care if it fails } } - await server.videosCommand.get({ id: videoId, expectedStatus: HttpStatusCode.TOO_MANY_REQUESTS_429 }) + await server.videos.get({ id: videoId, expectedStatus: HttpStatusCode.TOO_MANY_REQUESTS_429 }) }) after(async function () { diff --git a/server/tests/api/server/services.ts b/server/tests/api/server/services.ts index a62fb3939..28f9ae3b6 100644 --- a/server/tests/api/server/services.ts +++ b/server/tests/api/server/services.ts @@ -23,25 +23,25 @@ describe('Test services', function () { { const attributes = { name: 'my super name' } - await server.videosCommand.upload({ attributes }) + await server.videos.upload({ attributes }) - const { data } = await server.videosCommand.list() + const { data } = await server.videos.list() video = data[0] } { - const created = await server.playlistsCommand.create({ + const created = await server.playlists.create({ attributes: { displayName: 'The Life and Times of Scrooge McDuck', privacy: VideoPlaylistPrivacy.PUBLIC, - videoChannelId: server.videoChannel.id + videoChannelId: server.store.channel.id } }) playlistUUID = created.uuid playlistDisplayName = 'The Life and Times of Scrooge McDuck' - await server.playlistsCommand.addElement({ + await server.playlists.addElement({ playlistId: created.id, attributes: { videoId: video.id @@ -54,7 +54,7 @@ describe('Test services', function () { for (const basePath of [ '/videos/watch/', '/w/' ]) { const oembedUrl = 'http://localhost:' + server.port + basePath + video.uuid - const res = await server.servicesCommand.getOEmbed({ oembedUrl }) + const res = await server.services.getOEmbed({ oembedUrl }) const expectedHtml = '' @@ -62,7 +62,7 @@ describe('Test services', function () { expect(res.body.html).to.equal(expectedHtml) expect(res.body.title).to.equal(video.name) - expect(res.body.author_name).to.equal(server.videoChannel.displayName) + expect(res.body.author_name).to.equal(server.store.channel.displayName) expect(res.body.width).to.equal(560) expect(res.body.height).to.equal(315) expect(res.body.thumbnail_url).to.equal(expectedThumbnailUrl) @@ -75,14 +75,14 @@ describe('Test services', function () { for (const basePath of [ '/videos/watch/playlist/', '/w/p/' ]) { const oembedUrl = 'http://localhost:' + server.port + basePath + playlistUUID - const res = await server.servicesCommand.getOEmbed({ oembedUrl }) + const res = await server.services.getOEmbed({ oembedUrl }) const expectedHtml = '' expect(res.body.html).to.equal(expectedHtml) expect(res.body.title).to.equal('The Life and Times of Scrooge McDuck') - expect(res.body.author_name).to.equal(server.videoChannel.displayName) + expect(res.body.author_name).to.equal(server.store.channel.displayName) expect(res.body.width).to.equal(560) expect(res.body.height).to.equal(315) expect(res.body.thumbnail_url).exist @@ -98,14 +98,14 @@ describe('Test services', function () { const maxHeight = 50 const maxWidth = 50 - const res = await server.servicesCommand.getOEmbed({ oembedUrl, format, maxHeight, maxWidth }) + const res = await server.services.getOEmbed({ oembedUrl, format, maxHeight, maxWidth }) const expectedHtml = '' expect(res.body.html).to.equal(expectedHtml) expect(res.body.title).to.equal(video.name) - expect(res.body.author_name).to.equal(server.videoChannel.displayName) + expect(res.body.author_name).to.equal(server.store.channel.displayName) expect(res.body.height).to.equal(50) expect(res.body.width).to.equal(50) expect(res.body).to.not.have.property('thumbnail_url') diff --git a/server/tests/api/server/stats.ts b/server/tests/api/server/stats.ts index 3eb1efb94..be5abad52 100644 --- a/server/tests/api/server/stats.ts +++ b/server/tests/api/server/stats.ts @@ -32,23 +32,23 @@ describe('Test stats (excluding redundancy)', function () { await doubleFollow(servers[0], servers[1]) - await servers[0].usersCommand.create({ username: user.username, password: user.password }) + await servers[0].users.create({ username: user.username, password: user.password }) - const { uuid } = await servers[0].videosCommand.upload({ attributes: { fixture: 'video_short.webm' } }) + const { uuid } = await servers[0].videos.upload({ attributes: { fixture: 'video_short.webm' } }) - await servers[0].commentsCommand.createThread({ videoId: uuid, text: 'comment' }) + await servers[0].comments.createThread({ videoId: uuid, text: 'comment' }) - await servers[0].videosCommand.view({ id: uuid }) + await servers[0].videos.view({ id: uuid }) // Wait the video views repeatable job await wait(8000) - await servers[2].followsCommand.follow({ targets: [ servers[0].url ] }) + await servers[2].follows.follow({ targets: [ servers[0].url ] }) await waitJobs(servers) }) it('Should have the correct stats on instance 1', async function () { - const data = await servers[0].statsCommand.get() + const data = await servers[0].stats.get() expect(data.totalLocalVideoComments).to.equal(1) expect(data.totalLocalVideos).to.equal(1) @@ -63,7 +63,7 @@ describe('Test stats (excluding redundancy)', function () { }) it('Should have the correct stats on instance 2', async function () { - const data = await servers[1].statsCommand.get() + const data = await servers[1].stats.get() expect(data.totalLocalVideoComments).to.equal(0) expect(data.totalLocalVideos).to.equal(0) @@ -78,7 +78,7 @@ describe('Test stats (excluding redundancy)', function () { }) it('Should have the correct stats on instance 3', async function () { - const data = await servers[2].statsCommand.get() + const data = await servers[2].stats.get() expect(data.totalLocalVideoComments).to.equal(0) expect(data.totalLocalVideos).to.equal(0) @@ -94,10 +94,10 @@ describe('Test stats (excluding redundancy)', function () { it('Should have the correct total videos stats after an unfollow', async function () { this.timeout(15000) - await servers[2].followsCommand.unfollow({ target: servers[0] }) + await servers[2].follows.unfollow({ target: servers[0] }) await waitJobs(servers) - const data = await servers[2].statsCommand.get() + const data = await servers[2].stats.get() expect(data.totalVideos).to.equal(0) }) @@ -106,7 +106,7 @@ describe('Test stats (excluding redundancy)', function () { const server = servers[0] { - const data = await server.statsCommand.get() + const data = await server.stats.get() expect(data.totalDailyActiveUsers).to.equal(1) expect(data.totalWeeklyActiveUsers).to.equal(1) @@ -114,9 +114,9 @@ describe('Test stats (excluding redundancy)', function () { } { - await server.loginCommand.getAccessToken(user) + await server.login.getAccessToken(user) - const data = await server.statsCommand.get() + const data = await server.stats.get() expect(data.totalDailyActiveUsers).to.equal(2) expect(data.totalWeeklyActiveUsers).to.equal(2) @@ -128,7 +128,7 @@ describe('Test stats (excluding redundancy)', function () { const server = servers[0] { - const data = await server.statsCommand.get() + const data = await server.stats.get() expect(data.totalLocalDailyActiveVideoChannels).to.equal(1) expect(data.totalLocalWeeklyActiveVideoChannels).to.equal(1) @@ -140,10 +140,10 @@ describe('Test stats (excluding redundancy)', function () { name: 'stats_channel', displayName: 'My stats channel' } - const created = await server.channelsCommand.create({ attributes }) + const created = await server.channels.create({ attributes }) channelId = created.id - const data = await server.statsCommand.get() + const data = await server.stats.get() expect(data.totalLocalDailyActiveVideoChannels).to.equal(1) expect(data.totalLocalWeeklyActiveVideoChannels).to.equal(1) @@ -151,9 +151,9 @@ describe('Test stats (excluding redundancy)', function () { } { - await server.videosCommand.upload({ attributes: { fixture: 'video_short.webm', channelId } }) + await server.videos.upload({ attributes: { fixture: 'video_short.webm', channelId } }) - const data = await server.statsCommand.get() + const data = await server.stats.get() expect(data.totalLocalDailyActiveVideoChannels).to.equal(2) expect(data.totalLocalWeeklyActiveVideoChannels).to.equal(2) @@ -165,12 +165,12 @@ describe('Test stats (excluding redundancy)', function () { const server = servers[0] { - const data = await server.statsCommand.get() + const data = await server.stats.get() expect(data.totalLocalPlaylists).to.equal(0) } { - await server.playlistsCommand.create({ + await server.playlists.create({ attributes: { displayName: 'playlist for count', privacy: VideoPlaylistPrivacy.PUBLIC, @@ -178,7 +178,7 @@ describe('Test stats (excluding redundancy)', function () { } }) - const data = await server.statsCommand.get() + const data = await server.stats.get() expect(data.totalLocalPlaylists).to.equal(1) } }) @@ -186,7 +186,7 @@ describe('Test stats (excluding redundancy)', function () { it('Should correctly count video file sizes if transcoding is enabled', async function () { this.timeout(60000) - await servers[0].configCommand.updateCustomSubConfig({ + await servers[0].config.updateCustomSubConfig({ newConfig: { transcoding: { enabled: true, @@ -210,17 +210,17 @@ describe('Test stats (excluding redundancy)', function () { } }) - await servers[0].videosCommand.upload({ attributes: { name: 'video', fixture: 'video_short.webm' } }) + await servers[0].videos.upload({ attributes: { name: 'video', fixture: 'video_short.webm' } }) await waitJobs(servers) { - const data = await servers[1].statsCommand.get() + const data = await servers[1].stats.get() expect(data.totalLocalVideoFilesSize).to.equal(0) } { - const data = await servers[0].statsCommand.get() + const data = await servers[0].stats.get() expect(data.totalLocalVideoFilesSize).to.be.greaterThan(500000) expect(data.totalLocalVideoFilesSize).to.be.lessThan(600000) } @@ -229,7 +229,7 @@ describe('Test stats (excluding redundancy)', function () { it('Should have the correct AP stats', async function () { this.timeout(60000) - await servers[0].configCommand.updateCustomSubConfig({ + await servers[0].config.updateCustomSubConfig({ newConfig: { transcoding: { enabled: false @@ -237,17 +237,17 @@ describe('Test stats (excluding redundancy)', function () { } }) - const first = await servers[1].statsCommand.get() + const first = await servers[1].stats.get() for (let i = 0; i < 10; i++) { - await servers[0].videosCommand.upload({ attributes: { name: 'video' } }) + await servers[0].videos.upload({ attributes: { name: 'video' } }) } await waitJobs(servers) await wait(6000) - const second = await servers[1].statsCommand.get() + const second = await servers[1].stats.get() expect(second.totalActivityPubMessagesProcessed).to.be.greaterThan(first.totalActivityPubMessagesProcessed) const apTypes: ActivityType[] = [ @@ -269,7 +269,7 @@ describe('Test stats (excluding redundancy)', function () { await wait(6000) - const third = await servers[1].statsCommand.get() + const third = await servers[1].stats.get() expect(third.totalActivityPubMessagesWaiting).to.equal(0) expect(third.activityPubMessagesProcessedPerSecond).to.be.lessThan(second.activityPubMessagesProcessedPerSecond) }) diff --git a/server/tests/api/server/tracker.ts b/server/tests/api/server/tracker.ts index 032012edf..d80362fee 100644 --- a/server/tests/api/server/tracker.ts +++ b/server/tests/api/server/tracker.ts @@ -16,8 +16,8 @@ describe('Test tracker', function () { await setAccessTokensToServers([ server ]) { - const { uuid } = await server.videosCommand.upload() - const video = await server.videosCommand.get({ id: uuid }) + const { uuid } = await server.videos.upload() + const video = await server.videos.get({ id: uuid }) goodMagnet = video.files[0].magnetUri const parsed = magnetUtil.decode(goodMagnet) diff --git a/server/tests/api/users/user-subscriptions.ts b/server/tests/api/users/user-subscriptions.ts index 622cddb7d..1b15a98dc 100644 --- a/server/tests/api/users/user-subscriptions.ts +++ b/server/tests/api/users/user-subscriptions.ts @@ -35,26 +35,26 @@ describe('Test users subscriptions', function () { { for (const server of servers) { const user = { username: 'user' + server.serverNumber, password: 'password' } - await server.usersCommand.create({ username: user.username, password: user.password }) + await server.users.create({ username: user.username, password: user.password }) - const accessToken = await server.loginCommand.getAccessToken(user) + const accessToken = await server.login.getAccessToken(user) users.push({ accessToken }) const videoName1 = 'video 1-' + server.serverNumber - await server.videosCommand.upload({ token: accessToken, attributes: { name: videoName1 } }) + await server.videos.upload({ token: accessToken, attributes: { name: videoName1 } }) const videoName2 = 'video 2-' + server.serverNumber - await server.videosCommand.upload({ token: accessToken, attributes: { name: videoName2 } }) + await server.videos.upload({ token: accessToken, attributes: { name: videoName2 } }) } } await waitJobs(servers) - command = servers[0].subscriptionsCommand + command = servers[0].subscriptions }) it('Should display videos of server 2 on server 1', async function () { - const { total } = await servers[0].videosCommand.list() + const { total } = await servers[0].videos.list() expect(total).to.equal(4) }) @@ -67,14 +67,14 @@ describe('Test users subscriptions', function () { await waitJobs(servers) - const { uuid } = await servers[2].videosCommand.upload({ attributes: { name: 'video server 3 added after follow' } }) + const { uuid } = await servers[2].videos.upload({ attributes: { name: 'video server 3 added after follow' } }) video3UUID = uuid await waitJobs(servers) }) it('Should not display videos of server 3 on server 1', async function () { - const { total, data } = await servers[0].videosCommand.list() + const { total, data } = await servers[0].videos.list() expect(total).to.equal(4) for (const video of data) { @@ -183,7 +183,7 @@ describe('Test users subscriptions', function () { this.timeout(60000) const videoName = 'video server 1 added after follow' - await servers[0].videosCommand.upload({ attributes: { name: videoName } }) + await servers[0].videos.upload({ attributes: { name: videoName } }) await waitJobs(servers) @@ -209,7 +209,7 @@ describe('Test users subscriptions', function () { } { - const { data, total } = await servers[0].videosCommand.list() + const { data, total } = await servers[0].videos.list() expect(total).to.equal(5) for (const video of data) { @@ -223,11 +223,11 @@ describe('Test users subscriptions', function () { it('Should have server 1 follow server 3 and display server 3 videos', async function () { this.timeout(60000) - await servers[0].followsCommand.follow({ targets: [ servers[2].url ] }) + await servers[0].follows.follow({ targets: [ servers[2].url ] }) await waitJobs(servers) - const { data, total } = await servers[0].videosCommand.list() + const { data, total } = await servers[0].videos.list() expect(total).to.equal(8) const names = [ '1-3', '2-3', 'video server 3 added after follow' ] @@ -240,11 +240,11 @@ describe('Test users subscriptions', function () { it('Should remove follow server 1 -> server 3 and hide server 3 videos', async function () { this.timeout(60000) - await servers[0].followsCommand.unfollow({ target: servers[2] }) + await servers[0].follows.unfollow({ target: servers[2] }) await waitJobs(servers) - const { total, data } = await servers[0].videosCommand.list() + const { total, data } = await servers[0].videos.list() expect(total).to.equal(5) for (const video of data) { @@ -280,7 +280,7 @@ describe('Test users subscriptions', function () { it('Should update a video of server 3 and see the updated video on server 1', async function () { this.timeout(30000) - await servers[2].videosCommand.update({ id: video3UUID, attributes: { name: 'video server 3 added after follow updated' } }) + await servers[2].videos.update({ id: video3UUID, attributes: { name: 'video server 3 added after follow updated' } }) await waitJobs(servers) @@ -325,7 +325,7 @@ describe('Test users subscriptions', function () { }) it('Should correctly display public videos on server 1', async function () { - const { total, data } = await servers[0].videosCommand.list() + const { total, data } = await servers[0].videos.list() expect(total).to.equal(5) for (const video of data) { @@ -356,7 +356,7 @@ describe('Test users subscriptions', function () { } { - const { total, data } = await servers[0].videosCommand.list() + const { total, data } = await servers[0].videos.list() expect(total).to.equal(5) for (const video of data) { diff --git a/server/tests/api/users/users-multiple-servers.ts b/server/tests/api/users/users-multiple-servers.ts index 3ae105008..f8d7ae88e 100644 --- a/server/tests/api/users/users-multiple-servers.ts +++ b/server/tests/api/users/users-multiple-servers.ts @@ -42,20 +42,20 @@ describe('Test users with multiple servers', function () { await doubleFollow(servers[1], servers[2]) // The root user of server 1 is propagated to servers 2 and 3 - await servers[0].videosCommand.upload() + await servers[0].videos.upload() { const user = { username: 'user1', password: 'password' } - const created = await servers[0].usersCommand.create(user) + const created = await servers[0].users.create(user) userId = created.id - userAccessToken = await servers[0].loginCommand.getAccessToken(user) + userAccessToken = await servers[0].login.getAccessToken(user) } { - const { uuid } = await servers[0].videosCommand.upload({ token: userAccessToken }) + const { uuid } = await servers[0].videos.upload({ token: userAccessToken }) videoUUID = uuid } @@ -65,9 +65,9 @@ describe('Test users with multiple servers', function () { it('Should be able to update my display name', async function () { this.timeout(10000) - await servers[0].usersCommand.updateMe({ displayName: 'my super display name' }) + await servers[0].users.updateMe({ displayName: 'my super display name' }) - user = await servers[0].usersCommand.getMyInfo() + user = await servers[0].users.getMyInfo() expect(user.account.displayName).to.equal('my super display name') await waitJobs(servers) @@ -76,9 +76,9 @@ describe('Test users with multiple servers', function () { it('Should be able to update my description', async function () { this.timeout(10_000) - await servers[0].usersCommand.updateMe({ description: 'my super description updated' }) + await servers[0].users.updateMe({ description: 'my super description updated' }) - user = await servers[0].usersCommand.getMyInfo() + user = await servers[0].users.getMyInfo() expect(user.account.displayName).to.equal('my super display name') expect(user.account.description).to.equal('my super description updated') @@ -90,9 +90,9 @@ describe('Test users with multiple servers', function () { const fixture = 'avatar2.png' - await servers[0].usersCommand.updateMyAvatar({ fixture }) + await servers[0].users.updateMyAvatar({ fixture }) - user = await servers[0].usersCommand.getMyInfo() + user = await servers[0].users.getMyInfo() userAvatarFilename = user.account.avatar.path await testImage(servers[0].url, 'avatar2-resized', userAvatarFilename, '.png') @@ -104,12 +104,12 @@ describe('Test users with multiple servers', function () { let createdAt: string | Date for (const server of servers) { - const body = await server.accountsCommand.list({ sort: '-createdAt' }) + const body = await server.accounts.list({ sort: '-createdAt' }) const resList = body.data.find(a => a.name === 'root' && a.host === 'localhost:' + servers[0].port) expect(resList).not.to.be.undefined - const account = await server.accountsCommand.get({ accountName: resList.name + '@' + resList.host }) + const account = await server.accounts.get({ accountName: resList.name + '@' + resList.host }) if (!createdAt) createdAt = account.createdAt @@ -131,7 +131,7 @@ describe('Test users with multiple servers', function () { it('Should list account videos', async function () { for (const server of servers) { - const { total, data } = await server.videosCommand.listByAccount({ accountName: 'user1@localhost:' + servers[0].port }) + const { total, data } = await server.videos.listByAccount({ accountName: 'user1@localhost:' + servers[0].port }) expect(total).to.equal(1) expect(data).to.be.an('array') @@ -143,12 +143,12 @@ describe('Test users with multiple servers', function () { it('Should search through account videos', async function () { this.timeout(10_000) - const created = await servers[0].videosCommand.upload({ token: userAccessToken, attributes: { name: 'Kami no chikara' } }) + const created = await servers[0].videos.upload({ token: userAccessToken, attributes: { name: 'Kami no chikara' } }) await waitJobs(servers) for (const server of servers) { - const { total, data } = await server.videosCommand.listByAccount({ accountName: 'user1@localhost:' + servers[0].port, search: 'Kami' }) + const { total, data } = await server.videos.listByAccount({ accountName: 'user1@localhost:' + servers[0].port, search: 'Kami' }) expect(total).to.equal(1) expect(data).to.be.an('array') @@ -161,27 +161,27 @@ describe('Test users with multiple servers', function () { this.timeout(10_000) for (const server of servers) { - const body = await server.accountsCommand.list({ sort: '-createdAt' }) + const body = await server.accounts.list({ sort: '-createdAt' }) const accountDeleted = body.data.find(a => a.name === 'user1' && a.host === 'localhost:' + servers[0].port) expect(accountDeleted).not.to.be.undefined - const { data } = await server.channelsCommand.list() + const { data } = await server.channels.list() const videoChannelDeleted = data.find(a => a.displayName === 'Main user1 channel' && a.host === 'localhost:' + servers[0].port) expect(videoChannelDeleted).not.to.be.undefined } - await servers[0].usersCommand.remove({ userId }) + await servers[0].users.remove({ userId }) await waitJobs(servers) for (const server of servers) { - const body = await server.accountsCommand.list({ sort: '-createdAt' }) + const body = await server.accounts.list({ sort: '-createdAt' }) const accountDeleted = body.data.find(a => a.name === 'user1' && a.host === 'localhost:' + servers[0].port) expect(accountDeleted).to.be.undefined - const { data } = await server.channelsCommand.list() + const { data } = await server.channels.list() const videoChannelDeleted = data.find(a => a.name === 'Main user1 channel' && a.host === 'localhost:' + servers[0].port) expect(videoChannelDeleted).to.be.undefined } diff --git a/server/tests/api/users/users-verification.ts b/server/tests/api/users/users-verification.ts index 271aa3c7a..c8c226fa8 100644 --- a/server/tests/api/users/users-verification.ts +++ b/server/tests/api/users/users-verification.ts @@ -42,7 +42,7 @@ describe('Test users account verification', function () { it('Should register user and send verification email if verification required', async function () { this.timeout(30000) - await server.configCommand.updateCustomSubConfig({ + await server.config.updateCustomSubConfig({ newConfig: { signup: { enabled: true, @@ -52,7 +52,7 @@ describe('Test users account verification', function () { } }) - await server.usersCommand.register(user1) + await server.users.register(user1) await waitJobs(server) expectedEmailsLength++ @@ -71,22 +71,22 @@ describe('Test users account verification', function () { userId = parseInt(userIdMatches[1], 10) - const body = await server.usersCommand.get({ userId }) + const body = await server.users.get({ userId }) expect(body.emailVerified).to.be.false }) it('Should not allow login for user with unverified email', async function () { - const { detail } = await server.loginCommand.login({ user: user1, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) + const { detail } = await server.login.login({ user: user1, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) expect(detail).to.contain('User email is not verified.') }) it('Should verify the user via email and allow login', async function () { - await server.usersCommand.verifyEmail({ userId, verificationString }) + await server.users.verifyEmail({ userId, verificationString }) - const body = await server.loginCommand.login({ user: user1 }) + const body = await server.login.login({ user: user1 }) userAccessToken = body.access_token - const user = await server.usersCommand.get({ userId }) + const user = await server.users.get({ userId }) expect(user.emailVerified).to.be.true }) @@ -96,7 +96,7 @@ describe('Test users account verification', function () { let updateVerificationString: string { - await server.usersCommand.updateMe({ + await server.users.updateMe({ token: userAccessToken, email: 'updated@example.com', currentPassword: user1.password @@ -113,15 +113,15 @@ describe('Test users account verification', function () { } { - const me = await server.usersCommand.getMyInfo({ token: userAccessToken }) + const me = await server.users.getMyInfo({ token: userAccessToken }) expect(me.email).to.equal('user_1@example.com') expect(me.pendingEmail).to.equal('updated@example.com') } { - await server.usersCommand.verifyEmail({ userId, verificationString: updateVerificationString, isPendingEmail: true }) + await server.users.verifyEmail({ userId, verificationString: updateVerificationString, isPendingEmail: true }) - const me = await server.usersCommand.getMyInfo({ token: userAccessToken }) + const me = await server.users.getMyInfo({ token: userAccessToken }) expect(me.email).to.equal('updated@example.com') expect(me.pendingEmail).to.be.null } @@ -129,7 +129,7 @@ describe('Test users account verification', function () { it('Should register user not requiring email verification if setting not enabled', async function () { this.timeout(5000) - await server.configCommand.updateCustomSubConfig({ + await server.config.updateCustomSubConfig({ newConfig: { signup: { enabled: true, @@ -139,19 +139,19 @@ describe('Test users account verification', function () { } }) - await server.usersCommand.register(user2) + await server.users.register(user2) await waitJobs(server) expect(emails).to.have.lengthOf(expectedEmailsLength) - const accessToken = await server.loginCommand.getAccessToken(user2) + const accessToken = await server.login.getAccessToken(user2) - const user = await server.usersCommand.getMyInfo({ token: accessToken }) + const user = await server.users.getMyInfo({ token: accessToken }) expect(user.emailVerified).to.be.null }) it('Should allow login for user with unverified email when setting later enabled', async function () { - await server.configCommand.updateCustomSubConfig({ + await server.config.updateCustomSubConfig({ newConfig: { signup: { enabled: true, @@ -161,7 +161,7 @@ describe('Test users account verification', function () { } }) - await server.loginCommand.getAccessToken(user2) + await server.login.getAccessToken(user2) }) after(async function () { diff --git a/server/tests/api/users/users.ts b/server/tests/api/users/users.ts index 6f3873939..310136a37 100644 --- a/server/tests/api/users/users.ts +++ b/server/tests/api/users/users.ts @@ -42,7 +42,7 @@ describe('Test users', function () { await setAccessTokensToServers([ server ]) - await server.pluginsCommand.install({ npmName: 'peertube-theme-background-red' }) + await server.plugins.install({ npmName: 'peertube-theme-background-red' }) }) describe('OAuth client', function () { @@ -53,8 +53,8 @@ describe('Test users', function () { it('Should remove the last client') it('Should not login with an invalid client id', async function () { - const client = { id: 'client', secret: server.client.secret } - const body = await server.loginCommand.login({ client, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) + const client = { id: 'client', secret: server.store.client.secret } + const body = await server.login.login({ client, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) expect(body.code).to.equal(OAuth2ErrorCode.INVALID_CLIENT) expect(body.error).to.contain('client is invalid') @@ -63,8 +63,8 @@ describe('Test users', function () { }) it('Should not login with an invalid client secret', async function () { - const client = { id: server.client.id, secret: 'coucou' } - const body = await server.loginCommand.login({ client, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) + const client = { id: server.store.client.id, secret: 'coucou' } + const body = await server.login.login({ client, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) expect(body.code).to.equal(OAuth2ErrorCode.INVALID_CLIENT) expect(body.error).to.contain('client is invalid') @@ -76,8 +76,8 @@ describe('Test users', function () { describe('Login', function () { it('Should not login with an invalid username', async function () { - const user = { username: 'captain crochet', password: server.user.password } - const body = await server.loginCommand.login({ user, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) + const user = { username: 'captain crochet', password: server.store.user.password } + const body = await server.login.login({ user, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) expect(body.code).to.equal(OAuth2ErrorCode.INVALID_GRANT) expect(body.error).to.contain('credentials are invalid') @@ -86,8 +86,8 @@ describe('Test users', function () { }) it('Should not login with an invalid password', async function () { - const user = { username: server.user.username, password: 'mew_three' } - const body = await server.loginCommand.login({ user, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) + const user = { username: server.store.user.username, password: 'mew_three' } + const body = await server.login.login({ user, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) expect(body.code).to.equal(OAuth2ErrorCode.INVALID_GRANT) expect(body.error).to.contain('credentials are invalid') @@ -98,13 +98,13 @@ describe('Test users', function () { it('Should not be able to upload a video', async function () { token = 'my_super_token' - await server.videosCommand.upload({ token, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) + await server.videos.upload({ token, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should not be able to follow', async function () { token = 'my_super_token' - await server.followsCommand.follow({ + await server.follows.follow({ targets: [ 'http://example.com' ], token, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 @@ -114,28 +114,28 @@ describe('Test users', function () { it('Should not be able to unfollow') it('Should be able to login', async function () { - const body = await server.loginCommand.login({ expectedStatus: HttpStatusCode.OK_200 }) + const body = await server.login.login({ expectedStatus: HttpStatusCode.OK_200 }) token = body.access_token }) it('Should be able to login with an insensitive username', async function () { - const user = { username: 'RoOt', password: server.user.password } - await server.loginCommand.login({ user, expectedStatus: HttpStatusCode.OK_200 }) + const user = { username: 'RoOt', password: server.store.user.password } + await server.login.login({ user, expectedStatus: HttpStatusCode.OK_200 }) - const user2 = { username: 'rOoT', password: server.user.password } - await server.loginCommand.login({ user: user2, expectedStatus: HttpStatusCode.OK_200 }) + const user2 = { username: 'rOoT', password: server.store.user.password } + await server.login.login({ user: user2, expectedStatus: HttpStatusCode.OK_200 }) - const user3 = { username: 'ROOt', password: server.user.password } - await server.loginCommand.login({ user: user3, expectedStatus: HttpStatusCode.OK_200 }) + const user3 = { username: 'ROOt', password: server.store.user.password } + await server.login.login({ user: user3, expectedStatus: HttpStatusCode.OK_200 }) }) }) describe('Upload', function () { it('Should upload the video with the correct token', async function () { - await server.videosCommand.upload({ token }) - const { data } = await server.videosCommand.list() + await server.videos.upload({ token }) + const { data } = await server.videos.list() const video = data[0] expect(video.account.name).to.equal('root') @@ -143,24 +143,24 @@ describe('Test users', function () { }) it('Should upload the video again with the correct token', async function () { - await server.videosCommand.upload({ token }) + await server.videos.upload({ token }) }) }) describe('Ratings', function () { it('Should retrieve a video rating', async function () { - await server.videosCommand.rate({ id: videoId, rating: 'like' }) - const rating = await server.usersCommand.getMyRating({ token, videoId }) + await server.videos.rate({ id: videoId, rating: 'like' }) + const rating = await server.users.getMyRating({ token, videoId }) expect(rating.videoId).to.equal(videoId) expect(rating.rating).to.equal('like') }) it('Should retrieve ratings list', async function () { - await server.videosCommand.rate({ id: videoId, rating: 'like' }) + await server.videos.rate({ id: videoId, rating: 'like' }) - const body = await server.accountsCommand.listRatings({ accountName: server.user.username }) + const body = await server.accounts.listRatings({ accountName: server.store.user.username }) expect(body.total).to.equal(1) expect(body.data[0].video.id).to.equal(videoId) @@ -169,12 +169,12 @@ describe('Test users', function () { it('Should retrieve ratings list by rating type', async function () { { - const body = await server.accountsCommand.listRatings({ accountName: server.user.username, rating: 'like' }) + const body = await server.accounts.listRatings({ accountName: server.store.user.username, rating: 'like' }) expect(body.data.length).to.equal(1) } { - const body = await server.accountsCommand.listRatings({ accountName: server.user.username, rating: 'dislike' }) + const body = await server.accounts.listRatings({ accountName: server.store.user.username, rating: 'dislike' }) expect(body.data.length).to.equal(0) } }) @@ -182,27 +182,27 @@ describe('Test users', function () { describe('Remove video', function () { it('Should not be able to remove the video with an incorrect token', async function () { - await server.videosCommand.remove({ token: 'bad_token', id: videoId, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) + await server.videos.remove({ token: 'bad_token', id: videoId, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should not be able to remove the video with the token of another account') it('Should be able to remove the video with the correct token', async function () { - await server.videosCommand.remove({ token, id: videoId }) + await server.videos.remove({ token, id: videoId }) }) }) describe('Logout', function () { it('Should logout (revoke token)', async function () { - await server.loginCommand.logout({ token: server.accessToken }) + await server.login.logout({ token: server.accessToken }) }) it('Should not be able to get the user information', async function () { - await server.usersCommand.getMyInfo({ expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) + await server.users.getMyInfo({ expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should not be able to upload a video', async function () { - await server.videosCommand.upload({ attributes: { name: 'video' }, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) + await server.videos.upload({ attributes: { name: 'video' }, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should not be able to rate a video', async function () { @@ -222,64 +222,64 @@ describe('Test users', function () { }) it('Should be able to login again', async function () { - const body = await server.loginCommand.login() + const body = await server.login.login() server.accessToken = body.access_token server.refreshToken = body.refresh_token }) it('Should be able to get my user information again', async function () { - await server.usersCommand.getMyInfo() + await server.users.getMyInfo() }) it('Should have an expired access token', async function () { this.timeout(15000) - await server.sqlCommand.setTokenField(server.accessToken, 'accessTokenExpiresAt', new Date().toISOString()) - await server.sqlCommand.setTokenField(server.accessToken, 'refreshTokenExpiresAt', new Date().toISOString()) + await server.sql.setTokenField(server.accessToken, 'accessTokenExpiresAt', new Date().toISOString()) + await server.sql.setTokenField(server.accessToken, 'refreshTokenExpiresAt', new Date().toISOString()) await killallServers([ server ]) await reRunServer(server) - await server.usersCommand.getMyInfo({ expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) + await server.users.getMyInfo({ expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should not be able to refresh an access token with an expired refresh token', async function () { - await server.loginCommand.refreshToken({ refreshToken: server.refreshToken, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) + await server.login.refreshToken({ refreshToken: server.refreshToken, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) it('Should refresh the token', async function () { this.timeout(15000) const futureDate = new Date(new Date().getTime() + 1000 * 60).toISOString() - await server.sqlCommand.setTokenField(server.accessToken, 'refreshTokenExpiresAt', futureDate) + await server.sql.setTokenField(server.accessToken, 'refreshTokenExpiresAt', futureDate) await killallServers([ server ]) await reRunServer(server) - const res = await server.loginCommand.refreshToken({ refreshToken: server.refreshToken }) + const res = await server.login.refreshToken({ refreshToken: server.refreshToken }) server.accessToken = res.body.access_token server.refreshToken = res.body.refresh_token }) it('Should be able to get my user information again', async function () { - await server.usersCommand.getMyInfo() + await server.users.getMyInfo() }) }) describe('Creating a user', function () { it('Should be able to create a new user', async function () { - await server.usersCommand.create({ ...user, videoQuota: 2 * 1024 * 1024, adminFlags: UserAdminFlag.BYPASS_VIDEO_AUTO_BLACKLIST }) + await server.users.create({ ...user, videoQuota: 2 * 1024 * 1024, adminFlags: UserAdminFlag.BYPASS_VIDEO_AUTO_BLACKLIST }) }) it('Should be able to login with this user', async function () { - userToken = await server.loginCommand.getAccessToken(user) + userToken = await server.login.getAccessToken(user) }) it('Should be able to get user information', async function () { - const userMe = await server.usersCommand.getMyInfo({ token: userToken }) + const userMe = await server.users.getMyInfo({ token: userToken }) - const userGet = await server.usersCommand.get({ userId: userMe.id, withStats: true }) + const userGet = await server.users.get({ userId: userMe.id, withStats: true }) for (const user of [ userMe, userGet ]) { expect(user.username).to.equal('user_1') @@ -319,20 +319,20 @@ describe('Test users', function () { name: 'super user video', fixture: 'video_short.webm' } - await server.videosCommand.upload({ token: userToken, attributes }) + await server.videos.upload({ token: userToken, attributes }) }) it('Should have video quota updated', async function () { - const quota = await server.usersCommand.getMyQuotaUsed({ token: userToken }) + const quota = await server.users.getMyQuotaUsed({ token: userToken }) expect(quota.videoQuotaUsed).to.equal(218910) - const { data } = await server.usersCommand.list() + const { data } = await server.users.list() const tmpUser = data.find(u => u.username === user.username) expect(tmpUser.videoQuotaUsed).to.equal(218910) }) it('Should be able to list my videos', async function () { - const { total, data } = await server.videosCommand.listMyVideos({ token: userToken }) + const { total, data } = await server.videos.listMyVideos({ token: userToken }) expect(total).to.equal(1) expect(data).to.have.lengthOf(1) @@ -344,13 +344,13 @@ describe('Test users', function () { it('Should be able to search in my videos', async function () { { - const { total, data } = await server.videosCommand.listMyVideos({ token: userToken, sort: '-createdAt', search: 'user video' }) + const { total, data } = await server.videos.listMyVideos({ token: userToken, sort: '-createdAt', search: 'user video' }) expect(total).to.equal(1) expect(data).to.have.lengthOf(1) } { - const { total, data } = await server.videosCommand.listMyVideos({ token: userToken, sort: '-createdAt', search: 'toto' }) + const { total, data } = await server.videos.listMyVideos({ token: userToken, sort: '-createdAt', search: 'toto' }) expect(total).to.equal(0) expect(data).to.have.lengthOf(0) } @@ -360,11 +360,11 @@ describe('Test users', function () { this.timeout(60000) { - const config = await server.configCommand.getCustomConfig() + const config = await server.config.getCustomConfig() config.transcoding.webtorrent.enabled = false config.transcoding.hls.enabled = true config.transcoding.enabled = true - await server.configCommand.updateCustomSubConfig({ newConfig: config }) + await server.config.updateCustomSubConfig({ newConfig: config }) } { @@ -372,13 +372,13 @@ describe('Test users', function () { name: 'super user video 2', fixture: 'video_short.webm' } - await server.videosCommand.upload({ token: userToken, attributes }) + await server.videos.upload({ token: userToken, attributes }) await waitJobs([ server ]) } { - const data = await server.usersCommand.getMyQuotaUsed({ token: userToken }) + const data = await server.users.getMyQuotaUsed({ token: userToken }) expect(data.videoQuotaUsed).to.be.greaterThan(220000) } }) @@ -387,7 +387,7 @@ describe('Test users', function () { describe('Users listing', function () { it('Should list all the users', async function () { - const { data, total } = await server.usersCommand.list() + const { data, total } = await server.users.list() expect(total).to.equal(2) expect(data).to.be.an('array') @@ -410,7 +410,7 @@ describe('Test users', function () { }) it('Should list only the first user by username asc', async function () { - const { total, data } = await server.usersCommand.list({ start: 0, count: 1, sort: 'username' }) + const { total, data } = await server.users.list({ start: 0, count: 1, sort: 'username' }) expect(total).to.equal(2) expect(data.length).to.equal(1) @@ -423,7 +423,7 @@ describe('Test users', function () { }) it('Should list only the first user by username desc', async function () { - const { total, data } = await server.usersCommand.list({ start: 0, count: 1, sort: '-username' }) + const { total, data } = await server.users.list({ start: 0, count: 1, sort: '-username' }) expect(total).to.equal(2) expect(data.length).to.equal(1) @@ -435,7 +435,7 @@ describe('Test users', function () { }) it('Should list only the second user by createdAt desc', async function () { - const { data, total } = await server.usersCommand.list({ start: 0, count: 1, sort: '-createdAt' }) + const { data, total } = await server.users.list({ start: 0, count: 1, sort: '-createdAt' }) expect(total).to.equal(2) expect(data.length).to.equal(1) @@ -447,7 +447,7 @@ describe('Test users', function () { }) it('Should list all the users by createdAt asc', async function () { - const { data, total } = await server.usersCommand.list({ start: 0, count: 2, sort: 'createdAt' }) + const { data, total } = await server.users.list({ start: 0, count: 2, sort: 'createdAt' }) expect(total).to.equal(2) expect(data.length).to.equal(2) @@ -462,7 +462,7 @@ describe('Test users', function () { }) it('Should search user by username', async function () { - const { data, total } = await server.usersCommand.list({ start: 0, count: 2, sort: 'createdAt', search: 'oot' }) + const { data, total } = await server.users.list({ start: 0, count: 2, sort: 'createdAt', search: 'oot' }) expect(total).to.equal(1) expect(data.length).to.equal(1) expect(data[0].username).to.equal('root') @@ -470,7 +470,7 @@ describe('Test users', function () { it('Should search user by email', async function () { { - const { total, data } = await server.usersCommand.list({ start: 0, count: 2, sort: 'createdAt', search: 'r_1@exam' }) + const { total, data } = await server.users.list({ start: 0, count: 2, sort: 'createdAt', search: 'r_1@exam' }) expect(total).to.equal(1) expect(data.length).to.equal(1) expect(data[0].username).to.equal('user_1') @@ -478,7 +478,7 @@ describe('Test users', function () { } { - const { total, data } = await server.usersCommand.list({ start: 0, count: 2, sort: 'createdAt', search: 'example' }) + const { total, data } = await server.users.list({ start: 0, count: 2, sort: 'createdAt', search: 'example' }) expect(total).to.equal(2) expect(data.length).to.equal(2) expect(data[0].username).to.equal('root') @@ -490,23 +490,23 @@ describe('Test users', function () { describe('Update my account', function () { it('Should update my password', async function () { - await server.usersCommand.updateMe({ + await server.users.updateMe({ token: userToken, currentPassword: 'super password', password: 'new password' }) user.password = 'new password' - await server.loginCommand.login({ user }) + await server.login.login({ user }) }) it('Should be able to change the NSFW display attribute', async function () { - await server.usersCommand.updateMe({ + await server.users.updateMe({ token: userToken, nsfwPolicy: 'do_not_list' }) - const user = await server.usersCommand.getMyInfo({ token: userToken }) + const user = await server.users.getMyInfo({ token: userToken }) expect(user.username).to.equal('user_1') expect(user.email).to.equal('user_1@example.com') expect(user.nsfwPolicy).to.equal('do_not_list') @@ -517,33 +517,33 @@ describe('Test users', function () { }) it('Should be able to change the autoPlayVideo attribute', async function () { - await server.usersCommand.updateMe({ + await server.users.updateMe({ token: userToken, autoPlayVideo: false }) - const user = await server.usersCommand.getMyInfo({ token: userToken }) + const user = await server.users.getMyInfo({ token: userToken }) expect(user.autoPlayVideo).to.be.false }) it('Should be able to change the autoPlayNextVideo attribute', async function () { - await server.usersCommand.updateMe({ + await server.users.updateMe({ token: userToken, autoPlayNextVideo: true }) - const user = await server.usersCommand.getMyInfo({ token: userToken }) + const user = await server.users.getMyInfo({ token: userToken }) expect(user.autoPlayNextVideo).to.be.true }) it('Should be able to change the email attribute', async function () { - await server.usersCommand.updateMe({ + await server.users.updateMe({ token: userToken, currentPassword: 'new password', email: 'updated@example.com' }) - const user = await server.usersCommand.getMyInfo({ token: userToken }) + const user = await server.users.getMyInfo({ token: userToken }) expect(user.username).to.equal('user_1') expect(user.email).to.equal('updated@example.com') expect(user.nsfwPolicy).to.equal('do_not_list') @@ -556,9 +556,9 @@ describe('Test users', function () { it('Should be able to update my avatar with a gif', async function () { const fixture = 'avatar.gif' - await server.usersCommand.updateMyAvatar({ token: userToken, fixture }) + await server.users.updateMyAvatar({ token: userToken, fixture }) - const user = await server.usersCommand.getMyInfo({ token: userToken }) + const user = await server.users.getMyInfo({ token: userToken }) await testImage(server.url, 'avatar-resized', user.account.avatar.path, '.gif') }) @@ -566,17 +566,17 @@ describe('Test users', function () { for (const extension of [ '.png', '.gif' ]) { const fixture = 'avatar' + extension - await server.usersCommand.updateMyAvatar({ token: userToken, fixture }) + await server.users.updateMyAvatar({ token: userToken, fixture }) - const user = await server.usersCommand.getMyInfo({ token: userToken }) + const user = await server.users.getMyInfo({ token: userToken }) await testImage(server.url, 'avatar-resized', user.account.avatar.path, extension) } }) it('Should be able to update my display name', async function () { - await server.usersCommand.updateMe({ token: userToken, displayName: 'new display name' }) + await server.users.updateMe({ token: userToken, displayName: 'new display name' }) - const user = await server.usersCommand.getMyInfo({ token: userToken }) + const user = await server.users.getMyInfo({ token: userToken }) expect(user.username).to.equal('user_1') expect(user.email).to.equal('updated@example.com') expect(user.nsfwPolicy).to.equal('do_not_list') @@ -587,9 +587,9 @@ describe('Test users', function () { }) it('Should be able to update my description', async function () { - await server.usersCommand.updateMe({ token: userToken, description: 'my super description updated' }) + await server.users.updateMe({ token: userToken, description: 'my super description updated' }) - const user = await server.usersCommand.getMyInfo({ token: userToken }) + const user = await server.users.getMyInfo({ token: userToken }) expect(user.username).to.equal('user_1') expect(user.email).to.equal('updated@example.com') expect(user.nsfwPolicy).to.equal('do_not_list') @@ -603,21 +603,21 @@ describe('Test users', function () { it('Should be able to update my theme', async function () { for (const theme of [ 'background-red', 'default', 'instance-default' ]) { - await server.usersCommand.updateMe({ token: userToken, theme }) + await server.users.updateMe({ token: userToken, theme }) - const user = await server.usersCommand.getMyInfo({ token: userToken }) + const user = await server.users.getMyInfo({ token: userToken }) expect(user.theme).to.equal(theme) } }) it('Should be able to update my modal preferences', async function () { - await server.usersCommand.updateMe({ + await server.users.updateMe({ token: userToken, noInstanceConfigWarningModal: true, noWelcomeModal: true }) - const user = await server.usersCommand.getMyInfo({ token: userToken }) + const user = await server.users.getMyInfo({ token: userToken }) expect(user.noWelcomeModal).to.be.true expect(user.noInstanceConfigWarningModal).to.be.true }) @@ -625,7 +625,7 @@ describe('Test users', function () { describe('Updating another user', function () { it('Should be able to update another user', async function () { - await server.usersCommand.update({ + await server.users.update({ userId, token, email: 'updated2@example.com', @@ -636,7 +636,7 @@ describe('Test users', function () { pluginAuth: 'toto' }) - const user = await server.usersCommand.get({ token, userId }) + const user = await server.users.get({ token, userId }) expect(user.username).to.equal('user_1') expect(user.email).to.equal('updated2@example.com') @@ -650,47 +650,47 @@ describe('Test users', function () { }) it('Should reset the auth plugin', async function () { - await server.usersCommand.update({ userId, token, pluginAuth: null }) + await server.users.update({ userId, token, pluginAuth: null }) - const user = await server.usersCommand.get({ token, userId }) + const user = await server.users.get({ token, userId }) expect(user.pluginAuth).to.be.null }) it('Should have removed the user token', async function () { - await server.usersCommand.getMyQuotaUsed({ token: userToken, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) + await server.users.getMyQuotaUsed({ token: userToken, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) - userToken = await server.loginCommand.getAccessToken(user) + userToken = await server.login.getAccessToken(user) }) it('Should be able to update another user password', async function () { - await server.usersCommand.update({ userId, token, password: 'password updated' }) + await server.users.update({ userId, token, password: 'password updated' }) - await server.usersCommand.getMyQuotaUsed({ token: userToken, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) + await server.users.getMyQuotaUsed({ token: userToken, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) - await server.loginCommand.login({ user, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) + await server.login.login({ user, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) user.password = 'password updated' - userToken = await server.loginCommand.getAccessToken(user) + userToken = await server.login.getAccessToken(user) }) }) describe('Video blacklists', function () { it('Should be able to list video blacklist by a moderator', async function () { - await server.blacklistCommand.list({ token: userToken }) + await server.blacklist.list({ token: userToken }) }) }) describe('Remove a user', function () { it('Should be able to remove this user', async function () { - await server.usersCommand.remove({ userId, token }) + await server.users.remove({ userId, token }) }) it('Should not be able to login with this user', async function () { - await server.loginCommand.login({ user, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) + await server.login.login({ user, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) it('Should not have videos of this user', async function () { - const { data, total } = await server.videosCommand.list() + const { data, total } = await server.videos.list() expect(total).to.equal(1) const video = data[0] @@ -705,7 +705,7 @@ describe('Test users', function () { const user = { displayName: 'super user 15', username: 'user_15', password: 'my super password' } const channel = { name: 'my_user_15_channel', displayName: 'my channel rocks' } - await server.usersCommand.register({ ...user, channel }) + await server.users.register({ ...user, channel }) }) it('Should be able to login with this registered user', async function () { @@ -714,35 +714,35 @@ describe('Test users', function () { password: 'my super password' } - user15AccessToken = await server.loginCommand.getAccessToken(user15) + user15AccessToken = await server.login.getAccessToken(user15) }) it('Should have the correct display name', async function () { - const user = await server.usersCommand.getMyInfo({ token: user15AccessToken }) + const user = await server.users.getMyInfo({ token: user15AccessToken }) expect(user.account.displayName).to.equal('super user 15') }) it('Should have the correct video quota', async function () { - const user = await server.usersCommand.getMyInfo({ token: user15AccessToken }) + const user = await server.users.getMyInfo({ token: user15AccessToken }) expect(user.videoQuota).to.equal(5 * 1024 * 1024) }) it('Should have created the channel', async function () { - const { displayName } = await server.channelsCommand.get({ channelName: 'my_user_15_channel' }) + const { displayName } = await server.channels.get({ channelName: 'my_user_15_channel' }) expect(displayName).to.equal('my channel rocks') }) it('Should remove me', async function () { { - const { data } = await server.usersCommand.list() + const { data } = await server.users.list() expect(data.find(u => u.username === 'user_15')).to.not.be.undefined } - await server.usersCommand.deleteMe({ token: user15AccessToken }) + await server.users.deleteMe({ token: user15AccessToken }) { - const { data } = await server.usersCommand.list() + const { data } = await server.users.list() expect(data.find(u => u.username === 'user_15')).to.be.undefined } }) @@ -757,21 +757,21 @@ describe('Test users', function () { } it('Should block a user', async function () { - const user = await server.usersCommand.create({ ...user16 }) + const user = await server.users.create({ ...user16 }) user16Id = user.id - user16AccessToken = await server.loginCommand.getAccessToken(user16) + user16AccessToken = await server.login.getAccessToken(user16) - await server.usersCommand.getMyInfo({ token: user16AccessToken, expectedStatus: HttpStatusCode.OK_200 }) - await server.usersCommand.banUser({ userId: user16Id }) + await server.users.getMyInfo({ token: user16AccessToken, expectedStatus: HttpStatusCode.OK_200 }) + await server.users.banUser({ userId: user16Id }) - await server.usersCommand.getMyInfo({ token: user16AccessToken, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) - await server.loginCommand.login({ user: user16, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) + await server.users.getMyInfo({ token: user16AccessToken, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) + await server.login.login({ user: user16, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) it('Should search user by banned status', async function () { { - const { data, total } = await server.usersCommand.list({ start: 0, count: 2, sort: 'createdAt', blocked: true }) + const { data, total } = await server.users.list({ start: 0, count: 2, sort: 'createdAt', blocked: true }) expect(total).to.equal(1) expect(data.length).to.equal(1) @@ -779,7 +779,7 @@ describe('Test users', function () { } { - const { data, total } = await server.usersCommand.list({ start: 0, count: 2, sort: 'createdAt', blocked: false }) + const { data, total } = await server.users.list({ start: 0, count: 2, sort: 'createdAt', blocked: false }) expect(total).to.equal(1) expect(data.length).to.equal(1) @@ -788,9 +788,9 @@ describe('Test users', function () { }) it('Should unblock a user', async function () { - await server.usersCommand.unbanUser({ userId: user16Id }) - user16AccessToken = await server.loginCommand.getAccessToken(user16) - await server.usersCommand.getMyInfo({ token: user16AccessToken, expectedStatus: HttpStatusCode.OK_200 }) + await server.users.unbanUser({ userId: user16Id }) + user16AccessToken = await server.login.getAccessToken(user16) + await server.users.getMyInfo({ token: user16AccessToken, expectedStatus: HttpStatusCode.OK_200 }) }) }) @@ -803,12 +803,12 @@ describe('Test users', function () { username: 'user_17', password: 'my super password' } - const created = await server.usersCommand.create({ ...user17 }) + const created = await server.users.create({ ...user17 }) user17Id = created.id - user17AccessToken = await server.loginCommand.getAccessToken(user17) + user17AccessToken = await server.login.getAccessToken(user17) - const user = await server.usersCommand.get({ userId: user17Id, withStats: true }) + const user = await server.users.get({ userId: user17Id, withStats: true }) expect(user.videosCount).to.equal(0) expect(user.videoCommentsCount).to.equal(0) expect(user.abusesCount).to.equal(0) @@ -818,37 +818,37 @@ describe('Test users', function () { it('Should report correct videos count', async function () { const attributes = { name: 'video to test user stats' } - await server.videosCommand.upload({ token: user17AccessToken, attributes }) + await server.videos.upload({ token: user17AccessToken, attributes }) - const { data } = await server.videosCommand.list() + const { data } = await server.videos.list() videoId = data.find(video => video.name === attributes.name).id - const user = await server.usersCommand.get({ userId: user17Id, withStats: true }) + const user = await server.users.get({ userId: user17Id, withStats: true }) expect(user.videosCount).to.equal(1) }) it('Should report correct video comments for user', async function () { const text = 'super comment' - await server.commentsCommand.createThread({ token: user17AccessToken, videoId, text }) + await server.comments.createThread({ token: user17AccessToken, videoId, text }) - const user = await server.usersCommand.get({ userId: user17Id, withStats: true }) + const user = await server.users.get({ userId: user17Id, withStats: true }) expect(user.videoCommentsCount).to.equal(1) }) it('Should report correct abuses counts', async function () { const reason = 'my super bad reason' - await server.abusesCommand.report({ token: user17AccessToken, videoId, reason }) + await server.abuses.report({ token: user17AccessToken, videoId, reason }) - const body1 = await server.abusesCommand.getAdminList() + const body1 = await server.abuses.getAdminList() const abuseId = body1.data[0].id - const user2 = await server.usersCommand.get({ userId: user17Id, withStats: true }) + const user2 = await server.users.get({ userId: user17Id, withStats: true }) expect(user2.abusesCount).to.equal(1) // number of incriminations expect(user2.abusesCreatedCount).to.equal(1) // number of reports created - await server.abusesCommand.update({ abuseId, body: { state: AbuseState.ACCEPTED } }) + await server.abuses.update({ abuseId, body: { state: AbuseState.ACCEPTED } }) - const user3 = await server.usersCommand.get({ userId: user17Id, withStats: true }) + const user3 = await server.users.get({ userId: user17Id, withStats: true }) expect(user3.abusesAcceptedCount).to.equal(1) // number of reports created accepted }) }) diff --git a/server/tests/api/videos/audio-only.ts b/server/tests/api/videos/audio-only.ts index e31905b36..b2952e38b 100644 --- a/server/tests/api/videos/audio-only.ts +++ b/server/tests/api/videos/audio-only.ts @@ -48,13 +48,13 @@ describe('Test audio only video transcoding', function () { it('Should upload a video and transcode it', async function () { this.timeout(120000) - const { uuid } = await servers[0].videosCommand.upload({ attributes: { name: 'audio only' } }) + const { uuid } = await servers[0].videos.upload({ attributes: { name: 'audio only' } }) videoUUID = uuid await waitJobs(servers) for (const server of servers) { - const video = await server.videosCommand.get({ id: videoUUID }) + const video = await server.videos.get({ id: videoUUID }) expect(video.streamingPlaylists).to.have.lengthOf(1) for (const files of [ video.files, video.streamingPlaylists[0].files ]) { @@ -68,8 +68,8 @@ describe('Test audio only video transcoding', function () { it('0p transcoded video should not have video', async function () { const paths = [ - servers[0].serversCommand.buildDirectory(join('videos', videoUUID + '-0.mp4')), - servers[0].serversCommand.buildDirectory(join('streaming-playlists', 'hls', videoUUID, videoUUID + '-0-fragmented.mp4')) + servers[0].servers.buildDirectory(join('videos', videoUUID + '-0.mp4')), + servers[0].servers.buildDirectory(join('streaming-playlists', 'hls', videoUUID, videoUUID + '-0-fragmented.mp4')) ] for (const path of paths) { diff --git a/server/tests/api/videos/multiple-servers.ts b/server/tests/api/videos/multiple-servers.ts index 5c13ac629..89d842307 100644 --- a/server/tests/api/videos/multiple-servers.ts +++ b/server/tests/api/videos/multiple-servers.ts @@ -44,8 +44,8 @@ describe('Test multiple servers', function () { displayName: 'my channel', description: 'super channel' } - await servers[0].channelsCommand.create({ attributes: videoChannel }) - const { data } = await servers[0].channelsCommand.list({ start: 0, count: 1 }) + await servers[0].channels.create({ attributes: videoChannel }) + const { data } = await servers[0].channels.list({ start: 0, count: 1 }) videoChannelId = data[0].id } @@ -59,7 +59,7 @@ describe('Test multiple servers', function () { it('Should not have videos for all servers', async function () { for (const server of servers) { - const { data } = await server.videosCommand.list() + const { data } = await server.videos.list() expect(data).to.be.an('array') expect(data.length).to.equal(0) } @@ -82,7 +82,7 @@ describe('Test multiple servers', function () { channelId: videoChannelId, fixture: 'video_short1.webm' } - await servers[0].videosCommand.upload({ attributes }) + await servers[0].videos.upload({ attributes }) await waitJobs(servers) @@ -125,7 +125,7 @@ describe('Test multiple servers', function () { ] } - const { data } = await server.videosCommand.list() + const { data } = await server.videos.list() expect(data).to.be.an('array') expect(data.length).to.equal(1) const video = data[0] @@ -142,8 +142,8 @@ describe('Test multiple servers', function () { username: 'user1', password: 'super_password' } - await servers[1].usersCommand.create({ username: user.username, password: user.password }) - const userAccessToken = await servers[1].loginCommand.getAccessToken(user) + await servers[1].users.create({ username: user.username, password: user.password }) + const userAccessToken = await servers[1].login.getAccessToken(user) const attributes = { name: 'my super name for server 2', @@ -158,7 +158,7 @@ describe('Test multiple servers', function () { thumbnailfile: 'thumbnail.jpg', previewfile: 'preview.jpg' } - await servers[1].videosCommand.upload({ token: userAccessToken, attributes, mode: 'resumable' }) + await servers[1].videos.upload({ token: userAccessToken, attributes, mode: 'resumable' }) // Transcoding await waitJobs(servers) @@ -213,7 +213,7 @@ describe('Test multiple servers', function () { previewfile: 'preview' } - const { data } = await server.videosCommand.list() + const { data } = await server.videos.list() expect(data).to.be.an('array') expect(data.length).to.equal(2) const video = data[1] @@ -237,7 +237,7 @@ describe('Test multiple servers', function () { tags: [ 'tag1p3' ], fixture: 'video_short3.webm' } - await servers[2].videosCommand.upload({ attributes }) + await servers[2].videos.upload({ attributes }) } { @@ -252,7 +252,7 @@ describe('Test multiple servers', function () { tags: [ 'tag2p3', 'tag3p3', 'tag4p3' ], fixture: 'video_short.webm' } - await servers[2].videosCommand.upload({ attributes }) + await servers[2].videos.upload({ attributes }) } await waitJobs(servers) @@ -260,7 +260,7 @@ describe('Test multiple servers', function () { // All servers should have this video for (const server of servers) { const isLocal = server.url === 'http://localhost:' + servers[2].port - const { data } = await server.videosCommand.list() + const { data } = await server.videos.list() expect(data).to.be.an('array') expect(data.length).to.equal(4) @@ -349,7 +349,7 @@ describe('Test multiple servers', function () { describe('It should list local videos', function () { it('Should list only local videos on server 1', async function () { - const { data, total } = await servers[0].videosCommand.list({ filter: 'local' }) + const { data, total } = await servers[0].videos.list({ filter: 'local' }) expect(total).to.equal(1) expect(data).to.be.an('array') @@ -358,7 +358,7 @@ describe('Test multiple servers', function () { }) it('Should list only local videos on server 2', async function () { - const { data, total } = await servers[1].videosCommand.list({ filter: 'local' }) + const { data, total } = await servers[1].videos.list({ filter: 'local' }) expect(total).to.equal(1) expect(data).to.be.an('array') @@ -367,7 +367,7 @@ describe('Test multiple servers', function () { }) it('Should list only local videos on server 3', async function () { - const { data, total } = await servers[2].videosCommand.list({ filter: 'local' }) + const { data, total } = await servers[2].videos.list({ filter: 'local' }) expect(total).to.equal(2) expect(data).to.be.an('array') @@ -381,13 +381,13 @@ describe('Test multiple servers', function () { it('Should add the file 1 by asking server 3', async function () { this.timeout(10000) - const { data } = await servers[2].videosCommand.list() + const { data } = await servers[2].videos.list() const video = data[0] toRemove.push(data[2]) toRemove.push(data[3]) - const videoDetails = await servers[2].videosCommand.get({ id: video.id }) + const videoDetails = await servers[2].videos.get({ id: video.id }) const torrent = await webtorrentAdd(videoDetails.files[0].magnetUri, true) expect(torrent.files).to.be.an('array') expect(torrent.files.length).to.equal(1) @@ -397,10 +397,10 @@ describe('Test multiple servers', function () { it('Should add the file 2 by asking server 1', async function () { this.timeout(10000) - const { data } = await servers[0].videosCommand.list() + const { data } = await servers[0].videos.list() const video = data[1] - const videoDetails = await servers[0].videosCommand.get({ id: video.id }) + const videoDetails = await servers[0].videos.get({ id: video.id }) const torrent = await webtorrentAdd(videoDetails.files[0].magnetUri, true) expect(torrent.files).to.be.an('array') @@ -411,10 +411,10 @@ describe('Test multiple servers', function () { it('Should add the file 3 by asking server 2', async function () { this.timeout(10000) - const { data } = await servers[1].videosCommand.list() + const { data } = await servers[1].videos.list() const video = data[2] - const videoDetails = await servers[1].videosCommand.get({ id: video.id }) + const videoDetails = await servers[1].videos.get({ id: video.id }) const torrent = await webtorrentAdd(videoDetails.files[0].magnetUri, true) expect(torrent.files).to.be.an('array') @@ -425,10 +425,10 @@ describe('Test multiple servers', function () { it('Should add the file 3-2 by asking server 1', async function () { this.timeout(10000) - const { data } = await servers[0].videosCommand.list() + const { data } = await servers[0].videos.list() const video = data[3] - const videoDetails = await servers[0].videosCommand.get({ id: video.id }) + const videoDetails = await servers[0].videos.get({ id: video.id }) const torrent = await webtorrentAdd(videoDetails.files[0].magnetUri) expect(torrent.files).to.be.an('array') @@ -439,10 +439,10 @@ describe('Test multiple servers', function () { it('Should add the file 2 in 360p by asking server 1', async function () { this.timeout(10000) - const { data } = await servers[0].videosCommand.list() + const { data } = await servers[0].videos.list() const video = data.find(v => v.name === 'my super name for server 2') - const videoDetails = await servers[0].videosCommand.get({ id: video.id }) + const videoDetails = await servers[0].videos.get({ id: video.id }) const file = videoDetails.files.find(f => f.resolution.id === 360) expect(file).not.to.be.undefined @@ -462,17 +462,17 @@ describe('Test multiple servers', function () { before(async function () { { - const { data } = await servers[0].videosCommand.list() + const { data } = await servers[0].videos.list() remoteVideosServer1 = data.filter(video => video.isLocal === false).map(video => video.uuid) } { - const { data } = await servers[1].videosCommand.list() + const { data } = await servers[1].videos.list() remoteVideosServer2 = data.filter(video => video.isLocal === false).map(video => video.uuid) } { - const { data } = await servers[2].videosCommand.list() + const { data } = await servers[2].videos.list() localVideosServer3 = data.filter(video => video.isLocal === true).map(video => video.uuid) remoteVideosServer3 = data.filter(video => video.isLocal === false).map(video => video.uuid) } @@ -481,16 +481,16 @@ describe('Test multiple servers', function () { it('Should view multiple videos on owned servers', async function () { this.timeout(30000) - await servers[2].videosCommand.view({ id: localVideosServer3[0] }) + await servers[2].videos.view({ id: localVideosServer3[0] }) await wait(1000) - await servers[2].videosCommand.view({ id: localVideosServer3[0] }) - await servers[2].videosCommand.view({ id: localVideosServer3[1] }) + await servers[2].videos.view({ id: localVideosServer3[0] }) + await servers[2].videos.view({ id: localVideosServer3[1] }) await wait(1000) - await servers[2].videosCommand.view({ id: localVideosServer3[0] }) - await servers[2].videosCommand.view({ id: localVideosServer3[0] }) + await servers[2].videos.view({ id: localVideosServer3[0] }) + await servers[2].videos.view({ id: localVideosServer3[0] }) await waitJobs(servers) @@ -500,7 +500,7 @@ describe('Test multiple servers', function () { await waitJobs(servers) for (const server of servers) { - const { data } = await server.videosCommand.list() + const { data } = await server.videos.list() const video0 = data.find(v => v.uuid === localVideosServer3[0]) const video1 = data.find(v => v.uuid === localVideosServer3[1]) @@ -514,16 +514,16 @@ describe('Test multiple servers', function () { this.timeout(45000) const tasks: Promise[] = [] - tasks.push(servers[0].videosCommand.view({ id: remoteVideosServer1[0] })) - tasks.push(servers[1].videosCommand.view({ id: remoteVideosServer2[0] })) - tasks.push(servers[1].videosCommand.view({ id: remoteVideosServer2[0] })) - tasks.push(servers[2].videosCommand.view({ id: remoteVideosServer3[0] })) - tasks.push(servers[2].videosCommand.view({ id: remoteVideosServer3[1] })) - tasks.push(servers[2].videosCommand.view({ id: remoteVideosServer3[1] })) - tasks.push(servers[2].videosCommand.view({ id: remoteVideosServer3[1] })) - tasks.push(servers[2].videosCommand.view({ id: localVideosServer3[1] })) - tasks.push(servers[2].videosCommand.view({ id: localVideosServer3[1] })) - tasks.push(servers[2].videosCommand.view({ id: localVideosServer3[1] })) + tasks.push(servers[0].videos.view({ id: remoteVideosServer1[0] })) + tasks.push(servers[1].videos.view({ id: remoteVideosServer2[0] })) + tasks.push(servers[1].videos.view({ id: remoteVideosServer2[0] })) + tasks.push(servers[2].videos.view({ id: remoteVideosServer3[0] })) + tasks.push(servers[2].videos.view({ id: remoteVideosServer3[1] })) + tasks.push(servers[2].videos.view({ id: remoteVideosServer3[1] })) + tasks.push(servers[2].videos.view({ id: remoteVideosServer3[1] })) + tasks.push(servers[2].videos.view({ id: localVideosServer3[1] })) + tasks.push(servers[2].videos.view({ id: localVideosServer3[1] })) + tasks.push(servers[2].videos.view({ id: localVideosServer3[1] })) await Promise.all(tasks) @@ -537,7 +537,7 @@ describe('Test multiple servers', function () { let baseVideos = null for (const server of servers) { - const { data } = await server.videosCommand.list() + const { data } = await server.videos.list() // Initialize base videos for future comparisons if (baseVideos === null) { @@ -555,17 +555,17 @@ describe('Test multiple servers', function () { it('Should like and dislikes videos on different services', async function () { this.timeout(50000) - await servers[0].videosCommand.rate({ id: remoteVideosServer1[0], rating: 'like' }) + await servers[0].videos.rate({ id: remoteVideosServer1[0], rating: 'like' }) await wait(500) - await servers[0].videosCommand.rate({ id: remoteVideosServer1[0], rating: 'dislike' }) + await servers[0].videos.rate({ id: remoteVideosServer1[0], rating: 'dislike' }) await wait(500) - await servers[0].videosCommand.rate({ id: remoteVideosServer1[0], rating: 'like' }) - await servers[2].videosCommand.rate({ id: localVideosServer3[1], rating: 'like' }) + await servers[0].videos.rate({ id: remoteVideosServer1[0], rating: 'like' }) + await servers[2].videos.rate({ id: localVideosServer3[1], rating: 'like' }) await wait(500) - await servers[2].videosCommand.rate({ id: localVideosServer3[1], rating: 'dislike' }) - await servers[2].videosCommand.rate({ id: remoteVideosServer3[1], rating: 'dislike' }) + await servers[2].videos.rate({ id: localVideosServer3[1], rating: 'dislike' }) + await servers[2].videos.rate({ id: remoteVideosServer3[1], rating: 'dislike' }) await wait(500) - await servers[2].videosCommand.rate({ id: remoteVideosServer3[0], rating: 'like' }) + await servers[2].videos.rate({ id: remoteVideosServer3[0], rating: 'like' }) await waitJobs(servers) await wait(5000) @@ -573,7 +573,7 @@ describe('Test multiple servers', function () { let baseVideos = null for (const server of servers) { - const { data } = await server.videosCommand.list() + const { data } = await server.videos.list() // Initialize base videos for future comparisons if (baseVideos === null) { @@ -608,7 +608,7 @@ describe('Test multiple servers', function () { previewfile: 'preview.jpg' } - await servers[2].videosCommand.update({ id: toRemove[0].id, attributes }) + await servers[2].videos.update({ id: toRemove[0].id, attributes }) await waitJobs(servers) }) @@ -617,7 +617,7 @@ describe('Test multiple servers', function () { this.timeout(10000) for (const server of servers) { - const { data } = await server.videosCommand.list() + const { data } = await server.videos.list() const videoUpdated = data.find(video => video.name === 'my super video updated') expect(!!videoUpdated).to.be.true @@ -665,8 +665,8 @@ describe('Test multiple servers', function () { it('Should remove the videos 3 and 3-2 by asking server 3', async function () { this.timeout(10000) - await servers[2].videosCommand.remove({ id: toRemove[0].id }) - await servers[2].videosCommand.remove({ id: toRemove[1].id }) + await servers[2].videos.remove({ id: toRemove[0].id }) + await servers[2].videos.remove({ id: toRemove[1].id }) await waitJobs(servers) }) @@ -680,7 +680,7 @@ describe('Test multiple servers', function () { it('Should have videos 1 and 3 on each server', async function () { for (const server of servers) { - const { data } = await server.videosCommand.list() + const { data } = await server.videos.list() expect(data).to.be.an('array') expect(data.length).to.equal(2) @@ -697,7 +697,7 @@ describe('Test multiple servers', function () { it('Should get the same video by UUID on each server', async function () { let baseVideo = null for (const server of servers) { - const video = await server.videosCommand.get({ id: videoUUID }) + const video = await server.videos.get({ id: videoUUID }) if (baseVideo === null) { baseVideo = video @@ -720,7 +720,7 @@ describe('Test multiple servers', function () { it('Should get the preview from each server', async function () { for (const server of servers) { - const video = await server.videosCommand.get({ id: videoUUID }) + const video = await server.videos.get({ id: videoUUID }) await testImage(server.url, 'video_short1-preview.webm', video.previewPath) } @@ -735,36 +735,36 @@ describe('Test multiple servers', function () { { const text = 'my super first comment' - await servers[0].commentsCommand.createThread({ videoId: videoUUID, text }) + await servers[0].comments.createThread({ videoId: videoUUID, text }) } { const text = 'my super second comment' - await servers[2].commentsCommand.createThread({ videoId: videoUUID, text }) + await servers[2].comments.createThread({ videoId: videoUUID, text }) } await waitJobs(servers) { - const threadId = await servers[1].commentsCommand.findCommentId({ videoId: videoUUID, text: 'my super first comment' }) + const threadId = await servers[1].comments.findCommentId({ videoId: videoUUID, text: 'my super first comment' }) const text = 'my super answer to thread 1' - await servers[1].commentsCommand.addReply({ videoId: videoUUID, toCommentId: threadId, text }) + await servers[1].comments.addReply({ videoId: videoUUID, toCommentId: threadId, text }) } await waitJobs(servers) { - const threadId = await servers[2].commentsCommand.findCommentId({ videoId: videoUUID, text: 'my super first comment' }) + const threadId = await servers[2].comments.findCommentId({ videoId: videoUUID, text: 'my super first comment' }) - const body = await servers[2].commentsCommand.getThread({ videoId: videoUUID, threadId }) + const body = await servers[2].comments.getThread({ videoId: videoUUID, threadId }) const childCommentId = body.children[0].comment.id const text3 = 'my second answer to thread 1' - await servers[2].commentsCommand.addReply({ videoId: videoUUID, toCommentId: threadId, text: text3 }) + await servers[2].comments.addReply({ videoId: videoUUID, toCommentId: threadId, text: text3 }) const text2 = 'my super answer to answer of thread 1' - await servers[2].commentsCommand.addReply({ videoId: videoUUID, toCommentId: childCommentId, text: text2 }) + await servers[2].comments.addReply({ videoId: videoUUID, toCommentId: childCommentId, text: text2 }) } await waitJobs(servers) @@ -772,7 +772,7 @@ describe('Test multiple servers', function () { it('Should have these threads', async function () { for (const server of servers) { - const body = await server.commentsCommand.listThreads({ videoId: videoUUID }) + const body = await server.comments.listThreads({ videoId: videoUUID }) expect(body.total).to.equal(2) expect(body.data).to.be.an('array') @@ -804,10 +804,10 @@ describe('Test multiple servers', function () { it('Should have these comments', async function () { for (const server of servers) { - const body = await server.commentsCommand.listThreads({ videoId: videoUUID }) + const body = await server.comments.listThreads({ videoId: videoUUID }) const threadId = body.data.find(c => c.text === 'my super first comment').id - const tree = await server.commentsCommand.getThread({ videoId: videoUUID, threadId }) + const tree = await server.comments.getThread({ videoId: videoUUID, threadId }) expect(tree.comment.text).equal('my super first comment') expect(tree.comment.account.name).equal('root') @@ -837,17 +837,17 @@ describe('Test multiple servers', function () { it('Should delete a reply', async function () { this.timeout(10000) - await servers[2].commentsCommand.delete({ videoId: videoUUID, commentId: childOfFirstChild.comment.id }) + await servers[2].comments.delete({ videoId: videoUUID, commentId: childOfFirstChild.comment.id }) await waitJobs(servers) }) it('Should have this comment marked as deleted', async function () { for (const server of servers) { - const { data } = await server.commentsCommand.listThreads({ videoId: videoUUID }) + const { data } = await server.comments.listThreads({ videoId: videoUUID }) const threadId = data.find(c => c.text === 'my super first comment').id - const tree = await server.commentsCommand.getThread({ videoId: videoUUID, threadId }) + const tree = await server.comments.getThread({ videoId: videoUUID, threadId }) expect(tree.comment.text).equal('my super first comment') const firstChild = tree.children[0] @@ -868,16 +868,16 @@ describe('Test multiple servers', function () { it('Should delete the thread comments', async function () { this.timeout(10000) - const { data } = await servers[0].commentsCommand.listThreads({ videoId: videoUUID }) + const { data } = await servers[0].comments.listThreads({ videoId: videoUUID }) const commentId = data.find(c => c.text === 'my super first comment').id - await servers[0].commentsCommand.delete({ videoId: videoUUID, commentId }) + await servers[0].comments.delete({ videoId: videoUUID, commentId }) await waitJobs(servers) }) it('Should have the threads marked as deleted on other servers too', async function () { for (const server of servers) { - const body = await server.commentsCommand.listThreads({ videoId: videoUUID }) + const body = await server.comments.listThreads({ videoId: videoUUID }) expect(body.total).to.equal(2) expect(body.data).to.be.an('array') @@ -913,16 +913,16 @@ describe('Test multiple servers', function () { it('Should delete a remote thread by the origin server', async function () { this.timeout(5000) - const { data } = await servers[0].commentsCommand.listThreads({ videoId: videoUUID }) + const { data } = await servers[0].comments.listThreads({ videoId: videoUUID }) const commentId = data.find(c => c.text === 'my super second comment').id - await servers[0].commentsCommand.delete({ videoId: videoUUID, commentId }) + await servers[0].comments.delete({ videoId: videoUUID, commentId }) await waitJobs(servers) }) it('Should have the threads marked as deleted on other servers too', async function () { for (const server of servers) { - const body = await server.commentsCommand.listThreads({ videoId: videoUUID }) + const body = await server.comments.listThreads({ videoId: videoUUID }) expect(body.total).to.equal(2) expect(body.data).to.have.lengthOf(2) @@ -957,17 +957,17 @@ describe('Test multiple servers', function () { downloadEnabled: false } - await servers[0].videosCommand.update({ id: videoUUID, attributes }) + await servers[0].videos.update({ id: videoUUID, attributes }) await waitJobs(servers) for (const server of servers) { - const video = await server.videosCommand.get({ id: videoUUID }) + const video = await server.videos.get({ id: videoUUID }) expect(video.commentsEnabled).to.be.false expect(video.downloadEnabled).to.be.false const text = 'my super forbidden comment' - await server.commentsCommand.createThread({ videoId: videoUUID, text, expectedStatus: HttpStatusCode.CONFLICT_409 }) + await server.comments.createThread({ videoId: videoUUID, text, expectedStatus: HttpStatusCode.CONFLICT_409 }) } }) }) @@ -992,7 +992,7 @@ describe('Test multiple servers', function () { await waitJobs(servers) for (const server of servers) { - const { data } = await server.videosCommand.list() + const { data } = await server.videos.list() const video = data.find(v => v.name === 'minimum parameters') const isLocal = server.url === 'http://localhost:' + servers[1].port diff --git a/server/tests/api/videos/resumable-upload.ts b/server/tests/api/videos/resumable-upload.ts index b7756a4a8..2f1cf8a55 100644 --- a/server/tests/api/videos/resumable-upload.ts +++ b/server/tests/api/videos/resumable-upload.ts @@ -36,14 +36,14 @@ describe('Test resumable upload', function () { const attributes = { name: 'video', - channelId: server.videoChannel.id, + channelId: server.store.channel.id, privacy: VideoPrivacy.PUBLIC, fixture: defaultFixture } const mimetype = 'video/mp4' - const res = await server.videosCommand.prepareResumableUpload({ attributes, size, mimetype }) + const res = await server.videos.prepareResumableUpload({ attributes, size, mimetype }) return res.header['location'].split('?')[1] } @@ -61,7 +61,7 @@ describe('Test resumable upload', function () { const size = await buildSize(defaultFixture, options.size) const absoluteFilePath = buildAbsoluteFixturePath(defaultFixture) - return server.videosCommand.sendResumableChunks({ + return server.videos.sendResumableChunks({ pathUploadId, videoFilePath: absoluteFilePath, size, @@ -75,7 +75,7 @@ describe('Test resumable upload', function () { const uploadId = uploadIdArg.replace(/^upload_id=/, '') const subPath = join('tmp', 'resumable-uploads', uploadId) - const filePath = server.serversCommand.buildDirectory(subPath) + const filePath = server.servers.buildDirectory(subPath) const exists = await pathExists(filePath) if (expectedSize === null) { @@ -90,7 +90,7 @@ describe('Test resumable upload', function () { async function countResumableUploads () { const subPath = join('tmp', 'resumable-uploads') - const filePath = server.serversCommand.buildDirectory(subPath) + const filePath = server.servers.buildDirectory(subPath) const files = await readdir(filePath) return files.length @@ -103,10 +103,10 @@ describe('Test resumable upload', function () { await setAccessTokensToServers([ server ]) await setDefaultVideoChannel([ server ]) - const body = await server.usersCommand.getMyInfo() + const body = await server.users.getMyInfo() rootId = body.id - await server.usersCommand.update({ userId: rootId, videoQuota: 10_000_000 }) + await server.users.update({ userId: rootId, videoQuota: 10_000_000 }) }) describe('Directory cleaning', function () { @@ -125,13 +125,13 @@ describe('Test resumable upload', function () { }) it('Should not delete recent uploads', async function () { - await server.debugCommand.sendCommand({ body: { command: 'remove-dandling-resumable-uploads' } }) + await server.debug.sendCommand({ body: { command: 'remove-dandling-resumable-uploads' } }) expect(await countResumableUploads()).to.equal(2) }) it('Should delete old uploads', async function () { - await server.debugCommand.sendCommand({ body: { command: 'remove-dandling-resumable-uploads' } }) + await server.debug.sendCommand({ body: { command: 'remove-dandling-resumable-uploads' } }) expect(await countResumableUploads()).to.equal(0) }) diff --git a/server/tests/api/videos/single-server.ts b/server/tests/api/videos/single-server.ts index da0b2011e..12c1f7b2f 100644 --- a/server/tests/api/videos/single-server.ts +++ b/server/tests/api/videos/single-server.ts @@ -100,35 +100,35 @@ describe('Test a single server', function () { }) it('Should list video categories', async function () { - const categories = await server.videosCommand.getCategories() + const categories = await server.videos.getCategories() expect(Object.keys(categories)).to.have.length.above(10) expect(categories[11]).to.equal('News & Politics') }) it('Should list video licences', async function () { - const licences = await server.videosCommand.getLicences() + const licences = await server.videos.getLicences() expect(Object.keys(licences)).to.have.length.above(5) expect(licences[3]).to.equal('Attribution - No Derivatives') }) it('Should list video languages', async function () { - const languages = await server.videosCommand.getLanguages() + const languages = await server.videos.getLanguages() expect(Object.keys(languages)).to.have.length.above(5) expect(languages['ru']).to.equal('Russian') }) it('Should list video privacies', async function () { - const privacies = await server.videosCommand.getPrivacies() + const privacies = await server.videos.getPrivacies() expect(Object.keys(privacies)).to.have.length.at.least(3) expect(privacies[3]).to.equal('Private') }) it('Should not have videos', async function () { - const { data, total } = await server.videosCommand.list() + const { data, total } = await server.videos.list() expect(total).to.equal(0) expect(data).to.be.an('array') @@ -145,7 +145,7 @@ describe('Test a single server', function () { licence: 6, tags: [ 'tag1', 'tag2', 'tag3' ] } - const video = await server.videosCommand.upload({ attributes, mode }) + const video = await server.videos.upload({ attributes, mode }) expect(video).to.not.be.undefined expect(video.id).to.equal(1) expect(video.uuid).to.have.length.above(5) @@ -157,7 +157,7 @@ describe('Test a single server', function () { it('Should get and seed the uploaded video', async function () { this.timeout(5000) - const { data, total } = await server.videosCommand.list() + const { data, total } = await server.videos.list() expect(total).to.equal(1) expect(data).to.be.an('array') @@ -170,42 +170,42 @@ describe('Test a single server', function () { it('Should get the video by UUID', async function () { this.timeout(5000) - const video = await server.videosCommand.get({ id: videoUUID }) + const video = await server.videos.get({ id: videoUUID }) await completeVideoCheck(server, video, getCheckAttributes()) }) it('Should have the views updated', async function () { this.timeout(20000) - await server.videosCommand.view({ id: videoId }) - await server.videosCommand.view({ id: videoId }) - await server.videosCommand.view({ id: videoId }) + await server.videos.view({ id: videoId }) + await server.videos.view({ id: videoId }) + await server.videos.view({ id: videoId }) await wait(1500) - await server.videosCommand.view({ id: videoId }) - await server.videosCommand.view({ id: videoId }) + await server.videos.view({ id: videoId }) + await server.videos.view({ id: videoId }) await wait(1500) - await server.videosCommand.view({ id: videoId }) - await server.videosCommand.view({ id: videoId }) + await server.videos.view({ id: videoId }) + await server.videos.view({ id: videoId }) // Wait the repeatable job await wait(8000) - const video = await server.videosCommand.get({ id: videoId }) + const video = await server.videos.get({ id: videoId }) expect(video.views).to.equal(3) }) it('Should remove the video', async function () { - await server.videosCommand.remove({ id: videoId }) + await server.videos.remove({ id: videoId }) await checkVideoFilesWereRemoved(videoUUID, server) }) it('Should not have videos', async function () { - const { total, data } = await server.videosCommand.list() + const { total, data } = await server.videos.list() expect(total).to.equal(0) expect(data).to.be.an('array') @@ -232,12 +232,12 @@ describe('Test a single server', function () { fixture: video } - await server.videosCommand.upload({ attributes, mode }) + await server.videos.upload({ attributes, mode }) } }) it('Should have the correct durations', async function () { - const { total, data } = await server.videosCommand.list() + const { total, data } = await server.videos.list() expect(total).to.equal(6) expect(data).to.be.an('array') @@ -255,7 +255,7 @@ describe('Test a single server', function () { }) it('Should have the correct thumbnails', async function () { - const { data } = await server.videosCommand.list() + const { data } = await server.videos.list() // For the next test videosListBase = data @@ -267,7 +267,7 @@ describe('Test a single server', function () { }) it('Should list only the two first videos', async function () { - const { total, data } = await server.videosCommand.list({ start: 0, count: 2, sort: 'name' }) + const { total, data } = await server.videos.list({ start: 0, count: 2, sort: 'name' }) expect(total).to.equal(6) expect(data.length).to.equal(2) @@ -276,7 +276,7 @@ describe('Test a single server', function () { }) it('Should list only the next three videos', async function () { - const { total, data } = await server.videosCommand.list({ start: 2, count: 3, sort: 'name' }) + const { total, data } = await server.videos.list({ start: 2, count: 3, sort: 'name' }) expect(total).to.equal(6) expect(data.length).to.equal(3) @@ -286,7 +286,7 @@ describe('Test a single server', function () { }) it('Should list the last video', async function () { - const { total, data } = await server.videosCommand.list({ start: 5, count: 6, sort: 'name' }) + const { total, data } = await server.videos.list({ start: 5, count: 6, sort: 'name' }) expect(total).to.equal(6) expect(data.length).to.equal(1) @@ -294,7 +294,7 @@ describe('Test a single server', function () { }) it('Should not have the total field', async function () { - const { total, data } = await server.videosCommand.list({ start: 5, count: 6, sort: 'name', skipCount: true }) + const { total, data } = await server.videos.list({ start: 5, count: 6, sort: 'name', skipCount: true }) expect(total).to.not.exist expect(data.length).to.equal(1) @@ -302,7 +302,7 @@ describe('Test a single server', function () { }) it('Should list and sort by name in descending order', async function () { - const { total, data } = await server.videosCommand.list({ sort: '-name' }) + const { total, data } = await server.videos.list({ sort: '-name' }) expect(total).to.equal(6) expect(data.length).to.equal(6) @@ -318,21 +318,21 @@ describe('Test a single server', function () { }) it('Should list and sort by trending in descending order', async function () { - const { total, data } = await server.videosCommand.list({ start: 0, count: 2, sort: '-trending' }) + const { total, data } = await server.videos.list({ start: 0, count: 2, sort: '-trending' }) expect(total).to.equal(6) expect(data.length).to.equal(2) }) it('Should list and sort by hotness in descending order', async function () { - const { total, data } = await server.videosCommand.list({ start: 0, count: 2, sort: '-hot' }) + const { total, data } = await server.videos.list({ start: 0, count: 2, sort: '-hot' }) expect(total).to.equal(6) expect(data.length).to.equal(2) }) it('Should list and sort by best in descending order', async function () { - const { total, data } = await server.videosCommand.list({ start: 0, count: 2, sort: '-best' }) + const { total, data } = await server.videos.list({ start: 0, count: 2, sort: '-best' }) expect(total).to.equal(6) expect(data.length).to.equal(2) @@ -350,18 +350,18 @@ describe('Test a single server', function () { downloadEnabled: false, tags: [ 'tagup1', 'tagup2' ] } - await server.videosCommand.update({ id: videoId, attributes }) + await server.videos.update({ id: videoId, attributes }) }) it('Should filter by tags and category', async function () { { - const { data, total } = await server.videosCommand.list({ tagsAllOf: [ 'tagup1', 'tagup2' ], categoryOneOf: [ 4 ] }) + const { data, total } = await server.videos.list({ tagsAllOf: [ 'tagup1', 'tagup2' ], categoryOneOf: [ 4 ] }) expect(total).to.equal(1) expect(data[0].name).to.equal('my super video updated') } { - const { total } = await server.videosCommand.list({ tagsAllOf: [ 'tagup1', 'tagup2' ], categoryOneOf: [ 3 ] }) + const { total } = await server.videos.list({ tagsAllOf: [ 'tagup1', 'tagup2' ], categoryOneOf: [ 3 ] }) expect(total).to.equal(0) } }) @@ -369,7 +369,7 @@ describe('Test a single server', function () { it('Should have the video updated', async function () { this.timeout(60000) - const video = await server.videosCommand.get({ id: videoId }) + const video = await server.videos.get({ id: videoId }) await completeVideoCheck(server, video, updateCheckAttributes()) }) @@ -378,9 +378,9 @@ describe('Test a single server', function () { const attributes = { tags: [ 'supertag', 'tag1', 'tag2' ] } - await server.videosCommand.update({ id: videoId, attributes }) + await server.videos.update({ id: videoId, attributes }) - const video = await server.videosCommand.get({ id: videoId }) + const video = await server.videos.get({ id: videoId }) await completeVideoCheck(server, video, Object.assign(updateCheckAttributes(), attributes)) }) @@ -389,27 +389,27 @@ describe('Test a single server', function () { const attributes = { description: 'hello everybody' } - await server.videosCommand.update({ id: videoId, attributes }) + await server.videos.update({ id: videoId, attributes }) - const video = await server.videosCommand.get({ id: videoId }) + const video = await server.videos.get({ id: videoId }) const expectedAttributes = Object.assign(updateCheckAttributes(), { tags: [ 'supertag', 'tag1', 'tag2' ] }, attributes) await completeVideoCheck(server, video, expectedAttributes) }) it('Should like a video', async function () { - await server.videosCommand.rate({ id: videoId, rating: 'like' }) + await server.videos.rate({ id: videoId, rating: 'like' }) - const video = await server.videosCommand.get({ id: videoId }) + const video = await server.videos.get({ id: videoId }) expect(video.likes).to.equal(1) expect(video.dislikes).to.equal(0) }) it('Should dislike the same video', async function () { - await server.videosCommand.rate({ id: videoId, rating: 'dislike' }) + await server.videos.rate({ id: videoId, rating: 'dislike' }) - const video = await server.videosCommand.get({ id: videoId }) + const video = await server.videos.get({ id: videoId }) expect(video.likes).to.equal(0) expect(video.dislikes).to.equal(1) @@ -419,9 +419,9 @@ describe('Test a single server', function () { { const now = new Date() const attributes = { originallyPublishedAt: now.toISOString() } - await server.videosCommand.update({ id: videoId, attributes }) + await server.videos.update({ id: videoId, attributes }) - const { data } = await server.videosCommand.list({ sort: '-originallyPublishedAt' }) + const { data } = await server.videos.list({ sort: '-originallyPublishedAt' }) const names = data.map(v => v.name) expect(names[0]).to.equal('my super video updated') @@ -435,9 +435,9 @@ describe('Test a single server', function () { { const now = new Date() const attributes = { originallyPublishedAt: now.toISOString() } - await server.videosCommand.update({ id: videoId2, attributes }) + await server.videos.update({ id: videoId2, attributes }) - const { data } = await server.videosCommand.list({ sort: '-originallyPublishedAt' }) + const { data } = await server.videos.list({ sort: '-originallyPublishedAt' }) const names = data.map(v => v.name) expect(names[0]).to.equal('video_short1.webm name') diff --git a/server/tests/api/videos/video-captions.ts b/server/tests/api/videos/video-captions.ts index 4c67e96f7..abc07194d 100644 --- a/server/tests/api/videos/video-captions.ts +++ b/server/tests/api/videos/video-captions.ts @@ -32,7 +32,7 @@ describe('Test video captions', function () { await waitJobs(servers) - const { uuid } = await servers[0].videosCommand.upload({ attributes: { name: 'my video name' } }) + const { uuid } = await servers[0].videos.upload({ attributes: { name: 'my video name' } }) videoUUID = uuid await waitJobs(servers) @@ -40,7 +40,7 @@ describe('Test video captions', function () { it('Should list the captions and return an empty list', async function () { for (const server of servers) { - const body = await server.captionsCommand.listVideoCaptions({ videoId: videoUUID }) + const body = await server.captions.listVideoCaptions({ videoId: videoUUID }) expect(body.total).to.equal(0) expect(body.data).to.have.lengthOf(0) } @@ -49,13 +49,13 @@ describe('Test video captions', function () { it('Should create two new captions', async function () { this.timeout(30000) - await servers[0].captionsCommand.createVideoCaption({ + await servers[0].captions.createVideoCaption({ language: 'ar', videoId: videoUUID, fixture: 'subtitle-good1.vtt' }) - await servers[0].captionsCommand.createVideoCaption({ + await servers[0].captions.createVideoCaption({ language: 'zh', videoId: videoUUID, fixture: 'subtitle-good2.vtt', @@ -67,7 +67,7 @@ describe('Test video captions', function () { it('Should list these uploaded captions', async function () { for (const server of servers) { - const body = await server.captionsCommand.listVideoCaptions({ videoId: videoUUID }) + const body = await server.captions.listVideoCaptions({ videoId: videoUUID }) expect(body.total).to.equal(2) expect(body.data).to.have.lengthOf(2) @@ -88,7 +88,7 @@ describe('Test video captions', function () { it('Should replace an existing caption', async function () { this.timeout(30000) - await servers[0].captionsCommand.createVideoCaption({ + await servers[0].captions.createVideoCaption({ language: 'ar', videoId: videoUUID, fixture: 'subtitle-good2.vtt' @@ -99,7 +99,7 @@ describe('Test video captions', function () { it('Should have this caption updated', async function () { for (const server of servers) { - const body = await server.captionsCommand.listVideoCaptions({ videoId: videoUUID }) + const body = await server.captions.listVideoCaptions({ videoId: videoUUID }) expect(body.total).to.equal(2) expect(body.data).to.have.lengthOf(2) @@ -114,7 +114,7 @@ describe('Test video captions', function () { it('Should replace an existing caption with a srt file and convert it', async function () { this.timeout(30000) - await servers[0].captionsCommand.createVideoCaption({ + await servers[0].captions.createVideoCaption({ language: 'ar', videoId: videoUUID, fixture: 'subtitle-good.srt' @@ -128,7 +128,7 @@ describe('Test video captions', function () { it('Should have this caption updated and converted', async function () { for (const server of servers) { - const body = await server.captionsCommand.listVideoCaptions({ videoId: videoUUID }) + const body = await server.captions.listVideoCaptions({ videoId: videoUUID }) expect(body.total).to.equal(2) expect(body.data).to.have.lengthOf(2) @@ -157,14 +157,14 @@ describe('Test video captions', function () { it('Should remove one caption', async function () { this.timeout(30000) - await servers[0].captionsCommand.deleteVideoCaption({ videoId: videoUUID, language: 'ar' }) + await servers[0].captions.deleteVideoCaption({ videoId: videoUUID, language: 'ar' }) await waitJobs(servers) }) it('Should only list the caption that was not deleted', async function () { for (const server of servers) { - const body = await server.captionsCommand.listVideoCaptions({ videoId: videoUUID }) + const body = await server.captions.listVideoCaptions({ videoId: videoUUID }) expect(body.total).to.equal(1) expect(body.data).to.have.lengthOf(1) @@ -178,7 +178,7 @@ describe('Test video captions', function () { }) it('Should remove the video, and thus all video captions', async function () { - await servers[0].videosCommand.remove({ id: videoUUID }) + await servers[0].videos.remove({ id: videoUUID }) await checkVideoFilesWereRemoved(videoUUID, servers[0]) }) diff --git a/server/tests/api/videos/video-change-ownership.ts b/server/tests/api/videos/video-change-ownership.ts index b85edd920..352eb5ea3 100644 --- a/server/tests/api/videos/video-change-ownership.ts +++ b/server/tests/api/videos/video-change-ownership.ts @@ -43,7 +43,7 @@ describe('Test video change ownership - nominal', function () { await setAccessTokensToServers(servers) await setDefaultVideoChannel(servers) - await servers[0].configCommand.updateCustomSubConfig({ + await servers[0].config.updateCustomSubConfig({ newConfig: { transcoding: { enabled: false @@ -54,16 +54,16 @@ describe('Test video change ownership - nominal', function () { } }) - firstUserToken = await servers[0].usersCommand.generateUserAndToken(firstUser) - secondUserToken = await servers[0].usersCommand.generateUserAndToken(secondUser) + firstUserToken = await servers[0].users.generateUserAndToken(firstUser) + secondUserToken = await servers[0].users.generateUserAndToken(secondUser) { - const { videoChannels } = await servers[0].usersCommand.getMyInfo({ token: firstUserToken }) + const { videoChannels } = await servers[0].users.getMyInfo({ token: firstUserToken }) firstUserChannelId = videoChannels[0].id } { - const { videoChannels } = await servers[0].usersCommand.getMyInfo({ token: secondUserToken }) + const { videoChannels } = await servers[0].users.getMyInfo({ token: secondUserToken }) secondUserChannelId = videoChannels[0].id } @@ -72,19 +72,19 @@ describe('Test video change ownership - nominal', function () { name: 'my super name', description: 'my super description' } - const { id } = await servers[0].videosCommand.upload({ token: firstUserToken, attributes }) + const { id } = await servers[0].videos.upload({ token: firstUserToken, attributes }) - servers[0].video = await servers[0].videosCommand.get({ id }) + servers[0].store.video = await servers[0].videos.get({ id }) } { const attributes = { name: 'live', channelId: firstUserChannelId, privacy: VideoPrivacy.PUBLIC } - const video = await servers[0].liveCommand.create({ token: firstUserToken, fields: attributes }) + const video = await servers[0].live.create({ token: firstUserToken, fields: attributes }) liveId = video.id } - command = servers[0].changeOwnershipCommand + command = servers[0].changeOwnership await doubleFollow(servers[0], servers[1]) }) @@ -110,7 +110,7 @@ describe('Test video change ownership - nominal', function () { it('Should send a request to change ownership of a video', async function () { this.timeout(15000) - await command.create({ token: firstUserToken, videoId: servers[0].video.id, username: secondUser }) + await command.create({ token: firstUserToken, videoId: servers[0].store.video.id, username: secondUser }) }) it('Should only return a request to change ownership for the second user', async function () { @@ -136,7 +136,7 @@ describe('Test video change ownership - nominal', function () { it('Should accept the same change ownership request without crashing', async function () { this.timeout(10000) - await command.create({ token: firstUserToken, videoId: servers[0].video.id, username: secondUser }) + await command.create({ token: firstUserToken, videoId: servers[0].store.video.id, username: secondUser }) }) it('Should not create multiple change ownership requests while one is waiting', async function () { @@ -164,7 +164,7 @@ describe('Test video change ownership - nominal', function () { it('Should send a new request to change ownership of a video', async function () { this.timeout(15000) - await command.create({ token: firstUserToken, videoId: servers[0].video.id, username: secondUser }) + await command.create({ token: firstUserToken, videoId: servers[0].store.video.id, username: secondUser }) }) it('Should return two requests to change ownership for the second user', async function () { @@ -208,7 +208,7 @@ describe('Test video change ownership - nominal', function () { it('Should have the channel of the video updated', async function () { for (const server of servers) { - const video = await server.videosCommand.get({ id: servers[0].video.uuid }) + const video = await server.videos.get({ id: servers[0].store.video.uuid }) expect(video.name).to.equal('my super name') expect(video.channel.displayName).to.equal('Main second channel') @@ -237,7 +237,7 @@ describe('Test video change ownership - nominal', function () { await waitJobs(servers) for (const server of servers) { - const video = await server.videosCommand.get({ id: servers[0].video.uuid }) + const video = await server.videos.get({ id: servers[0].store.video.uuid }) expect(video.name).to.equal('my super name') expect(video.channel.displayName).to.equal('Main second channel') @@ -266,35 +266,35 @@ describe('Test video change ownership - quota too small', function () { server = await flushAndRunServer(1) await setAccessTokensToServers([ server ]) - await server.usersCommand.create({ username: secondUser, videoQuota: 10 }) + await server.users.create({ username: secondUser, videoQuota: 10 }) - firstUserToken = await server.usersCommand.generateUserAndToken(firstUser) - secondUserToken = await server.loginCommand.getAccessToken(secondUser) + firstUserToken = await server.users.generateUserAndToken(firstUser) + secondUserToken = await server.login.getAccessToken(secondUser) // Upload some videos on the server const attributes = { name: 'my super name', description: 'my super description' } - await server.videosCommand.upload({ token: firstUserToken, attributes }) + await server.videos.upload({ token: firstUserToken, attributes }) await waitJobs(server) - const { data } = await server.videosCommand.list() + const { data } = await server.videos.list() expect(data.length).to.equal(1) - server.video = data.find(video => video.name === 'my super name') + server.store.video = data.find(video => video.name === 'my super name') }) it('Should send a request to change ownership of a video', async function () { this.timeout(15000) - await server.changeOwnershipCommand.create({ token: firstUserToken, videoId: server.video.id, username: secondUser }) + await server.changeOwnership.create({ token: firstUserToken, videoId: server.store.video.id, username: secondUser }) }) it('Should only return a request to change ownership for the second user', async function () { { - const body = await server.changeOwnershipCommand.list({ token: firstUserToken }) + const body = await server.changeOwnership.list({ token: firstUserToken }) expect(body.total).to.equal(0) expect(body.data).to.be.an('array') @@ -302,7 +302,7 @@ describe('Test video change ownership - quota too small', function () { } { - const body = await server.changeOwnershipCommand.list({ token: secondUserToken }) + const body = await server.changeOwnership.list({ token: secondUserToken }) expect(body.total).to.equal(1) expect(body.data).to.be.an('array') @@ -315,10 +315,10 @@ describe('Test video change ownership - quota too small', function () { it('Should not be possible to accept the change of ownership from second user because of exceeded quota', async function () { this.timeout(10000) - const { videoChannels } = await server.usersCommand.getMyInfo({ token: secondUserToken }) + const { videoChannels } = await server.users.getMyInfo({ token: secondUserToken }) const channelId = videoChannels[0].id - await server.changeOwnershipCommand.accept({ + await server.changeOwnership.accept({ token: secondUserToken, ownershipId: lastRequestId, channelId, diff --git a/server/tests/api/videos/video-channels.ts b/server/tests/api/videos/video-channels.ts index 170cc942e..1efef932c 100644 --- a/server/tests/api/videos/video-channels.ts +++ b/server/tests/api/videos/video-channels.ts @@ -21,7 +21,7 @@ import { User, VideoChannel } from '@shared/models' const expect = chai.expect async function findChannel (server: ServerInfo, channelId: number) { - const body = await server.channelsCommand.list({ sort: '-name' }) + const body = await server.channels.list({ sort: '-name' }) return body.data.find(c => c.id === channelId) } @@ -49,7 +49,7 @@ describe('Test video channels', function () { }) it('Should have one video channel (created with root)', async () => { - const body = await servers[0].channelsCommand.list({ start: 0, count: 2 }) + const body = await servers[0].channels.list({ start: 0, count: 2 }) expect(body.total).to.equal(1) expect(body.data).to.be.an('array') @@ -66,14 +66,14 @@ describe('Test video channels', function () { description: 'super video channel description', support: 'super video channel support text' } - const created = await servers[0].channelsCommand.create({ attributes: videoChannel }) + const created = await servers[0].channels.create({ attributes: videoChannel }) secondVideoChannelId = created.id } // The channel is 1 is propagated to servers 2 { const attributes = { name: 'my video name', channelId: secondVideoChannelId, support: 'video support field' } - const { uuid } = await servers[0].videosCommand.upload({ attributes }) + const { uuid } = await servers[0].videos.upload({ attributes }) videoUUID = uuid } @@ -81,7 +81,7 @@ describe('Test video channels', function () { }) it('Should have two video channels when getting my information', async () => { - userInfo = await servers[0].usersCommand.getMyInfo() + userInfo = await servers[0].users.getMyInfo() expect(userInfo.videoChannels).to.be.an('array') expect(userInfo.videoChannels).to.have.lengthOf(2) @@ -99,7 +99,7 @@ describe('Test video channels', function () { }) it('Should have two video channels when getting account channels on server 1', async function () { - const body = await servers[0].channelsCommand.listByAccount({ accountName }) + const body = await servers[0].channels.listByAccount({ accountName }) expect(body.total).to.equal(2) const videoChannels = body.data @@ -118,7 +118,7 @@ describe('Test video channels', function () { it('Should paginate and sort account channels', async function () { { - const body = await servers[0].channelsCommand.listByAccount({ + const body = await servers[0].channels.listByAccount({ accountName, start: 0, count: 1, @@ -133,7 +133,7 @@ describe('Test video channels', function () { } { - const body = await servers[0].channelsCommand.listByAccount({ + const body = await servers[0].channels.listByAccount({ accountName, start: 0, count: 1, @@ -146,7 +146,7 @@ describe('Test video channels', function () { } { - const body = await servers[0].channelsCommand.listByAccount({ + const body = await servers[0].channels.listByAccount({ accountName, start: 1, count: 1, @@ -160,7 +160,7 @@ describe('Test video channels', function () { }) it('Should have one video channel when getting account channels on server 2', async function () { - const body = await servers[1].channelsCommand.listByAccount({ accountName }) + const body = await servers[1].channels.listByAccount({ accountName }) expect(body.total).to.equal(1) expect(body.data).to.be.an('array') @@ -174,7 +174,7 @@ describe('Test video channels', function () { }) it('Should list video channels', async function () { - const body = await servers[0].channelsCommand.list({ start: 1, count: 1, sort: '-name' }) + const body = await servers[0].channels.list({ start: 1, count: 1, sort: '-name' }) expect(body.total).to.equal(2) expect(body.data).to.be.an('array') @@ -192,14 +192,14 @@ describe('Test video channels', function () { support: 'support updated' } - await servers[0].channelsCommand.update({ channelName: 'second_video_channel', attributes: videoChannelAttributes }) + await servers[0].channels.update({ channelName: 'second_video_channel', attributes: videoChannelAttributes }) await waitJobs(servers) }) it('Should have video channel updated', async function () { for (const server of servers) { - const body = await server.channelsCommand.list({ start: 0, count: 1, sort: '-name' }) + const body = await server.channels.list({ start: 0, count: 1, sort: '-name' }) expect(body.total).to.equal(2) expect(body.data).to.be.an('array') @@ -214,7 +214,7 @@ describe('Test video channels', function () { it('Should not have updated the video support field', async function () { for (const server of servers) { - const video = await server.videosCommand.get({ id: videoUUID }) + const video = await server.videos.get({ id: videoUUID }) expect(video.support).to.equal('video support field') } }) @@ -227,12 +227,12 @@ describe('Test video channels', function () { bulkVideosSupportUpdate: true } - await servers[0].channelsCommand.update({ channelName: 'second_video_channel', attributes: videoChannelAttributes }) + await servers[0].channels.update({ channelName: 'second_video_channel', attributes: videoChannelAttributes }) await waitJobs(servers) for (const server of servers) { - const video = await server.videosCommand.get({ id: videoUUID }) + const video = await server.videos.get({ id: videoUUID }) expect(video.support).to.equal(videoChannelAttributes.support) } }) @@ -242,7 +242,7 @@ describe('Test video channels', function () { const fixture = 'avatar.png' - await servers[0].channelsCommand.updateImage({ + await servers[0].channels.updateImage({ channelName: 'second_video_channel', fixture, type: 'avatar' @@ -257,7 +257,7 @@ describe('Test video channels', function () { await testImage(server.url, 'avatar-resized', avatarPaths[server.port], '.png') await testFileExistsOrNot(server, 'avatars', basename(avatarPaths[server.port]), true) - const row = await server.sqlCommand.getActorImage(basename(avatarPaths[server.port])) + const row = await server.sql.getActorImage(basename(avatarPaths[server.port])) expect(row.height).to.equal(ACTOR_IMAGES_SIZE.AVATARS.height) expect(row.width).to.equal(ACTOR_IMAGES_SIZE.AVATARS.width) } @@ -268,7 +268,7 @@ describe('Test video channels', function () { const fixture = 'banner.jpg' - await servers[0].channelsCommand.updateImage({ + await servers[0].channels.updateImage({ channelName: 'second_video_channel', fixture, type: 'banner' @@ -277,13 +277,13 @@ describe('Test video channels', function () { await waitJobs(servers) for (const server of servers) { - const videoChannel = await server.channelsCommand.get({ channelName: 'second_video_channel@' + servers[0].host }) + const videoChannel = await server.channels.get({ channelName: 'second_video_channel@' + servers[0].host }) bannerPaths[server.port] = videoChannel.banner.path await testImage(server.url, 'banner-resized', bannerPaths[server.port]) await testFileExistsOrNot(server, 'avatars', basename(bannerPaths[server.port]), true) - const row = await server.sqlCommand.getActorImage(basename(bannerPaths[server.port])) + const row = await server.sql.getActorImage(basename(bannerPaths[server.port])) expect(row.height).to.equal(ACTOR_IMAGES_SIZE.BANNERS.height) expect(row.width).to.equal(ACTOR_IMAGES_SIZE.BANNERS.width) } @@ -292,7 +292,7 @@ describe('Test video channels', function () { it('Should delete the video channel avatar', async function () { this.timeout(15000) - await servers[0].channelsCommand.deleteImage({ channelName: 'second_video_channel', type: 'avatar' }) + await servers[0].channels.deleteImage({ channelName: 'second_video_channel', type: 'avatar' }) await waitJobs(servers) @@ -307,7 +307,7 @@ describe('Test video channels', function () { it('Should delete the video channel banner', async function () { this.timeout(15000) - await servers[0].channelsCommand.deleteImage({ channelName: 'second_video_channel', type: 'banner' }) + await servers[0].channels.deleteImage({ channelName: 'second_video_channel', type: 'banner' }) await waitJobs(servers) @@ -324,7 +324,7 @@ describe('Test video channels', function () { for (const server of servers) { const channelURI = 'second_video_channel@localhost:' + servers[0].port - const { total, data } = await server.videosCommand.listByChannel({ videoChannelName: channelURI }) + const { total, data } = await server.videos.listByChannel({ videoChannelName: channelURI }) expect(total).to.equal(1) expect(data).to.be.an('array') @@ -336,7 +336,7 @@ describe('Test video channels', function () { it('Should change the video channel of a video', async function () { this.timeout(10000) - await servers[0].videosCommand.update({ id: videoUUID, attributes: { channelId: servers[0].videoChannel.id } }) + await servers[0].videos.update({ id: videoUUID, attributes: { channelId: servers[0].store.channel.id } }) await waitJobs(servers) }) @@ -347,13 +347,13 @@ describe('Test video channels', function () { for (const server of servers) { { const secondChannelURI = 'second_video_channel@localhost:' + servers[0].port - const { total } = await server.videosCommand.listByChannel({ videoChannelName: secondChannelURI }) + const { total } = await server.videos.listByChannel({ videoChannelName: secondChannelURI }) expect(total).to.equal(0) } { const channelURI = 'root_channel@localhost:' + servers[0].port - const { total, data } = await server.videosCommand.listByChannel({ videoChannelName: channelURI }) + const { total, data } = await server.videos.listByChannel({ videoChannelName: channelURI }) expect(total).to.equal(1) expect(data).to.be.an('array') @@ -364,11 +364,11 @@ describe('Test video channels', function () { }) it('Should delete video channel', async function () { - await servers[0].channelsCommand.delete({ channelName: 'second_video_channel' }) + await servers[0].channels.delete({ channelName: 'second_video_channel' }) }) it('Should have video channel deleted', async function () { - const body = await servers[0].channelsCommand.list({ start: 0, count: 10 }) + const body = await servers[0].channels.list({ start: 0, count: 10 }) expect(body.total).to.equal(1) expect(body.data).to.be.an('array') @@ -379,15 +379,15 @@ describe('Test video channels', function () { it('Should create the main channel with an uuid if there is a conflict', async function () { { const videoChannel = { name: 'toto_channel', displayName: 'My toto channel' } - const created = await servers[0].channelsCommand.create({ attributes: videoChannel }) + const created = await servers[0].channels.create({ attributes: videoChannel }) totoChannel = created.id } { - await servers[0].usersCommand.create({ username: 'toto', password: 'password' }) - const accessToken = await servers[0].loginCommand.getAccessToken({ username: 'toto', password: 'password' }) + await servers[0].users.create({ username: 'toto', password: 'password' }) + const accessToken = await servers[0].login.getAccessToken({ username: 'toto', password: 'password' }) - const { videoChannels } = await servers[0].usersCommand.getMyInfo({ token: accessToken }) + const { videoChannels } = await servers[0].users.getMyInfo({ token: accessToken }) const videoChannel = videoChannels[0] expect(videoChannel.name).to.match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/) } @@ -397,7 +397,7 @@ describe('Test video channels', function () { this.timeout(10000) { - const { data } = await servers[0].channelsCommand.listByAccount({ accountName, withStats: true }) + const { data } = await servers[0].channels.listByAccount({ accountName, withStats: true }) for (const channel of data) { expect(channel).to.haveOwnProperty('viewsPerDay') @@ -411,21 +411,21 @@ describe('Test video channels', function () { } { - // video has been posted on channel servers[0].videoChannel.id since last update - await servers[0].videosCommand.view({ id: videoUUID, xForwardedFor: '0.0.0.1,127.0.0.1' }) - await servers[0].videosCommand.view({ id: videoUUID, xForwardedFor: '0.0.0.2,127.0.0.1' }) + // video has been posted on channel servers[0].store.videoChannel.id since last update + await servers[0].videos.view({ id: videoUUID, xForwardedFor: '0.0.0.1,127.0.0.1' }) + await servers[0].videos.view({ id: videoUUID, xForwardedFor: '0.0.0.2,127.0.0.1' }) // Wait the repeatable job await wait(8000) - const { data } = await servers[0].channelsCommand.listByAccount({ accountName, withStats: true }) - const channelWithView = data.find(channel => channel.id === servers[0].videoChannel.id) + const { data } = await servers[0].channels.listByAccount({ accountName, withStats: true }) + const channelWithView = data.find(channel => channel.id === servers[0].store.channel.id) expect(channelWithView.viewsPerDay.slice(-1)[0].views).to.equal(2) } }) it('Should report correct videos count', async function () { - const { data } = await servers[0].channelsCommand.listByAccount({ accountName, withStats: true }) + const { data } = await servers[0].channels.listByAccount({ accountName, withStats: true }) const totoChannel = data.find(c => c.name === 'toto_channel') const rootChannel = data.find(c => c.name === 'root_channel') @@ -436,7 +436,7 @@ describe('Test video channels', function () { it('Should search among account video channels', async function () { { - const body = await servers[0].channelsCommand.listByAccount({ accountName, search: 'root' }) + const body = await servers[0].channels.listByAccount({ accountName, search: 'root' }) expect(body.total).to.equal(1) const channels = body.data @@ -444,7 +444,7 @@ describe('Test video channels', function () { } { - const body = await servers[0].channelsCommand.listByAccount({ accountName, search: 'does not exist' }) + const body = await servers[0].channels.listByAccount({ accountName, search: 'does not exist' }) expect(body.total).to.equal(0) const channels = body.data @@ -455,21 +455,21 @@ describe('Test video channels', function () { it('Should list channels by updatedAt desc if a video has been uploaded', async function () { this.timeout(30000) - await servers[0].videosCommand.upload({ attributes: { channelId: totoChannel } }) + await servers[0].videos.upload({ attributes: { channelId: totoChannel } }) await waitJobs(servers) for (const server of servers) { - const { data } = await server.channelsCommand.listByAccount({ accountName, sort: '-updatedAt' }) + const { data } = await server.channels.listByAccount({ accountName, sort: '-updatedAt' }) expect(data[0].name).to.equal('toto_channel') expect(data[1].name).to.equal('root_channel') } - await servers[0].videosCommand.upload({ attributes: { channelId: servers[0].videoChannel.id } }) + await servers[0].videos.upload({ attributes: { channelId: servers[0].store.channel.id } }) await waitJobs(servers) for (const server of servers) { - const { data } = await server.channelsCommand.listByAccount({ accountName, sort: '-updatedAt' }) + const { data } = await server.channels.listByAccount({ accountName, sort: '-updatedAt' }) expect(data[0].name).to.equal('root_channel') expect(data[1].name).to.equal('toto_channel') diff --git a/server/tests/api/videos/video-comments.ts b/server/tests/api/videos/video-comments.ts index 41be54c81..adb59bd74 100644 --- a/server/tests/api/videos/video-comments.ts +++ b/server/tests/api/videos/video-comments.ts @@ -32,15 +32,15 @@ describe('Test video comments', function () { await setAccessTokensToServers([ server ]) - const { id, uuid } = await server.videosCommand.upload() + const { id, uuid } = await server.videos.upload() videoUUID = uuid videoId = id - await server.usersCommand.updateMyAvatar({ fixture: 'avatar.png' }) + await server.users.updateMyAvatar({ fixture: 'avatar.png' }) - userAccessTokenServer1 = await server.usersCommand.generateUserAndToken('user1') + userAccessTokenServer1 = await server.users.generateUserAndToken('user1') - command = server.commentsCommand + command = server.comments }) describe('User comments', function () { diff --git a/server/tests/api/videos/video-description.ts b/server/tests/api/videos/video-description.ts index 6ac9206f5..b89247288 100644 --- a/server/tests/api/videos/video-description.ts +++ b/server/tests/api/videos/video-description.ts @@ -31,11 +31,11 @@ describe('Test video description', function () { const attributes = { description: longDescription } - await servers[0].videosCommand.upload({ attributes }) + await servers[0].videos.upload({ attributes }) await waitJobs(servers) - const { data } = await servers[0].videosCommand.list() + const { data } = await servers[0].videos.list() videoId = data[0].id videoUUID = data[0].uuid @@ -43,7 +43,7 @@ describe('Test video description', function () { it('Should have a truncated description on each server', async function () { for (const server of servers) { - const video = await server.videosCommand.get({ id: videoUUID }) + const video = await server.videos.get({ id: videoUUID }) // 30 characters * 6 -> 240 characters const truncatedDescription = 'my super description for server 1'.repeat(7) + @@ -55,9 +55,9 @@ describe('Test video description', function () { it('Should fetch long description on each server', async function () { for (const server of servers) { - const video = await server.videosCommand.get({ id: videoUUID }) + const video = await server.videos.get({ id: videoUUID }) - const { description } = await server.videosCommand.getDescription({ descriptionPath: video.descriptionPath }) + const { description } = await server.videos.getDescription({ descriptionPath: video.descriptionPath }) expect(description).to.equal(longDescription) } }) @@ -68,18 +68,18 @@ describe('Test video description', function () { const attributes = { description: 'short description' } - await servers[0].videosCommand.update({ id: videoId, attributes }) + await servers[0].videos.update({ id: videoId, attributes }) await waitJobs(servers) }) it('Should have a small description on each server', async function () { for (const server of servers) { - const video = await server.videosCommand.get({ id: videoUUID }) + const video = await server.videos.get({ id: videoUUID }) expect(video.description).to.equal('short description') - const { description } = await server.videosCommand.getDescription({ descriptionPath: video.descriptionPath }) + const { description } = await server.videos.getDescription({ descriptionPath: video.descriptionPath }) expect(description).to.equal('short description') } }) diff --git a/server/tests/api/videos/video-hls.ts b/server/tests/api/videos/video-hls.ts index d63b81694..9d79f2683 100644 --- a/server/tests/api/videos/video-hls.ts +++ b/server/tests/api/videos/video-hls.ts @@ -25,7 +25,7 @@ const expect = chai.expect async function checkHlsPlaylist (servers: ServerInfo[], videoUUID: string, hlsOnly: boolean, resolutions = [ 240, 360, 480, 720 ]) { for (const server of servers) { - const videoDetails = await server.videosCommand.get({ id: videoUUID }) + const videoDetails = await server.videos.get({ id: videoUUID }) const baseUrl = `http://${videoDetails.account.host}` expect(videoDetails.streamingPlaylists).to.have.lengthOf(1) @@ -62,7 +62,7 @@ async function checkHlsPlaylist (servers: ServerInfo[], videoUUID: string, hlsOn { await checkResolutionsInMasterPlaylist({ server, playlistUrl: hlsPlaylist.playlistUrl, resolutions }) - const masterPlaylist = await server.streamingPlaylistsCommand.get({ url: hlsPlaylist.playlistUrl }) + const masterPlaylist = await server.streamingPlaylists.get({ url: hlsPlaylist.playlistUrl }) for (const resolution of resolutions) { expect(masterPlaylist).to.contain(`${resolution}.m3u8`) @@ -72,7 +72,7 @@ async function checkHlsPlaylist (servers: ServerInfo[], videoUUID: string, hlsOn { for (const resolution of resolutions) { - const subPlaylist = await server.streamingPlaylistsCommand.get({ + const subPlaylist = await server.streamingPlaylists.get({ url: `${baseUrl}/static/streaming-playlists/hls/${videoUUID}/${resolution}.m3u8` }) @@ -107,7 +107,7 @@ describe('Test HLS videos', function () { it('Should upload a video and transcode it to HLS', async function () { this.timeout(120000) - const { uuid } = await servers[0].videosCommand.upload({ attributes: { name: 'video 1', fixture: 'video_short.webm' } }) + const { uuid } = await servers[0].videos.upload({ attributes: { name: 'video 1', fixture: 'video_short.webm' } }) videoUUID = uuid await waitJobs(servers) @@ -118,7 +118,7 @@ describe('Test HLS videos', function () { it('Should upload an audio file and transcode it to HLS', async function () { this.timeout(120000) - const { uuid } = await servers[0].videosCommand.upload({ attributes: { name: 'video audio', fixture: 'sample.ogg' } }) + const { uuid } = await servers[0].videos.upload({ attributes: { name: 'video audio', fixture: 'sample.ogg' } }) videoAudioUUID = uuid await waitJobs(servers) @@ -129,7 +129,7 @@ describe('Test HLS videos', function () { it('Should update the video', async function () { this.timeout(10000) - await servers[0].videosCommand.update({ id: videoUUID, attributes: { name: 'video 1 updated' } }) + await servers[0].videos.update({ id: videoUUID, attributes: { name: 'video 1 updated' } }) await waitJobs(servers) @@ -139,14 +139,14 @@ describe('Test HLS videos', function () { it('Should delete videos', async function () { this.timeout(10000) - await servers[0].videosCommand.remove({ id: videoUUID }) - await servers[0].videosCommand.remove({ id: videoAudioUUID }) + await servers[0].videos.remove({ id: videoUUID }) + await servers[0].videos.remove({ id: videoAudioUUID }) await waitJobs(servers) for (const server of servers) { - await server.videosCommand.get({ id: videoUUID, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) - await server.videosCommand.get({ id: videoAudioUUID, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) + await server.videos.get({ id: videoUUID, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) + await server.videos.get({ id: videoAudioUUID, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) } }) @@ -192,7 +192,7 @@ describe('Test HLS videos', function () { describe('With only HLS enabled', function () { before(async function () { - await servers[0].configCommand.updateCustomSubConfig({ + await servers[0].config.updateCustomSubConfig({ newConfig: { transcoding: { enabled: true, diff --git a/server/tests/api/videos/video-imports.ts b/server/tests/api/videos/video-imports.ts index 31fdfe12e..8b6542aa4 100644 --- a/server/tests/api/videos/video-imports.ts +++ b/server/tests/api/videos/video-imports.ts @@ -26,7 +26,7 @@ describe('Test video imports', function () { if (areHttpImportTestsDisabled()) return async function checkVideosServer1 (server: ServerInfo, idHttp: string, idMagnet: string, idTorrent: string) { - const videoHttp = await server.videosCommand.get({ id: idHttp }) + const videoHttp = await server.videos.get({ id: idHttp }) expect(videoHttp.name).to.equal('small video - youtube') // FIXME: youtube-dl seems broken @@ -43,8 +43,8 @@ describe('Test video imports', function () { expect(originallyPublishedAt.getMonth()).to.equal(0) expect(originallyPublishedAt.getFullYear()).to.equal(2019) - const videoMagnet = await server.videosCommand.get({ id: idMagnet }) - const videoTorrent = await server.videosCommand.get({ id: idTorrent }) + const videoMagnet = await server.videos.get({ id: idMagnet }) + const videoTorrent = await server.videos.get({ id: idTorrent }) for (const video of [ videoMagnet, videoTorrent ]) { expect(video.category.label).to.equal('Misc') @@ -59,12 +59,12 @@ describe('Test video imports', function () { expect(videoTorrent.name).to.contain('你好 世界 720p.mp4') expect(videoMagnet.name).to.contain('super peertube2 video') - const bodyCaptions = await server.captionsCommand.listVideoCaptions({ videoId: idHttp }) + const bodyCaptions = await server.captions.listVideoCaptions({ videoId: idHttp }) expect(bodyCaptions.total).to.equal(2) } async function checkVideoServer2 (server: ServerInfo, id: number | string) { - const video = await server.videosCommand.get({ id }) + const video = await server.videos.get({ id }) expect(video.name).to.equal('my super name') expect(video.category.label).to.equal('Entertainment') @@ -76,7 +76,7 @@ describe('Test video imports', function () { expect(video.files).to.have.lengthOf(1) - const bodyCaptions = await server.captionsCommand.listVideoCaptions({ videoId: id }) + const bodyCaptions = await server.captions.listVideoCaptions({ videoId: id }) expect(bodyCaptions.total).to.equal(2) } @@ -89,12 +89,12 @@ describe('Test video imports', function () { await setAccessTokensToServers(servers) { - const { videoChannels } = await servers[0].usersCommand.getMyInfo() + const { videoChannels } = await servers[0].users.getMyInfo() channelIdServer1 = videoChannels[0].id } { - const { videoChannels } = await servers[1].usersCommand.getMyInfo() + const { videoChannels } = await servers[1].users.getMyInfo() channelIdServer2 = videoChannels[0].id } @@ -111,7 +111,7 @@ describe('Test video imports', function () { { const attributes = { ...baseAttributes, targetUrl: ImportsCommand.getYoutubeVideoUrl() } - const { video } = await servers[0].importsCommand.importVideo({ attributes }) + const { video } = await servers[0].imports.importVideo({ attributes }) expect(video.name).to.equal('small video - youtube') expect(video.thumbnailPath).to.match(new RegExp(`^/static/thumbnails/.+.jpg$`)) @@ -120,7 +120,7 @@ describe('Test video imports', function () { await testImage(servers[0].url, 'video_import_thumbnail', video.thumbnailPath) await testImage(servers[0].url, 'video_import_preview', video.previewPath) - const bodyCaptions = await servers[0].captionsCommand.listVideoCaptions({ videoId: video.id }) + const bodyCaptions = await servers[0].captions.listVideoCaptions({ videoId: video.id }) const videoCaptions = bodyCaptions.data expect(videoCaptions).to.have.lengthOf(2) @@ -166,7 +166,7 @@ Ajouter un sous-titre est vraiment facile`) description: 'this is a super torrent description', tags: [ 'tag_torrent1', 'tag_torrent2' ] } - const { video } = await servers[0].importsCommand.importVideo({ attributes }) + const { video } = await servers[0].imports.importVideo({ attributes }) expect(video.name).to.equal('super peertube2 video') } @@ -177,13 +177,13 @@ Ajouter un sous-titre est vraiment facile`) description: 'this is a super torrent description', tags: [ 'tag_torrent1', 'tag_torrent2' ] } - const { video } = await servers[0].importsCommand.importVideo({ attributes }) + const { video } = await servers[0].imports.importVideo({ attributes }) expect(video.name).to.equal('你好 世界 720p.mp4') } }) it('Should list the videos to import in my videos on server 1', async function () { - const { total, data } = await servers[0].videosCommand.listMyVideos({ sort: 'createdAt' }) + const { total, data } = await servers[0].videos.listMyVideos({ sort: 'createdAt' }) expect(total).to.equal(3) @@ -194,7 +194,7 @@ Ajouter un sous-titre est vraiment facile`) }) it('Should list the videos to import in my imports on server 1', async function () { - const { total, data: videoImports } = await servers[0].importsCommand.getMyVideoImports({ sort: '-createdAt' }) + const { total, data: videoImports } = await servers[0].imports.getMyVideoImports({ sort: '-createdAt' }) expect(total).to.equal(3) expect(videoImports).to.have.lengthOf(3) @@ -221,7 +221,7 @@ Ajouter un sous-titre est vraiment facile`) await waitJobs(servers) for (const server of servers) { - const { total, data } = await server.videosCommand.list() + const { total, data } = await server.videos.list() expect(total).to.equal(3) expect(data).to.have.lengthOf(3) @@ -244,7 +244,7 @@ Ajouter un sous-titre est vraiment facile`) description: 'my super description', tags: [ 'supertag1', 'supertag2' ] } - const { video } = await servers[1].importsCommand.importVideo({ attributes }) + const { video } = await servers[1].imports.importVideo({ attributes }) expect(video.name).to.equal('my super name') }) @@ -254,7 +254,7 @@ Ajouter un sous-titre est vraiment facile`) await waitJobs(servers) for (const server of servers) { - const { total, data } = await server.videosCommand.list() + const { total, data } = await server.videos.list() expect(total).to.equal(4) expect(data).to.have.lengthOf(4) @@ -274,13 +274,13 @@ Ajouter un sous-titre est vraiment facile`) channelId: channelIdServer2, privacy: VideoPrivacy.PUBLIC } - const { video } = await servers[1].importsCommand.importVideo({ attributes }) + const { video } = await servers[1].imports.importVideo({ attributes }) const videoUUID = video.uuid await waitJobs(servers) for (const server of servers) { - const video = await server.videosCommand.get({ id: videoUUID }) + const video = await server.videos.get({ id: videoUUID }) expect(video.name).to.equal('transcoded video') expect(video.files).to.have.lengthOf(4) @@ -316,7 +316,7 @@ Ajouter un sous-titre est vraiment facile`) } } } - await servers[0].configCommand.updateCustomSubConfig({ newConfig: config }) + await servers[0].config.updateCustomSubConfig({ newConfig: config }) const attributes = { name: 'hdr video', @@ -324,13 +324,13 @@ Ajouter un sous-titre est vraiment facile`) channelId: channelIdServer1, privacy: VideoPrivacy.PUBLIC } - const { video: videoImported } = await servers[0].importsCommand.importVideo({ attributes }) + const { video: videoImported } = await servers[0].imports.importVideo({ attributes }) const videoUUID = videoImported.uuid await waitJobs(servers) // test resolution - const video = await servers[0].videosCommand.get({ id: videoUUID }) + const video = await servers[0].videos.get({ id: videoUUID }) expect(video.name).to.equal('hdr video') const maxResolution = Math.max.apply(Math, video.files.map(function (o) { return o.resolution.id })) expect(maxResolution, 'expected max resolution not met').to.equals(VideoResolution.H_1080P) diff --git a/server/tests/api/videos/video-nsfw.ts b/server/tests/api/videos/video-nsfw.ts index b8fff096d..95395a582 100644 --- a/server/tests/api/videos/video-nsfw.ts +++ b/server/tests/api/videos/video-nsfw.ts @@ -18,7 +18,7 @@ describe('Test video NSFW policy', function () { let customConfig: CustomConfig async function getVideosFunctions (token?: string, query: { nsfw?: BooleanBothQuery } = {}) { - const user = await server.usersCommand.getMyInfo() + const user = await server.users.getMyInfo() const videoChannelName = user.videoChannels[0].name const accountName = user.account.name + '@' + user.account.host const hasQuery = Object.keys(query).length !== 0 @@ -26,15 +26,15 @@ describe('Test video NSFW policy', function () { if (token) { promises = [ - server.searchCommand.advancedVideoSearch({ token, search: { search: 'n', sort: '-publishedAt', ...query } }), - server.videosCommand.listWithToken({ token, ...query }), - server.videosCommand.listByAccount({ token, accountName, ...query }), - server.videosCommand.listByChannel({ token, videoChannelName, ...query }) + server.search.advancedVideoSearch({ token, search: { search: 'n', sort: '-publishedAt', ...query } }), + server.videos.listWithToken({ token, ...query }), + server.videos.listByAccount({ token, accountName, ...query }), + server.videos.listByChannel({ token, videoChannelName, ...query }) ] // Overviews do not support video filters if (!hasQuery) { - const p = server.overviewsCommand.getVideos({ page: 1, token }) + const p = server.overviews.getVideos({ page: 1, token }) .then(res => createOverviewRes(res)) promises.push(p) } @@ -43,15 +43,15 @@ describe('Test video NSFW policy', function () { } promises = [ - server.searchCommand.searchVideos({ search: 'n', sort: '-publishedAt' }), - server.videosCommand.list(), - server.videosCommand.listByAccount({ accountName }), - server.videosCommand.listByChannel({ videoChannelName }) + server.search.searchVideos({ search: 'n', sort: '-publishedAt' }), + server.videos.list(), + server.videos.listByAccount({ accountName }), + server.videos.listByChannel({ videoChannelName }) ] // Overviews do not support video filters if (!hasQuery) { - const p = server.overviewsCommand.getVideos({ page: 1 }) + const p = server.overviews.getVideos({ page: 1 }) .then(res => createOverviewRes(res)) promises.push(p) } @@ -68,20 +68,20 @@ describe('Test video NSFW policy', function () { { const attributes = { name: 'nsfw', nsfw: true, category: 1 } - await server.videosCommand.upload({ attributes }) + await server.videos.upload({ attributes }) } { const attributes = { name: 'normal', nsfw: false, category: 1 } - await server.videosCommand.upload({ attributes }) + await server.videos.upload({ attributes }) } - customConfig = await server.configCommand.getCustomConfig() + customConfig = await server.config.getCustomConfig() }) describe('Instance default NSFW policy', function () { it('Should display NSFW videos with display default NSFW policy', async function () { - const serverConfig = await server.configCommand.getConfig() + const serverConfig = await server.config.getConfig() expect(serverConfig.instance.defaultNSFWPolicy).to.equal('display') for (const body of await getVideosFunctions()) { @@ -96,9 +96,9 @@ describe('Test video NSFW policy', function () { it('Should not display NSFW videos with do_not_list default NSFW policy', async function () { customConfig.instance.defaultNSFWPolicy = 'do_not_list' - await server.configCommand.updateCustomConfig({ newCustomConfig: customConfig }) + await server.config.updateCustomConfig({ newCustomConfig: customConfig }) - const serverConfig = await server.configCommand.getConfig() + const serverConfig = await server.config.getConfig() expect(serverConfig.instance.defaultNSFWPolicy).to.equal('do_not_list') for (const body of await getVideosFunctions()) { @@ -112,9 +112,9 @@ describe('Test video NSFW policy', function () { it('Should display NSFW videos with blur default NSFW policy', async function () { customConfig.instance.defaultNSFWPolicy = 'blur' - await server.configCommand.updateCustomConfig({ newCustomConfig: customConfig }) + await server.config.updateCustomConfig({ newCustomConfig: customConfig }) - const serverConfig = await server.configCommand.getConfig() + const serverConfig = await server.config.getConfig() expect(serverConfig.instance.defaultNSFWPolicy).to.equal('blur') for (const body of await getVideosFunctions()) { @@ -133,17 +133,17 @@ describe('Test video NSFW policy', function () { it('Should create a user having the default nsfw policy', async function () { const username = 'user1' const password = 'my super password' - await server.usersCommand.create({ username: username, password: password }) + await server.users.create({ username: username, password: password }) - userAccessToken = await server.loginCommand.getAccessToken({ username, password }) + userAccessToken = await server.login.getAccessToken({ username, password }) - const user = await server.usersCommand.getMyInfo({ token: userAccessToken }) + const user = await server.users.getMyInfo({ token: userAccessToken }) expect(user.nsfwPolicy).to.equal('blur') }) it('Should display NSFW videos with blur user NSFW policy', async function () { customConfig.instance.defaultNSFWPolicy = 'do_not_list' - await server.configCommand.updateCustomConfig({ newCustomConfig: customConfig }) + await server.config.updateCustomConfig({ newCustomConfig: customConfig }) for (const body of await getVideosFunctions(userAccessToken)) { expect(body.total).to.equal(2) @@ -156,7 +156,7 @@ describe('Test video NSFW policy', function () { }) it('Should display NSFW videos with display user NSFW policy', async function () { - await server.usersCommand.updateMe({ nsfwPolicy: 'display' }) + await server.users.updateMe({ nsfwPolicy: 'display' }) for (const body of await getVideosFunctions(server.accessToken)) { expect(body.total).to.equal(2) @@ -169,7 +169,7 @@ describe('Test video NSFW policy', function () { }) it('Should not display NSFW videos with do_not_list user NSFW policy', async function () { - await server.usersCommand.updateMe({ nsfwPolicy: 'do_not_list' }) + await server.users.updateMe({ nsfwPolicy: 'do_not_list' }) for (const body of await getVideosFunctions(server.accessToken)) { expect(body.total).to.equal(1) @@ -181,7 +181,7 @@ describe('Test video NSFW policy', function () { }) it('Should be able to see my NSFW videos even with do_not_list user NSFW policy', async function () { - const { total, data } = await server.videosCommand.listMyVideos() + const { total, data } = await server.videos.listMyVideos() expect(total).to.equal(2) expect(data).to.have.lengthOf(2) diff --git a/server/tests/api/videos/video-playlist-thumbnails.ts b/server/tests/api/videos/video-playlist-thumbnails.ts index 14739af20..709f64c4d 100644 --- a/server/tests/api/videos/video-playlist-thumbnails.ts +++ b/server/tests/api/videos/video-playlist-thumbnails.ts @@ -31,13 +31,13 @@ describe('Playlist thumbnail', function () { let video2: number async function getPlaylistWithoutThumbnail (server: ServerInfo) { - const body = await server.playlistsCommand.list({ start: 0, count: 10 }) + const body = await server.playlists.list({ start: 0, count: 10 }) return body.data.find(p => p.displayName === 'playlist without thumbnail') } async function getPlaylistWithThumbnail (server: ServerInfo) { - const body = await server.playlistsCommand.list({ start: 0, count: 10 }) + const body = await server.playlists.list({ start: 0, count: 10 }) return body.data.find(p => p.displayName === 'playlist with thumbnail') } @@ -54,8 +54,8 @@ describe('Playlist thumbnail', function () { // Server 1 and server 2 follow each other await doubleFollow(servers[0], servers[1]) - video1 = (await servers[0].videosCommand.quickUpload({ name: 'video 1' })).id - video2 = (await servers[0].videosCommand.quickUpload({ name: 'video 2' })).id + video1 = (await servers[0].videos.quickUpload({ name: 'video 1' })).id + video2 = (await servers[0].videos.quickUpload({ name: 'video 2' })).id await waitJobs(servers) }) @@ -63,16 +63,16 @@ describe('Playlist thumbnail', function () { it('Should automatically update the thumbnail when adding an element', async function () { this.timeout(30000) - const created = await servers[1].playlistsCommand.create({ + const created = await servers[1].playlists.create({ attributes: { displayName: 'playlist without thumbnail', privacy: VideoPlaylistPrivacy.PUBLIC, - videoChannelId: servers[1].videoChannel.id + videoChannelId: servers[1].store.channel.id } }) playlistWithoutThumbnailId = created.id - const added = await servers[1].playlistsCommand.addElement({ + const added = await servers[1].playlists.addElement({ playlistId: playlistWithoutThumbnailId, attributes: { videoId: video1 } }) @@ -89,17 +89,17 @@ describe('Playlist thumbnail', function () { it('Should not update the thumbnail if we explicitly uploaded a thumbnail', async function () { this.timeout(30000) - const created = await servers[1].playlistsCommand.create({ + const created = await servers[1].playlists.create({ attributes: { displayName: 'playlist with thumbnail', privacy: VideoPlaylistPrivacy.PUBLIC, - videoChannelId: servers[1].videoChannel.id, + videoChannelId: servers[1].store.channel.id, thumbnailfile: 'thumbnail.jpg' } }) playlistWithThumbnailId = created.id - const added = await servers[1].playlistsCommand.addElement({ + const added = await servers[1].playlists.addElement({ playlistId: playlistWithThumbnailId, attributes: { videoId: video1 } }) @@ -116,13 +116,13 @@ describe('Playlist thumbnail', function () { it('Should automatically update the thumbnail when moving the first element', async function () { this.timeout(30000) - const added = await servers[1].playlistsCommand.addElement({ + const added = await servers[1].playlists.addElement({ playlistId: playlistWithoutThumbnailId, attributes: { videoId: video2 } }) withoutThumbnailE2 = added.id - await servers[1].playlistsCommand.reorderElements({ + await servers[1].playlists.reorderElements({ playlistId: playlistWithoutThumbnailId, attributes: { startPosition: 1, @@ -141,13 +141,13 @@ describe('Playlist thumbnail', function () { it('Should not update the thumbnail when moving the first element if we explicitly uploaded a thumbnail', async function () { this.timeout(30000) - const added = await servers[1].playlistsCommand.addElement({ + const added = await servers[1].playlists.addElement({ playlistId: playlistWithThumbnailId, attributes: { videoId: video2 } }) withThumbnailE2 = added.id - await servers[1].playlistsCommand.reorderElements({ + await servers[1].playlists.reorderElements({ playlistId: playlistWithThumbnailId, attributes: { startPosition: 1, @@ -166,7 +166,7 @@ describe('Playlist thumbnail', function () { it('Should automatically update the thumbnail when deleting the first element', async function () { this.timeout(30000) - await servers[1].playlistsCommand.removeElement({ + await servers[1].playlists.removeElement({ playlistId: playlistWithoutThumbnailId, elementId: withoutThumbnailE1 }) @@ -182,7 +182,7 @@ describe('Playlist thumbnail', function () { it('Should not update the thumbnail when deleting the first element if we explicitly uploaded a thumbnail', async function () { this.timeout(30000) - await servers[1].playlistsCommand.removeElement({ + await servers[1].playlists.removeElement({ playlistId: playlistWithThumbnailId, elementId: withThumbnailE1 }) @@ -198,7 +198,7 @@ describe('Playlist thumbnail', function () { it('Should the thumbnail when we delete the last element', async function () { this.timeout(30000) - await servers[1].playlistsCommand.removeElement({ + await servers[1].playlists.removeElement({ playlistId: playlistWithoutThumbnailId, elementId: withoutThumbnailE2 }) @@ -214,7 +214,7 @@ describe('Playlist thumbnail', function () { it('Should not update the thumbnail when we delete the last element if we explicitly uploaded a thumbnail', async function () { this.timeout(30000) - await servers[1].playlistsCommand.removeElement({ + await servers[1].playlists.removeElement({ playlistId: playlistWithThumbnailId, elementId: withThumbnailE2 }) diff --git a/server/tests/api/videos/video-playlists.ts b/server/tests/api/videos/video-playlists.ts index 40f61ca19..0dc53d4c0 100644 --- a/server/tests/api/videos/video-playlists.ts +++ b/server/tests/api/videos/video-playlists.ts @@ -36,7 +36,7 @@ async function checkPlaylistElementType ( total: number ) { for (const server of servers) { - const body = await server.playlistsCommand.listVideos({ token: server.accessToken, playlistId, start: 0, count: 10 }) + const body = await server.playlists.listVideos({ token: server.accessToken, playlistId, start: 0, count: 10 }) expect(body.total).to.equal(total) const videoElement = body.data.find(e => e.position === position) @@ -86,26 +86,26 @@ describe('Test video playlists', function () { // Server 1 and server 3 follow each other await doubleFollow(servers[0], servers[2]) - commands = servers.map(s => s.playlistsCommand) + commands = servers.map(s => s.playlists) { - servers[0].videos = [] - servers[1].videos = [] - servers[2].videos = [] + servers[0].store.videos = [] + servers[1].store.videos = [] + servers[2].store.videos = [] for (const server of servers) { for (let i = 0; i < 7; i++) { const name = `video ${i} server ${server.serverNumber}` - const video = await server.videosCommand.upload({ attributes: { name, nsfw: false } }) + const video = await server.videos.upload({ attributes: { name, nsfw: false } }) - server.videos.push(video) + server.store.videos.push(video) } } } - nsfwVideoServer1 = (await servers[0].videosCommand.quickUpload({ name: 'NSFW video', nsfw: true })).id + nsfwVideoServer1 = (await servers[0].videos.quickUpload({ name: 'NSFW video', nsfw: true })).id - userTokenServer1 = await servers[0].usersCommand.generateUserAndToken('user1') + userTokenServer1 = await servers[0].users.generateUserAndToken('user1') await waitJobs(servers) }) @@ -149,7 +149,7 @@ describe('Test video playlists', function () { }) it('Should get private playlist for a classic user', async function () { - const token = await servers[0].usersCommand.generateUserAndToken('toto') + const token = await servers[0].users.generateUserAndToken('toto') const body = await commands[0].listByAccount({ token, handle: 'toto' }) @@ -172,7 +172,7 @@ describe('Test video playlists', function () { privacy: VideoPlaylistPrivacy.PUBLIC, description: 'my super description', thumbnailfile: 'thumbnail.jpg', - videoChannelId: servers[0].videoChannel.id + videoChannelId: servers[0].store.channel.id } }) @@ -181,13 +181,13 @@ describe('Test video playlists', function () { await wait(3000) for (const server of servers) { - const body = await server.playlistsCommand.list({ start: 0, count: 5 }) + const body = await server.playlists.list({ start: 0, count: 5 }) expect(body.total).to.equal(1) expect(body.data).to.have.lengthOf(1) const playlistFromList = body.data[0] - const playlistFromGet = await server.playlistsCommand.get({ playlistId: playlistFromList.uuid }) + const playlistFromGet = await server.playlists.get({ playlistId: playlistFromList.uuid }) for (const playlist of [ playlistFromGet, playlistFromList ]) { expect(playlist.id).to.be.a('number') @@ -217,23 +217,23 @@ describe('Test video playlists', function () { this.timeout(30000) { - const playlist = await servers[1].playlistsCommand.create({ + const playlist = await servers[1].playlists.create({ attributes: { displayName: 'playlist 2', privacy: VideoPlaylistPrivacy.PUBLIC, - videoChannelId: servers[1].videoChannel.id + videoChannelId: servers[1].store.channel.id } }) playlistServer2Id1 = playlist.id } { - const playlist = await servers[1].playlistsCommand.create({ + const playlist = await servers[1].playlists.create({ attributes: { displayName: 'playlist 3', privacy: VideoPlaylistPrivacy.PUBLIC, thumbnailfile: 'thumbnail.jpg', - videoChannelId: servers[1].videoChannel.id + videoChannelId: servers[1].store.channel.id } }) @@ -242,13 +242,13 @@ describe('Test video playlists', function () { } for (const id of [ playlistServer2Id1, playlistServer2Id2 ]) { - await servers[1].playlistsCommand.addElement({ + await servers[1].playlists.addElement({ playlistId: id, - attributes: { videoId: servers[1].videos[0].id, startTimestamp: 1, stopTimestamp: 2 } + attributes: { videoId: servers[1].store.videos[0].id, startTimestamp: 1, stopTimestamp: 2 } }) - await servers[1].playlistsCommand.addElement({ + await servers[1].playlists.addElement({ playlistId: id, - attributes: { videoId: servers[1].videos[1].id } + attributes: { videoId: servers[1].store.videos[1].id } }) } @@ -256,7 +256,7 @@ describe('Test video playlists', function () { await wait(3000) for (const server of [ servers[0], servers[1] ]) { - const body = await server.playlistsCommand.list({ start: 0, count: 5 }) + const body = await server.playlists.list({ start: 0, count: 5 }) const playlist2 = body.data.find(p => p.displayName === 'playlist 2') expect(playlist2).to.not.be.undefined @@ -267,7 +267,7 @@ describe('Test video playlists', function () { await testImage(server.url, 'thumbnail', playlist3.thumbnailPath) } - const body = await servers[2].playlistsCommand.list({ start: 0, count: 5 }) + const body = await servers[2].playlists.list({ start: 0, count: 5 }) expect(body.data.find(p => p.displayName === 'playlist 2')).to.be.undefined expect(body.data.find(p => p.displayName === 'playlist 3')).to.be.undefined }) @@ -278,7 +278,7 @@ describe('Test video playlists', function () { // Server 2 and server 3 follow each other await doubleFollow(servers[1], servers[2]) - const body = await servers[2].playlistsCommand.list({ start: 0, count: 5 }) + const body = await servers[2].playlists.list({ start: 0, count: 5 }) const playlist2 = body.data.find(p => p.displayName === 'playlist 2') expect(playlist2).to.not.be.undefined @@ -294,7 +294,7 @@ describe('Test video playlists', function () { this.timeout(30000) { - const body = await servers[2].playlistsCommand.list({ start: 1, count: 2, sort: 'createdAt' }) + const body = await servers[2].playlists.list({ start: 1, count: 2, sort: 'createdAt' }) expect(body.total).to.equal(3) const data = body.data @@ -304,7 +304,7 @@ describe('Test video playlists', function () { } { - const body = await servers[2].playlistsCommand.list({ start: 1, count: 2, sort: '-createdAt' }) + const body = await servers[2].playlists.list({ start: 1, count: 2, sort: '-createdAt' }) expect(body.total).to.equal(3) const data = body.data @@ -331,7 +331,7 @@ describe('Test video playlists', function () { this.timeout(30000) { - const body = await servers[1].playlistsCommand.listByAccount({ handle: 'root', start: 1, count: 2, sort: '-createdAt' }) + const body = await servers[1].playlists.listByAccount({ handle: 'root', start: 1, count: 2, sort: '-createdAt' }) expect(body.total).to.equal(2) const data = body.data @@ -340,7 +340,7 @@ describe('Test video playlists', function () { } { - const body = await servers[1].playlistsCommand.listByAccount({ handle: 'root', start: 1, count: 2, sort: 'createdAt' }) + const body = await servers[1].playlists.listByAccount({ handle: 'root', start: 1, count: 2, sort: 'createdAt' }) expect(body.total).to.equal(2) const data = body.data @@ -349,7 +349,7 @@ describe('Test video playlists', function () { } { - const body = await servers[1].playlistsCommand.listByAccount({ handle: 'root', sort: 'createdAt', search: '3' }) + const body = await servers[1].playlists.listByAccount({ handle: 'root', sort: 'createdAt', search: '3' }) expect(body.total).to.equal(1) const data = body.data @@ -358,7 +358,7 @@ describe('Test video playlists', function () { } { - const body = await servers[1].playlistsCommand.listByAccount({ handle: 'root', sort: 'createdAt', search: '4' }) + const body = await servers[1].playlists.listByAccount({ handle: 'root', sort: 'createdAt', search: '4' }) expect(body.total).to.equal(0) const data = body.data @@ -375,17 +375,17 @@ describe('Test video playlists', function () { this.timeout(30000) { - unlistedPlaylist = await servers[1].playlistsCommand.create({ + unlistedPlaylist = await servers[1].playlists.create({ attributes: { displayName: 'playlist unlisted', privacy: VideoPlaylistPrivacy.UNLISTED, - videoChannelId: servers[1].videoChannel.id + videoChannelId: servers[1].store.channel.id } }) } { - privatePlaylist = await servers[1].playlistsCommand.create({ + privatePlaylist = await servers[1].playlists.create({ attributes: { displayName: 'playlist private', privacy: VideoPlaylistPrivacy.PRIVATE @@ -400,8 +400,8 @@ describe('Test video playlists', function () { it('Should not list unlisted or private playlists', async function () { for (const server of servers) { const results = [ - await server.playlistsCommand.listByAccount({ handle: 'root@localhost:' + servers[1].port, sort: '-createdAt' }), - await server.playlistsCommand.list({ start: 0, count: 2, sort: '-createdAt' }) + await server.playlists.listByAccount({ handle: 'root@localhost:' + servers[1].port, sort: '-createdAt' }), + await server.playlists.list({ start: 0, count: 2, sort: '-createdAt' }) ] expect(results[0].total).to.equal(2) @@ -417,23 +417,23 @@ describe('Test video playlists', function () { }) it('Should not get unlisted playlist using only the id', async function () { - await servers[1].playlistsCommand.get({ playlistId: unlistedPlaylist.id, expectedStatus: 404 }) + await servers[1].playlists.get({ playlistId: unlistedPlaylist.id, expectedStatus: 404 }) }) it('Should get unlisted plyaylist using uuid or shortUUID', async function () { - await servers[1].playlistsCommand.get({ playlistId: unlistedPlaylist.uuid }) - await servers[1].playlistsCommand.get({ playlistId: unlistedPlaylist.shortUUID }) + await servers[1].playlists.get({ playlistId: unlistedPlaylist.uuid }) + await servers[1].playlists.get({ playlistId: unlistedPlaylist.shortUUID }) }) it('Should not get private playlist without token', async function () { for (const id of [ privatePlaylist.id, privatePlaylist.uuid, privatePlaylist.shortUUID ]) { - await servers[1].playlistsCommand.get({ playlistId: id, expectedStatus: 401 }) + await servers[1].playlists.get({ playlistId: id, expectedStatus: 401 }) } }) it('Should get private playlist with a token', async function () { for (const id of [ privatePlaylist.id, privatePlaylist.uuid, privatePlaylist.shortUUID ]) { - await servers[1].playlistsCommand.get({ token: servers[1].accessToken, playlistId: id }) + await servers[1].playlists.get({ token: servers[1].accessToken, playlistId: id }) } }) }) @@ -443,13 +443,13 @@ describe('Test video playlists', function () { it('Should update a playlist', async function () { this.timeout(30000) - await servers[1].playlistsCommand.update({ + await servers[1].playlists.update({ attributes: { displayName: 'playlist 3 updated', description: 'description updated', privacy: VideoPlaylistPrivacy.UNLISTED, thumbnailfile: 'thumbnail.jpg', - videoChannelId: servers[1].videoChannel.id + videoChannelId: servers[1].store.channel.id }, playlistId: playlistServer2Id2 }) @@ -457,7 +457,7 @@ describe('Test video playlists', function () { await waitJobs(servers) for (const server of servers) { - const playlist = await server.playlistsCommand.get({ playlistId: playlistServer2UUID2 }) + const playlist = await server.playlists.get({ playlistId: playlistServer2UUID2 }) expect(playlist.displayName).to.equal('playlist 3 updated') expect(playlist.description).to.equal('description updated') @@ -491,23 +491,23 @@ describe('Test video playlists', function () { attributes: { displayName: 'playlist 4', privacy: VideoPlaylistPrivacy.PUBLIC, - videoChannelId: servers[0].videoChannel.id + videoChannelId: servers[0].store.channel.id } }) playlistServer1Id = playlist.id playlistServer1UUID = playlist.uuid - await addVideo({ videoId: servers[0].videos[0].uuid, startTimestamp: 15, stopTimestamp: 28 }) - await addVideo({ videoId: servers[2].videos[1].uuid, startTimestamp: 35 }) - await addVideo({ videoId: servers[2].videos[2].uuid }) + await addVideo({ videoId: servers[0].store.videos[0].uuid, startTimestamp: 15, stopTimestamp: 28 }) + await addVideo({ videoId: servers[2].store.videos[1].uuid, startTimestamp: 35 }) + await addVideo({ videoId: servers[2].store.videos[2].uuid }) { - const element = await addVideo({ videoId: servers[0].videos[3].uuid, stopTimestamp: 35 }) + const element = await addVideo({ videoId: servers[0].store.videos[3].uuid, stopTimestamp: 35 }) playlistElementServer1Video4 = element.id } { - const element = await addVideo({ videoId: servers[0].videos[4].uuid, startTimestamp: 45, stopTimestamp: 60 }) + const element = await addVideo({ videoId: servers[0].store.videos[4].uuid, startTimestamp: 45, stopTimestamp: 60 }) playlistElementServer1Video5 = element.id } @@ -527,7 +527,7 @@ describe('Test video playlists', function () { for (const server of servers) { { - const body = await server.playlistsCommand.listVideos({ playlistId: playlistServer1UUID, start: 0, count: 10 }) + const body = await server.playlists.listVideos({ playlistId: playlistServer1UUID, start: 0, count: 10 }) expect(body.total).to.equal(8) @@ -576,7 +576,7 @@ describe('Test video playlists', function () { } { - const body = await server.playlistsCommand.listVideos({ playlistId: playlistServer1UUID, start: 0, count: 2 }) + const body = await server.playlists.listVideos({ playlistId: playlistServer1UUID, start: 0, count: 2 }) expect(body.data).to.have.lengthOf(2) } } @@ -606,7 +606,7 @@ describe('Test video playlists', function () { attributes: { displayName: 'playlist 56', privacy: VideoPlaylistPrivacy.PUBLIC, - videoChannelId: servers[0].videoChannel.id + videoChannelId: servers[0].store.channel.id } }) @@ -617,9 +617,9 @@ describe('Test video playlists', function () { return commands[0].addElement({ token: userTokenServer1, playlistId: playlistServer1Id2, attributes }) } - video1 = (await servers[0].videosCommand.quickUpload({ name: 'video 89', token: userTokenServer1 })).uuid - video2 = (await servers[1].videosCommand.quickUpload({ name: 'video 90' })).uuid - video3 = (await servers[0].videosCommand.quickUpload({ name: 'video 91', nsfw: true })).uuid + video1 = (await servers[0].videos.quickUpload({ name: 'video 89', token: userTokenServer1 })).uuid + video2 = (await servers[1].videos.quickUpload({ name: 'video 90' })).uuid + video3 = (await servers[0].videos.quickUpload({ name: 'video 91', nsfw: true })).uuid await waitJobs(servers) @@ -637,7 +637,7 @@ describe('Test video playlists', function () { const position = 1 { - await servers[0].videosCommand.update({ id: video1, attributes: { privacy: VideoPrivacy.PRIVATE } }) + await servers[0].videos.update({ id: video1, attributes: { privacy: VideoPrivacy.PRIVATE } }) await waitJobs(servers) await checkPlaylistElementType(groupUser1, playlistServer1UUID2, VideoPlaylistElementType.REGULAR, position, name, 3) @@ -647,7 +647,7 @@ describe('Test video playlists', function () { } { - await servers[0].videosCommand.update({ id: video1, attributes: { privacy: VideoPrivacy.PUBLIC } }) + await servers[0].videos.update({ id: video1, attributes: { privacy: VideoPrivacy.PUBLIC } }) await waitJobs(servers) await checkPlaylistElementType(groupUser1, playlistServer1UUID2, VideoPlaylistElementType.REGULAR, position, name, 3) @@ -665,7 +665,7 @@ describe('Test video playlists', function () { const position = 1 { - await servers[0].blacklistCommand.add({ videoId: video1, reason: 'reason', unfederate: true }) + await servers[0].blacklist.add({ videoId: video1, reason: 'reason', unfederate: true }) await waitJobs(servers) await checkPlaylistElementType(groupUser1, playlistServer1UUID2, VideoPlaylistElementType.REGULAR, position, name, 3) @@ -675,7 +675,7 @@ describe('Test video playlists', function () { } { - await servers[0].blacklistCommand.remove({ videoId: video1 }) + await servers[0].blacklist.remove({ videoId: video1 }) await waitJobs(servers) await checkPlaylistElementType(groupUser1, playlistServer1UUID2, VideoPlaylistElementType.REGULAR, position, name, 3) @@ -689,7 +689,7 @@ describe('Test video playlists', function () { it('Should update the element type if the account or server of the video is blocked', async function () { this.timeout(90000) - const command = servers[0].blocklistCommand + const command = servers[0].blocklist const name = 'video 90' const position = 2 @@ -778,7 +778,7 @@ describe('Test video playlists', function () { await waitJobs(servers) for (const server of servers) { - const body = await server.playlistsCommand.listVideos({ playlistId: playlistServer1UUID, start: 0, count: 10 }) + const body = await server.playlists.listVideos({ playlistId: playlistServer1UUID, start: 0, count: 10 }) const names = body.data.map(v => v.video.name) expect(names).to.deep.equal([ @@ -807,7 +807,7 @@ describe('Test video playlists', function () { await waitJobs(servers) for (const server of servers) { - const body = await server.playlistsCommand.listVideos({ playlistId: playlistServer1UUID, start: 0, count: 10 }) + const body = await server.playlists.listVideos({ playlistId: playlistServer1UUID, start: 0, count: 10 }) const names = body.data.map(v => v.video.name) expect(names).to.deep.equal([ @@ -835,7 +835,7 @@ describe('Test video playlists', function () { await waitJobs(servers) for (const server of servers) { - const { data: elements } = await server.playlistsCommand.listVideos({ playlistId: playlistServer1UUID, start: 0, count: 10 }) + const { data: elements } = await server.playlists.listVideos({ playlistId: playlistServer1UUID, start: 0, count: 10 }) const names = elements.map(v => v.video.name) expect(names).to.deep.equal([ @@ -878,7 +878,7 @@ describe('Test video playlists', function () { await waitJobs(servers) for (const server of servers) { - const { data: elements } = await server.playlistsCommand.listVideos({ playlistId: playlistServer1UUID, start: 0, count: 10 }) + const { data: elements } = await server.playlists.listVideos({ playlistId: playlistServer1UUID, start: 0, count: 10 }) expect(elements[0].video.name).to.equal('video 3 server 1') expect(elements[0].position).to.equal(1) @@ -894,16 +894,16 @@ describe('Test video playlists', function () { it('Should check videos existence in my playlist', async function () { const videoIds = [ - servers[0].videos[0].id, + servers[0].store.videos[0].id, 42000, - servers[0].videos[3].id, + servers[0].store.videos[3].id, 43000, - servers[0].videos[4].id + servers[0].store.videos[4].id ] const obj = await commands[0].videosExist({ videoIds }) { - const elem = obj[servers[0].videos[0].id] + const elem = obj[servers[0].store.videos[0].id] expect(elem).to.have.lengthOf(1) expect(elem[0].playlistElementId).to.exist expect(elem[0].playlistId).to.equal(playlistServer1Id) @@ -912,7 +912,7 @@ describe('Test video playlists', function () { } { - const elem = obj[servers[0].videos[3].id] + const elem = obj[servers[0].store.videos[3].id] expect(elem).to.have.lengthOf(1) expect(elem[0].playlistElementId).to.equal(playlistElementServer1Video4) expect(elem[0].playlistId).to.equal(playlistServer1Id) @@ -921,7 +921,7 @@ describe('Test video playlists', function () { } { - const elem = obj[servers[0].videos[4].id] + const elem = obj[servers[0].store.videos[4].id] expect(elem).to.have.lengthOf(1) expect(elem[0].playlistId).to.equal(playlistServer1Id) expect(elem[0].startTimestamp).to.equal(45) @@ -934,29 +934,29 @@ describe('Test video playlists', function () { it('Should automatically update updatedAt field of playlists', async function () { const server = servers[1] - const videoId = servers[1].videos[5].id + const videoId = servers[1].store.videos[5].id async function getPlaylistNames () { - const { data } = await server.playlistsCommand.listByAccount({ token: server.accessToken, handle: 'root', sort: '-updatedAt' }) + const { data } = await server.playlists.listByAccount({ token: server.accessToken, handle: 'root', sort: '-updatedAt' }) return data.map(p => p.displayName) } const attributes = { videoId } - const element1 = await server.playlistsCommand.addElement({ playlistId: playlistServer2Id1, attributes }) - const element2 = await server.playlistsCommand.addElement({ playlistId: playlistServer2Id2, attributes }) + const element1 = await server.playlists.addElement({ playlistId: playlistServer2Id1, attributes }) + const element2 = await server.playlists.addElement({ playlistId: playlistServer2Id2, attributes }) const names1 = await getPlaylistNames() expect(names1[0]).to.equal('playlist 3 updated') expect(names1[1]).to.equal('playlist 2') - await server.playlistsCommand.removeElement({ playlistId: playlistServer2Id1, elementId: element1.id }) + await server.playlists.removeElement({ playlistId: playlistServer2Id1, elementId: element1.id }) const names2 = await getPlaylistNames() expect(names2[0]).to.equal('playlist 2') expect(names2[1]).to.equal('playlist 3 updated') - await server.playlistsCommand.removeElement({ playlistId: playlistServer2Id2, elementId: element2.id }) + await server.playlists.removeElement({ playlistId: playlistServer2Id2, elementId: element2.id }) const names3 = await getPlaylistNames() expect(names3[0]).to.equal('playlist 3 updated') @@ -972,7 +972,7 @@ describe('Test video playlists', function () { await waitJobs(servers) for (const server of servers) { - const body = await server.playlistsCommand.listVideos({ playlistId: playlistServer1UUID, start: 0, count: 10 }) + const body = await server.playlists.listVideos({ playlistId: playlistServer1UUID, start: 0, count: 10 }) expect(body.total).to.equal(6) const elements = body.data @@ -1005,14 +1005,14 @@ describe('Test video playlists', function () { attributes: { displayName: 'my super public playlist', privacy: VideoPlaylistPrivacy.PUBLIC, - videoChannelId: servers[0].videoChannel.id + videoChannelId: servers[0].store.channel.id } }) await waitJobs(servers) for (const server of servers) { - await server.playlistsCommand.get({ playlistId: videoPlaylistIds.uuid, expectedStatus: HttpStatusCode.OK_200 }) + await server.playlists.get({ playlistId: videoPlaylistIds.uuid, expectedStatus: HttpStatusCode.OK_200 }) } const attributes = { privacy: VideoPlaylistPrivacy.PRIVATE } @@ -1021,7 +1021,7 @@ describe('Test video playlists', function () { await waitJobs(servers) for (const server of [ servers[1], servers[2] ]) { - await server.playlistsCommand.get({ playlistId: videoPlaylistIds.uuid, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) + await server.playlists.get({ playlistId: videoPlaylistIds.uuid, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) } await commands[0].get({ playlistId: videoPlaylistIds.uuid, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) @@ -1039,7 +1039,7 @@ describe('Test video playlists', function () { await waitJobs(servers) for (const server of servers) { - await server.playlistsCommand.get({ playlistId: playlistServer1UUID, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) + await server.playlists.get({ playlistId: playlistServer1UUID, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) } }) @@ -1057,16 +1057,16 @@ describe('Test video playlists', function () { const finder = (data: VideoPlaylist[]) => data.find(p => p.displayName === 'my super playlist') { - const body = await servers[2].playlistsCommand.list({ start: 0, count: 5 }) + const body = await servers[2].playlists.list({ start: 0, count: 5 }) expect(body.total).to.equal(3) expect(finder(body.data)).to.not.be.undefined } - await servers[2].followsCommand.unfollow({ target: servers[0] }) + await servers[2].follows.unfollow({ target: servers[0] }) { - const body = await servers[2].playlistsCommand.list({ start: 0, count: 5 }) + const body = await servers[2].playlists.list({ start: 0, count: 5 }) expect(body.total).to.equal(1) expect(finder(body.data)).to.be.undefined @@ -1076,7 +1076,7 @@ describe('Test video playlists', function () { it('Should delete a channel and put the associated playlist in private mode', async function () { this.timeout(30000) - const channel = await servers[0].channelsCommand.create({ attributes: { name: 'super_channel', displayName: 'super channel' } }) + const channel = await servers[0].channels.create({ attributes: { name: 'super_channel', displayName: 'super channel' } }) const playlistCreated = await commands[0].create({ attributes: { @@ -1088,7 +1088,7 @@ describe('Test video playlists', function () { await waitJobs(servers) - await servers[0].channelsCommand.delete({ channelName: 'super_channel' }) + await servers[0].channels.delete({ channelName: 'super_channel' }) await waitJobs(servers) @@ -1096,15 +1096,15 @@ describe('Test video playlists', function () { expect(body.displayName).to.equal('channel playlist') expect(body.privacy.id).to.equal(VideoPlaylistPrivacy.PRIVATE) - await servers[1].playlistsCommand.get({ playlistId: playlistCreated.uuid, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) + await servers[1].playlists.get({ playlistId: playlistCreated.uuid, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) it('Should delete an account and delete its playlists', async function () { this.timeout(30000) - const { userId, token } = await servers[0].usersCommand.generate('user_1') + const { userId, token } = await servers[0].users.generate('user_1') - const { videoChannels } = await servers[0].usersCommand.getMyInfo({ token }) + const { videoChannels } = await servers[0].users.getMyInfo({ token }) const userChannel = videoChannels[0] await commands[0].create({ @@ -1121,18 +1121,18 @@ describe('Test video playlists', function () { { for (const server of [ servers[0], servers[1] ]) { - const body = await server.playlistsCommand.list({ start: 0, count: 15 }) + const body = await server.playlists.list({ start: 0, count: 15 }) expect(finder(body.data)).to.not.be.undefined } } - await servers[0].usersCommand.remove({ userId }) + await servers[0].users.remove({ userId }) await waitJobs(servers) { for (const server of [ servers[0], servers[1] ]) { - const body = await server.playlistsCommand.list({ start: 0, count: 15 }) + const body = await server.playlists.list({ start: 0, count: 15 }) expect(finder(body.data)).to.be.undefined } diff --git a/server/tests/api/videos/video-privacy.ts b/server/tests/api/videos/video-privacy.ts index bcf431edb..de08a9e7b 100644 --- a/server/tests/api/videos/video-privacy.ts +++ b/server/tests/api/videos/video-privacy.ts @@ -52,28 +52,28 @@ describe('Test video privacy', function () { for (const privacy of [ VideoPrivacy.PRIVATE, VideoPrivacy.INTERNAL ]) { const attributes = { privacy } - await servers[0].videosCommand.upload({ attributes }) + await servers[0].videos.upload({ attributes }) } await waitJobs(servers) }) it('Should not have these private and internal videos on server 2', async function () { - const { total, data } = await servers[1].videosCommand.list() + const { total, data } = await servers[1].videos.list() expect(total).to.equal(0) expect(data).to.have.lengthOf(0) }) it('Should not list the private and internal videos for an unauthenticated user on server 1', async function () { - const { total, data } = await servers[0].videosCommand.list() + const { total, data } = await servers[0].videos.list() expect(total).to.equal(0) expect(data).to.have.lengthOf(0) }) it('Should not list the private video and list the internal video for an authenticated user on server 1', async function () { - const { total, data } = await servers[0].videosCommand.listWithToken() + const { total, data } = await servers[0].videos.listWithToken() expect(total).to.equal(1) expect(data).to.have.lengthOf(1) @@ -82,7 +82,7 @@ describe('Test video privacy', function () { }) it('Should list my (private and internal) videos', async function () { - const { total, data } = await servers[0].videosCommand.listMyVideos() + const { total, data } = await servers[0].videos.listMyVideos() expect(total).to.equal(2) expect(data).to.have.lengthOf(2) @@ -97,8 +97,8 @@ describe('Test video privacy', function () { }) it('Should not be able to watch the private/internal video with non authenticated user', async function () { - await servers[0].videosCommand.get({ id: privateVideoUUID, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) - await servers[0].videosCommand.get({ id: internalVideoUUID, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) + await servers[0].videos.get({ id: privateVideoUUID, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) + await servers[0].videos.get({ id: internalVideoUUID, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should not be able to watch the private video with another user', async function () { @@ -108,11 +108,11 @@ describe('Test video privacy', function () { username: 'hello', password: 'super password' } - await servers[0].usersCommand.create({ username: user.username, password: user.password }) + await servers[0].users.create({ username: user.username, password: user.password }) - anotherUserToken = await servers[0].loginCommand.getAccessToken(user) + anotherUserToken = await servers[0].login.getAccessToken(user) - await servers[0].videosCommand.getWithToken({ + await servers[0].videos.getWithToken({ token: anotherUserToken, id: privateVideoUUID, expectedStatus: HttpStatusCode.FORBIDDEN_403 @@ -120,11 +120,11 @@ describe('Test video privacy', function () { }) it('Should be able to watch the internal video with another user', async function () { - await servers[0].videosCommand.getWithToken({ token: anotherUserToken, id: internalVideoUUID }) + await servers[0].videos.getWithToken({ token: anotherUserToken, id: internalVideoUUID }) }) it('Should be able to watch the private video with the correct user', async function () { - await servers[0].videosCommand.getWithToken({ id: privateVideoUUID }) + await servers[0].videos.getWithToken({ id: privateVideoUUID }) }) }) @@ -137,7 +137,7 @@ describe('Test video privacy', function () { name: 'unlisted video', privacy: VideoPrivacy.UNLISTED } - await servers[1].videosCommand.upload({ attributes }) + await servers[1].videos.upload({ attributes }) // Server 2 has transcoding enabled await waitJobs(servers) @@ -145,7 +145,7 @@ describe('Test video privacy', function () { it('Should not have this unlisted video listed on server 1 and 2', async function () { for (const server of servers) { - const { total, data } = await server.videosCommand.list() + const { total, data } = await server.videos.list() expect(total).to.equal(0) expect(data).to.have.lengthOf(0) @@ -153,7 +153,7 @@ describe('Test video privacy', function () { }) it('Should list my (unlisted) videos', async function () { - const { total, data } = await servers[1].videosCommand.listMyVideos() + const { total, data } = await servers[1].videos.listMyVideos() expect(total).to.equal(1) expect(data).to.have.lengthOf(1) @@ -162,13 +162,13 @@ describe('Test video privacy', function () { }) it('Should not be able to get this unlisted video using its id', async function () { - await servers[1].videosCommand.get({ id: unlistedVideo.id, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) + await servers[1].videos.get({ id: unlistedVideo.id, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) it('Should be able to get this unlisted video using its uuid/shortUUID', async function () { for (const server of servers) { for (const id of [ unlistedVideo.uuid, unlistedVideo.shortUUID ]) { - const video = await server.videosCommand.get({ id }) + const video = await server.videos.get({ id }) expect(video.name).to.equal('unlisted video') } @@ -182,13 +182,13 @@ describe('Test video privacy', function () { name: 'unlisted video', privacy: VideoPrivacy.UNLISTED } - await servers[0].videosCommand.upload({ attributes }) + await servers[0].videos.upload({ attributes }) await waitJobs(servers) }) it('Should list my new unlisted video', async function () { - const { total, data } = await servers[0].videosCommand.listMyVideos() + const { total, data } = await servers[0].videos.listMyVideos() expect(total).to.equal(3) expect(data).to.have.lengthOf(3) @@ -197,13 +197,13 @@ describe('Test video privacy', function () { }) it('Should be able to get non-federated unlisted video from origin', async function () { - const video = await servers[0].videosCommand.get({ id: nonFederatedUnlistedVideoUUID }) + const video = await servers[0].videos.get({ id: nonFederatedUnlistedVideoUUID }) expect(video.name).to.equal('unlisted video') }) it('Should not be able to get non-federated unlisted video from federated server', async function () { - await servers[1].videosCommand.get({ id: nonFederatedUnlistedVideoUUID, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) + await servers[1].videos.get({ id: nonFederatedUnlistedVideoUUID, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) }) @@ -220,7 +220,7 @@ describe('Test video privacy', function () { privacy: VideoPrivacy.PUBLIC } - await servers[0].videosCommand.update({ id: privateVideoId, attributes }) + await servers[0].videos.update({ id: privateVideoId, attributes }) } { @@ -228,7 +228,7 @@ describe('Test video privacy', function () { name: 'internal video becomes public', privacy: VideoPrivacy.PUBLIC } - await servers[0].videosCommand.update({ id: internalVideoId, attributes }) + await servers[0].videos.update({ id: internalVideoId, attributes }) } await waitJobs(servers) @@ -236,7 +236,7 @@ describe('Test video privacy', function () { it('Should have this new public video listed on server 1 and 2', async function () { for (const server of servers) { - const { total, data } = await server.videosCommand.list() + const { total, data } = await server.videos.list() expect(total).to.equal(2) expect(data).to.have.lengthOf(2) @@ -258,20 +258,20 @@ describe('Test video privacy', function () { it('Should set these videos as private and internal', async function () { this.timeout(10000) - await servers[0].videosCommand.update({ id: internalVideoId, attributes: { privacy: VideoPrivacy.PRIVATE } }) - await servers[0].videosCommand.update({ id: privateVideoId, attributes: { privacy: VideoPrivacy.INTERNAL } }) + await servers[0].videos.update({ id: internalVideoId, attributes: { privacy: VideoPrivacy.PRIVATE } }) + await servers[0].videos.update({ id: privateVideoId, attributes: { privacy: VideoPrivacy.INTERNAL } }) await waitJobs(servers) for (const server of servers) { - const { total, data } = await server.videosCommand.list() + const { total, data } = await server.videos.list() expect(total).to.equal(0) expect(data).to.have.lengthOf(0) } { - const { total, data } = await servers[0].videosCommand.listMyVideos() + const { total, data } = await servers[0].videos.listMyVideos() expect(total).to.equal(3) expect(data).to.have.lengthOf(3) diff --git a/server/tests/api/videos/video-schedule-update.ts b/server/tests/api/videos/video-schedule-update.ts index 635ae6ff1..3938b47c8 100644 --- a/server/tests/api/videos/video-schedule-update.ts +++ b/server/tests/api/videos/video-schedule-update.ts @@ -49,25 +49,25 @@ describe('Test video update scheduler', function () { } } - await servers[0].videosCommand.upload({ attributes }) + await servers[0].videos.upload({ attributes }) await waitJobs(servers) }) it('Should not list the video (in privacy mode)', async function () { for (const server of servers) { - const { total } = await server.videosCommand.list() + const { total } = await server.videos.list() expect(total).to.equal(0) } }) it('Should have my scheduled video in my account videos', async function () { - const { total, data } = await servers[0].videosCommand.listMyVideos() + const { total, data } = await servers[0].videos.listMyVideos() expect(total).to.equal(1) const videoFromList = data[0] - const videoFromGet = await servers[0].videosCommand.getWithToken({ id: videoFromList.uuid }) + const videoFromGet = await servers[0].videos.getWithToken({ id: videoFromList.uuid }) for (const video of [ videoFromList, videoFromGet ]) { expect(video.name).to.equal('video 1') @@ -84,7 +84,7 @@ describe('Test video update scheduler', function () { await waitJobs(servers) for (const server of servers) { - const { total, data } = await server.videosCommand.list() + const { total, data } = await server.videos.list() expect(total).to.equal(1) expect(data[0].name).to.equal('video 1') @@ -99,7 +99,7 @@ describe('Test video update scheduler', function () { privacy: VideoPrivacy.PRIVATE } - const { uuid } = await servers[0].videosCommand.upload({ attributes }) + const { uuid } = await servers[0].videos.upload({ attributes }) video2UUID = uuid await waitJobs(servers) @@ -116,20 +116,20 @@ describe('Test video update scheduler', function () { } } - await servers[0].videosCommand.update({ id: video2UUID, attributes }) + await servers[0].videos.update({ id: video2UUID, attributes }) await waitJobs(servers) }) it('Should not display the updated video', async function () { for (const server of servers) { - const { total } = await server.videosCommand.list() + const { total } = await server.videos.list() expect(total).to.equal(1) } }) it('Should have my scheduled updated video in my account videos', async function () { - const { total, data } = await servers[0].videosCommand.listMyVideos() + const { total, data } = await servers[0].videos.listMyVideos() expect(total).to.equal(2) const video = data.find(v => v.uuid === video2UUID) @@ -149,7 +149,7 @@ describe('Test video update scheduler', function () { await waitJobs(servers) for (const server of servers) { - const { total, data } = await server.videosCommand.list() + const { total, data } = await server.videos.list() expect(total).to.equal(2) const video = data.find(v => v.uuid === video2UUID) diff --git a/server/tests/api/videos/video-transcoder.ts b/server/tests/api/videos/video-transcoder.ts index b41c68283..37450eeeb 100644 --- a/server/tests/api/videos/video-transcoder.ts +++ b/server/tests/api/videos/video-transcoder.ts @@ -32,7 +32,7 @@ import { const expect = chai.expect function updateConfigForTranscoding (server: ServerInfo) { - return server.configCommand.updateCustomSubConfig({ + return server.config.updateCustomSubConfig({ newConfig: { transcoding: { enabled: true, @@ -82,15 +82,15 @@ describe('Test video transcoding', function () { description: 'my super description for server 1', fixture: 'video_short.webm' } - await servers[0].videosCommand.upload({ attributes }) + await servers[0].videos.upload({ attributes }) await waitJobs(servers) for (const server of servers) { - const { data } = await server.videosCommand.list() + const { data } = await server.videos.list() const video = data[0] - const videoDetails = await server.videosCommand.get({ id: video.id }) + const videoDetails = await server.videos.get({ id: video.id }) expect(videoDetails.files).to.have.lengthOf(1) const magnetUri = videoDetails.files[0].magnetUri @@ -111,15 +111,15 @@ describe('Test video transcoding', function () { description: 'my super description for server 2', fixture: 'video_short.webm' } - await servers[1].videosCommand.upload({ attributes }) + await servers[1].videos.upload({ attributes }) await waitJobs(servers) for (const server of servers) { - const { data } = await server.videosCommand.list() + const { data } = await server.videos.list() const video = data.find(v => v.name === attributes.name) - const videoDetails = await server.videosCommand.get({ id: video.id }) + const videoDetails = await server.videos.get({ id: video.id }) expect(videoDetails.files).to.have.lengthOf(4) @@ -143,11 +143,11 @@ describe('Test video transcoding', function () { fixture: 'video_short1.webm', waitTranscoding: true } - const { uuid } = await servers[1].videosCommand.upload({ attributes }) + const { uuid } = await servers[1].videos.upload({ attributes }) const videoId = uuid // Should be in transcode state - const body = await servers[1].videosCommand.get({ id: videoId }) + const body = await servers[1].videos.get({ id: videoId }) expect(body.name).to.equal('waiting video') expect(body.state.id).to.equal(VideoState.TO_TRANSCODE) expect(body.state.label).to.equal('To transcode') @@ -155,7 +155,7 @@ describe('Test video transcoding', function () { { // Should have my video - const { data } = await servers[1].videosCommand.listMyVideos() + const { data } = await servers[1].videos.listMyVideos() const videoToFindInMine = data.find(v => v.name === attributes.name) expect(videoToFindInMine).not.to.be.undefined expect(videoToFindInMine.state.id).to.equal(VideoState.TO_TRANSCODE) @@ -165,23 +165,23 @@ describe('Test video transcoding', function () { { // Should not list this video - const { data } = await servers[1].videosCommand.list() + const { data } = await servers[1].videos.list() const videoToFindInList = data.find(v => v.name === attributes.name) expect(videoToFindInList).to.be.undefined } // Server 1 should not have the video yet - await servers[0].videosCommand.get({ id: videoId, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) + await servers[0].videos.get({ id: videoId, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) } await waitJobs(servers) for (const server of servers) { - const { data } = await server.videosCommand.list() + const { data } = await server.videos.list() const videoToFind = data.find(v => v.name === 'waiting video') expect(videoToFind).not.to.be.undefined - const videoDetails = await server.videosCommand.get({ id: videoToFind.id }) + const videoDetails = await server.videos.get({ id: videoToFind.id }) expect(videoDetails.state.id).to.equal(VideoState.PUBLISHED) expect(videoDetails.state.label).to.equal('Published') @@ -207,15 +207,15 @@ describe('Test video transcoding', function () { fixture } - await servers[1].videosCommand.upload({ attributes }) + await servers[1].videos.upload({ attributes }) await waitJobs(servers) for (const server of servers) { - const { data } = await server.videosCommand.list() + const { data } = await server.videos.list() const video = data.find(v => v.name === attributes.name) - const videoDetails = await server.videosCommand.get({ id: video.id }) + const videoDetails = await server.videos.get({ id: video.id }) expect(videoDetails.files).to.have.lengthOf(4) const magnetUri = videoDetails.files[0].magnetUri @@ -232,7 +232,7 @@ describe('Test video transcoding', function () { fixture: 'video_short_4k.mp4' } - const { uuid } = await servers[1].videosCommand.upload({ attributes }) + const { uuid } = await servers[1].videos.upload({ attributes }) video4k = uuid await waitJobs(servers) @@ -240,7 +240,7 @@ describe('Test video transcoding', function () { const resolutions = [ 240, 360, 480, 720, 1080, 1440, 2160 ] for (const server of servers) { - const videoDetails = await server.videosCommand.get({ id: video4k }) + const videoDetails = await server.videos.get({ id: video4k }) expect(videoDetails.files).to.have.lengthOf(resolutions.length) for (const r of resolutions) { @@ -260,19 +260,19 @@ describe('Test video transcoding', function () { name: 'mp3_256k', fixture: 'video_short_mp3_256k.mp4' } - await servers[1].videosCommand.upload({ attributes }) + await servers[1].videos.upload({ attributes }) await waitJobs(servers) for (const server of servers) { - const { data } = await server.videosCommand.list() + const { data } = await server.videos.list() const video = data.find(v => v.name === attributes.name) - const videoDetails = await server.videosCommand.get({ id: video.id }) + const videoDetails = await server.videos.get({ id: video.id }) expect(videoDetails.files).to.have.lengthOf(4) - const path = servers[1].serversCommand.buildDirectory(join('videos', video.uuid + '-240.mp4')) + const path = servers[1].servers.buildDirectory(join('videos', video.uuid + '-240.mp4')) const probe = await getAudioStream(path) if (probe.audioStream) { @@ -291,18 +291,18 @@ describe('Test video transcoding', function () { name: 'no_audio', fixture: 'video_short_no_audio.mp4' } - await servers[1].videosCommand.upload({ attributes }) + await servers[1].videos.upload({ attributes }) await waitJobs(servers) for (const server of servers) { - const { data } = await server.videosCommand.list() + const { data } = await server.videos.list() const video = data.find(v => v.name === attributes.name) - const videoDetails = await server.videosCommand.get({ id: video.id }) + const videoDetails = await server.videos.get({ id: video.id }) expect(videoDetails.files).to.have.lengthOf(4) - const path = servers[1].serversCommand.buildDirectory(join('videos', video.uuid + '-240.mp4')) + const path = servers[1].servers.buildDirectory(join('videos', video.uuid + '-240.mp4')) const probe = await getAudioStream(path) expect(probe).to.not.have.property('audioStream') } @@ -315,21 +315,21 @@ describe('Test video transcoding', function () { name: 'untouched_audio', fixture: 'video_short.mp4' } - await servers[1].videosCommand.upload({ attributes }) + await servers[1].videos.upload({ attributes }) await waitJobs(servers) for (const server of servers) { - const { data } = await server.videosCommand.list() + const { data } = await server.videos.list() const video = data.find(v => v.name === attributes.name) - const videoDetails = await server.videosCommand.get({ id: video.id }) + const videoDetails = await server.videos.get({ id: video.id }) expect(videoDetails.files).to.have.lengthOf(4) const fixturePath = buildAbsoluteFixturePath(attributes.fixture) const fixtureVideoProbe = await getAudioStream(fixturePath) - const path = servers[1].serversCommand.buildDirectory(join('videos', video.uuid + '-240.mp4')) + const path = servers[1].servers.buildDirectory(join('videos', video.uuid + '-240.mp4')) const videoProbe = await getAudioStream(path) @@ -348,7 +348,7 @@ describe('Test video transcoding', function () { function runSuite (mode: 'legacy' | 'resumable') { before(async function () { - await servers[1].configCommand.updateCustomSubConfig({ + await servers[1].config.updateCustomSubConfig({ newConfig: { transcoding: { hls: { enabled: true }, @@ -372,15 +372,15 @@ describe('Test video transcoding', function () { this.timeout(60_000) const attributes = { name: 'audio_with_preview', previewfile: 'preview.jpg', fixture: 'sample.ogg' } - await servers[1].videosCommand.upload({ attributes, mode }) + await servers[1].videos.upload({ attributes, mode }) await waitJobs(servers) for (const server of servers) { - const { data } = await server.videosCommand.list() + const { data } = await server.videos.list() const video = data.find(v => v.name === 'audio_with_preview') - const videoDetails = await server.videosCommand.get({ id: video.id }) + const videoDetails = await server.videos.get({ id: video.id }) expect(videoDetails.files).to.have.lengthOf(1) @@ -396,15 +396,15 @@ describe('Test video transcoding', function () { this.timeout(60_000) const attributes = { name: 'audio_without_preview', fixture: 'sample.ogg' } - await servers[1].videosCommand.upload({ attributes, mode }) + await servers[1].videos.upload({ attributes, mode }) await waitJobs(servers) for (const server of servers) { - const { data } = await server.videosCommand.list() + const { data } = await server.videos.list() const video = data.find(v => v.name === 'audio_without_preview') - const videoDetails = await server.videosCommand.get({ id: video.id }) + const videoDetails = await server.videos.get({ id: video.id }) expect(videoDetails.files).to.have.lengthOf(1) @@ -419,7 +419,7 @@ describe('Test video transcoding', function () { it('Should upload an audio file and create an audio version only', async function () { this.timeout(60_000) - await servers[1].configCommand.updateCustomSubConfig({ + await servers[1].config.updateCustomSubConfig({ newConfig: { transcoding: { hls: { enabled: true }, @@ -434,12 +434,12 @@ describe('Test video transcoding', function () { }) const attributes = { name: 'audio_with_preview', previewfile: 'preview.jpg', fixture: 'sample.ogg' } - const { id } = await servers[1].videosCommand.upload({ attributes, mode }) + const { id } = await servers[1].videos.upload({ attributes, mode }) await waitJobs(servers) for (const server of servers) { - const videoDetails = await server.videosCommand.get({ id }) + const videoDetails = await server.videos.get({ id }) for (const files of [ videoDetails.files, videoDetails.streamingPlaylists[0].files ]) { expect(files).to.have.lengthOf(2) @@ -470,15 +470,15 @@ describe('Test video transcoding', function () { description: 'my super 30fps description for server 2', fixture: '60fps_720p_small.mp4' } - await servers[1].videosCommand.upload({ attributes }) + await servers[1].videos.upload({ attributes }) await waitJobs(servers) for (const server of servers) { - const { data } = await server.videosCommand.list() + const { data } = await server.videos.list() const video = data.find(v => v.name === attributes.name) - const videoDetails = await server.videosCommand.get({ id: video.id }) + const videoDetails = await server.videos.get({ id: video.id }) expect(videoDetails.files).to.have.lengthOf(4) expect(videoDetails.files[0].fps).to.be.above(58).and.below(62) @@ -487,13 +487,13 @@ describe('Test video transcoding', function () { expect(videoDetails.files[3].fps).to.be.below(31) for (const resolution of [ '240', '360', '480' ]) { - const path = servers[1].serversCommand.buildDirectory(join('videos', video.uuid + '-' + resolution + '.mp4')) + const path = servers[1].servers.buildDirectory(join('videos', video.uuid + '-' + resolution + '.mp4')) const fps = await getVideoFileFPS(path) expect(fps).to.be.below(31) } - const path = servers[1].serversCommand.buildDirectory(join('videos', video.uuid + '-720.mp4')) + const path = servers[1].servers.buildDirectory(join('videos', video.uuid + '-720.mp4')) const fps = await getVideoFileFPS(path) expect(fps).to.be.above(58).and.below(62) @@ -518,23 +518,23 @@ describe('Test video transcoding', function () { fixture: tempFixturePath } - await servers[1].videosCommand.upload({ attributes }) + await servers[1].videos.upload({ attributes }) await waitJobs(servers) for (const server of servers) { - const { data } = await server.videosCommand.list() + const { data } = await server.videos.list() const video = data.find(v => v.name === attributes.name) { - const path = servers[1].serversCommand.buildDirectory(join('videos', video.uuid + '-240.mp4')) + const path = servers[1].servers.buildDirectory(join('videos', video.uuid + '-240.mp4')) const fps = await getVideoFileFPS(path) expect(fps).to.be.equal(25) } { - const path = servers[1].serversCommand.buildDirectory(join('videos', video.uuid + '-720.mp4')) + const path = servers[1].servers.buildDirectory(join('videos', video.uuid + '-720.mp4')) const fps = await getVideoFileFPS(path) expect(fps).to.be.equal(59) } @@ -561,17 +561,17 @@ describe('Test video transcoding', function () { fixture: tempFixturePath } - await servers[1].videosCommand.upload({ attributes }) + await servers[1].videos.upload({ attributes }) await waitJobs(servers) for (const server of servers) { - const { data } = await server.videosCommand.list() + const { data } = await server.videos.list() const video = data.find(v => v.name === attributes.name) for (const resolution of [ '240', '360', '480', '720', '1080' ]) { - const path = servers[1].serversCommand.buildDirectory(join('videos', video.uuid + '-' + resolution + '.mp4')) + const path = servers[1].servers.buildDirectory(join('videos', video.uuid + '-' + resolution + '.mp4')) const bitrate = await getVideoFileBitrate(path) const fps = await getVideoFileFPS(path) @@ -602,21 +602,21 @@ describe('Test video transcoding', function () { hls: { enabled: true } } } - await servers[1].configCommand.updateCustomSubConfig({ newConfig }) + await servers[1].config.updateCustomSubConfig({ newConfig }) const attributes = { name: 'low bitrate', fixture: 'low-bitrate.mp4' } - const { uuid } = await servers[1].videosCommand.upload({ attributes }) + const { uuid } = await servers[1].videos.upload({ attributes }) await waitJobs(servers) const resolutions = [ 240, 360, 480, 720, 1080 ] for (const r of resolutions) { const path = `videos/${uuid}-${r}.mp4` - const size = await servers[1].serversCommand.getServerFileSize(path) + const size = await servers[1].servers.getServerFileSize(path) expect(size, `${path} not below ${60_000}`).to.be.below(60_000) } }) @@ -627,11 +627,11 @@ describe('Test video transcoding', function () { it('Should provide valid ffprobe data', async function () { this.timeout(160_000) - const videoUUID = (await servers[1].videosCommand.quickUpload({ name: 'ffprobe data' })).uuid + const videoUUID = (await servers[1].videos.quickUpload({ name: 'ffprobe data' })).uuid await waitJobs(servers) { - const path = servers[1].serversCommand.buildDirectory(join('videos', videoUUID + '-240.mp4')) + const path = servers[1].servers.buildDirectory(join('videos', videoUUID + '-240.mp4')) const metadata = await getMetadataFromFile(path) // expected format properties @@ -661,7 +661,7 @@ describe('Test video transcoding', function () { } for (const server of servers) { - const videoDetails = await server.videosCommand.get({ id: videoUUID }) + const videoDetails = await server.videos.get({ id: videoUUID }) const videoFiles = videoDetails.files .concat(videoDetails.streamingPlaylists[0].files) @@ -673,7 +673,7 @@ describe('Test video transcoding', function () { expect(file.metadataUrl).to.contain(servers[1].url) expect(file.metadataUrl).to.contain(videoUUID) - const metadata = await server.videosCommand.getFileMetadata({ url: file.metadataUrl }) + const metadata = await server.videos.getFileMetadata({ url: file.metadataUrl }) expect(metadata).to.have.nested.property('format.size') } } @@ -690,7 +690,7 @@ describe('Test video transcoding', function () { describe('Transcoding job queue', function () { it('Should have the appropriate priorities for transcoding jobs', async function () { - const body = await servers[1].jobsCommand.getJobsList({ + const body = await servers[1].jobs.getJobsList({ start: 0, count: 100, sort: '-createdAt', diff --git a/server/tests/api/videos/videos-filter.ts b/server/tests/api/videos/videos-filter.ts index 4a5a83ee6..af1541dbd 100644 --- a/server/tests/api/videos/videos-filter.ts +++ b/server/tests/api/videos/videos-filter.ts @@ -55,19 +55,19 @@ describe('Test videos filter', function () { for (const server of servers) { const moderator = { username: 'moderator', password: 'my super password' } - await server.usersCommand.create({ username: moderator.username, password: moderator.password, role: UserRole.MODERATOR }) - server['moderatorAccessToken'] = await server.loginCommand.getAccessToken(moderator) + await server.users.create({ username: moderator.username, password: moderator.password, role: UserRole.MODERATOR }) + server['moderatorAccessToken'] = await server.login.getAccessToken(moderator) - await server.videosCommand.upload({ attributes: { name: 'public ' + server.serverNumber } }) + await server.videos.upload({ attributes: { name: 'public ' + server.serverNumber } }) { const attributes = { name: 'unlisted ' + server.serverNumber, privacy: VideoPrivacy.UNLISTED } - await server.videosCommand.upload({ attributes }) + await server.videos.upload({ attributes }) } { const attributes = { name: 'private ' + server.serverNumber, privacy: VideoPrivacy.PRIVATE } - await server.videosCommand.upload({ attributes }) + await server.videos.upload({ attributes }) } } diff --git a/server/tests/api/videos/videos-history.ts b/server/tests/api/videos/videos-history.ts index 8614078f1..4b5e581d1 100644 --- a/server/tests/api/videos/videos-history.ts +++ b/server/tests/api/videos/videos-history.ts @@ -33,20 +33,20 @@ describe('Test videos history', function () { await setAccessTokensToServers([ server ]) - command = server.historyCommand + command = server.history { - const { uuid } = await server.videosCommand.upload({ attributes: { name: 'video 1' } }) + const { uuid } = await server.videos.upload({ attributes: { name: 'video 1' } }) video1UUID = uuid } { - const { uuid } = await server.videosCommand.upload({ attributes: { name: 'video 2' } }) + const { uuid } = await server.videos.upload({ attributes: { name: 'video 2' } }) video2UUID = uuid } { - const { uuid } = await server.videosCommand.upload({ attributes: { name: 'video 3' } }) + const { uuid } = await server.videos.upload({ attributes: { name: 'video 3' } }) video3UUID = uuid } @@ -54,15 +54,15 @@ describe('Test videos history', function () { username: 'user_1', password: 'super password' } - await server.usersCommand.create({ username: user.username, password: user.password }) - userAccessToken = await server.loginCommand.getAccessToken(user) + await server.users.create({ username: user.username, password: user.password }) + userAccessToken = await server.login.getAccessToken(user) }) it('Should get videos, without watching history', async function () { - const { data } = await server.videosCommand.listWithToken() + const { data } = await server.videos.listWithToken() for (const video of data) { - const videoDetails = await server.videosCommand.getWithToken({ id: video.id }) + const videoDetails = await server.videos.getWithToken({ id: video.id }) expect(video.userHistory).to.be.undefined expect(videoDetails.userHistory).to.be.undefined @@ -78,12 +78,12 @@ describe('Test videos history', function () { const videosOfVideos: Video[][] = [] { - const { data } = await server.videosCommand.listWithToken() + const { data } = await server.videos.listWithToken() videosOfVideos.push(data) } { - const body = await server.searchCommand.searchVideos({ token: server.accessToken, search: 'video' }) + const body = await server.search.searchVideos({ token: server.accessToken, search: 'video' }) videosOfVideos.push(body.data) } @@ -102,21 +102,21 @@ describe('Test videos history', function () { } { - const videoDetails = await server.videosCommand.getWithToken({ id: video1UUID }) + const videoDetails = await server.videos.getWithToken({ id: video1UUID }) expect(videoDetails.userHistory).to.not.be.undefined expect(videoDetails.userHistory.currentTime).to.equal(3) } { - const videoDetails = await server.videosCommand.getWithToken({ id: video2UUID }) + const videoDetails = await server.videos.getWithToken({ id: video2UUID }) expect(videoDetails.userHistory).to.not.be.undefined expect(videoDetails.userHistory.currentTime).to.equal(8) } { - const videoDetails = await server.videosCommand.getWithToken({ id: video3UUID }) + const videoDetails = await server.videos.getWithToken({ id: video3UUID }) expect(videoDetails.userHistory).to.be.undefined } @@ -164,7 +164,7 @@ describe('Test videos history', function () { }) it('Should disable videos history', async function () { - await server.usersCommand.updateMe({ + await server.users.updateMe({ videosHistoryEnabled: false }) @@ -172,7 +172,7 @@ describe('Test videos history', function () { }) it('Should re-enable videos history', async function () { - await server.usersCommand.updateMe({ + await server.users.updateMe({ videosHistoryEnabled: true }) diff --git a/server/tests/api/videos/videos-overview.ts b/server/tests/api/videos/videos-overview.ts index 969393842..f0657b334 100644 --- a/server/tests/api/videos/videos-overview.ts +++ b/server/tests/api/videos/videos-overview.ts @@ -25,7 +25,7 @@ describe('Test a videos overview', function () { }) it('Should send empty overview', async function () { - const body = await server.overviewsCommand.getVideos({ page: 1 }) + const body = await server.overviews.getVideos({ page: 1 }) testOverviewCount(body, 0) }) @@ -35,7 +35,7 @@ describe('Test a videos overview', function () { await wait(3000) - await server.videosCommand.upload({ + await server.videos.upload({ attributes: { name: 'video 0', category: 3, @@ -43,7 +43,7 @@ describe('Test a videos overview', function () { } }) - const body = await server.overviewsCommand.getVideos({ page: 1 }) + const body = await server.overviews.getVideos({ page: 1 }) testOverviewCount(body, 0) }) @@ -53,7 +53,7 @@ describe('Test a videos overview', function () { { for (let i = 1; i < 6; i++) { - await server.videosCommand.upload({ + await server.videos.upload({ attributes: { name: 'video ' + i, category: 3, @@ -66,13 +66,13 @@ describe('Test a videos overview', function () { } { - const body = await server.overviewsCommand.getVideos({ page: 1 }) + const body = await server.overviews.getVideos({ page: 1 }) testOverviewCount(body, 1) } { - const overview = await server.overviewsCommand.getVideos({ page: 2 }) + const overview = await server.overviews.getVideos({ page: 2 }) expect(overview.tags).to.have.lengthOf(1) expect(overview.categories).to.have.lengthOf(0) @@ -81,8 +81,8 @@ describe('Test a videos overview', function () { }) it('Should have the correct overview', async function () { - const overview1 = await server.overviewsCommand.getVideos({ page: 1 }) - const overview2 = await server.overviewsCommand.getVideos({ page: 2 }) + const overview1 = await server.overviews.getVideos({ page: 1 }) + const overview2 = await server.overviews.getVideos({ page: 2 }) for (const arr of [ overview1.tags, overview1.categories, overview1.channels, overview2.tags ]) { expect(arr).to.have.lengthOf(1) @@ -108,18 +108,18 @@ describe('Test a videos overview', function () { }) it('Should hide muted accounts', async function () { - const token = await server.usersCommand.generateUserAndToken('choco') + const token = await server.users.generateUserAndToken('choco') - await server.blocklistCommand.addToMyBlocklist({ token, account: 'root@' + server.host }) + await server.blocklist.addToMyBlocklist({ token, account: 'root@' + server.host }) { - const body = await server.overviewsCommand.getVideos({ page: 1 }) + const body = await server.overviews.getVideos({ page: 1 }) testOverviewCount(body, 1) } { - const body = await server.overviewsCommand.getVideos({ page: 1, token }) + const body = await server.overviews.getVideos({ page: 1, token }) testOverviewCount(body, 0) } diff --git a/server/tests/api/videos/videos-views-cleaner.ts b/server/tests/api/videos/videos-views-cleaner.ts index 7ded1bf38..238662cf3 100644 --- a/server/tests/api/videos/videos-views-cleaner.ts +++ b/server/tests/api/videos/videos-views-cleaner.ts @@ -30,15 +30,15 @@ describe('Test video views cleaner', function () { await doubleFollow(servers[0], servers[1]) - videoIdServer1 = (await servers[0].videosCommand.quickUpload({ name: 'video server 1' })).uuid - videoIdServer2 = (await servers[1].videosCommand.quickUpload({ name: 'video server 2' })).uuid + videoIdServer1 = (await servers[0].videos.quickUpload({ name: 'video server 1' })).uuid + videoIdServer2 = (await servers[1].videos.quickUpload({ name: 'video server 2' })).uuid await waitJobs(servers) - await servers[0].videosCommand.view({ id: videoIdServer1 }) - await servers[1].videosCommand.view({ id: videoIdServer1 }) - await servers[0].videosCommand.view({ id: videoIdServer2 }) - await servers[1].videosCommand.view({ id: videoIdServer2 }) + await servers[0].videos.view({ id: videoIdServer1 }) + await servers[1].videos.view({ id: videoIdServer1 }) + await servers[0].videos.view({ id: videoIdServer2 }) + await servers[1].videos.view({ id: videoIdServer2 }) await waitJobs(servers) }) @@ -56,14 +56,14 @@ describe('Test video views cleaner', function () { { for (const server of servers) { - const total = await server.sqlCommand.countVideoViewsOf(videoIdServer1) + const total = await server.sql.countVideoViewsOf(videoIdServer1) expect(total).to.equal(2, 'Server ' + server.serverNumber + ' does not have the correct amount of views') } } { for (const server of servers) { - const total = await server.sqlCommand.countVideoViewsOf(videoIdServer2) + const total = await server.sql.countVideoViewsOf(videoIdServer2) expect(total).to.equal(2, 'Server ' + server.serverNumber + ' does not have the correct amount of views') } } @@ -82,16 +82,16 @@ describe('Test video views cleaner', function () { { for (const server of servers) { - const total = await server.sqlCommand.countVideoViewsOf(videoIdServer1) + const total = await server.sql.countVideoViewsOf(videoIdServer1) expect(total).to.equal(2) } } { - const totalServer1 = await servers[0].sqlCommand.countVideoViewsOf(videoIdServer2) + const totalServer1 = await servers[0].sql.countVideoViewsOf(videoIdServer2) expect(totalServer1).to.equal(0) - const totalServer2 = await servers[1].sqlCommand.countVideoViewsOf(videoIdServer2) + const totalServer2 = await servers[1].sql.countVideoViewsOf(videoIdServer2) expect(totalServer2).to.equal(2) } }) diff --git a/server/tests/cli/create-import-video-file-job.ts b/server/tests/cli/create-import-video-file-job.ts index b1d9da242..26f4bdc8d 100644 --- a/server/tests/cli/create-import-video-file-job.ts +++ b/server/tests/cli/create-import-video-file-job.ts @@ -35,12 +35,12 @@ describe('Test create import video jobs', function () { // Upload two videos for our needs { - const { uuid } = await servers[0].videosCommand.upload({ attributes: { name: 'video1' } }) + const { uuid } = await servers[0].videos.upload({ attributes: { name: 'video1' } }) video1UUID = uuid } { - const { uuid } = await servers[1].videosCommand.upload({ attributes: { name: 'video2' } }) + const { uuid } = await servers[1].videos.upload({ attributes: { name: 'video2' } }) video2UUID = uuid } @@ -50,16 +50,16 @@ describe('Test create import video jobs', function () { it('Should run a import job on video 1 with a lower resolution', async function () { const command = `npm run create-import-video-file-job -- -v ${video1UUID} -i server/tests/fixtures/video_short-480.webm` - await servers[0].cliCommand.execWithEnv(command) + await servers[0].cli.execWithEnv(command) await waitJobs(servers) for (const server of servers) { - const { data: videos } = await server.videosCommand.list() + const { data: videos } = await server.videos.list() expect(videos).to.have.lengthOf(2) const video = videos.find(({ uuid }) => uuid === video1UUID) - const videoDetails = await server.videosCommand.get({ id: video.uuid }) + const videoDetails = await server.videos.get({ id: video.uuid }) expect(videoDetails.files).to.have.lengthOf(2) const [ originalVideo, transcodedVideo ] = videoDetails.files @@ -70,16 +70,16 @@ describe('Test create import video jobs', function () { it('Should run a import job on video 2 with the same resolution and a different extension', async function () { const command = `npm run create-import-video-file-job -- -v ${video2UUID} -i server/tests/fixtures/video_short.ogv` - await servers[1].cliCommand.execWithEnv(command) + await servers[1].cli.execWithEnv(command) await waitJobs(servers) for (const server of servers) { - const { data: videos } = await server.videosCommand.list() + const { data: videos } = await server.videos.list() expect(videos).to.have.lengthOf(2) const video = videos.find(({ uuid }) => uuid === video2UUID) - const videoDetails = await server.videosCommand.get({ id: video.uuid }) + const videoDetails = await server.videos.get({ id: video.uuid }) expect(videoDetails.files).to.have.lengthOf(4) const [ originalVideo, transcodedVideo420, transcodedVideo320, transcodedVideo240 ] = videoDetails.files @@ -92,16 +92,16 @@ describe('Test create import video jobs', function () { it('Should run a import job on video 2 with the same resolution and the same extension', async function () { const command = `npm run create-import-video-file-job -- -v ${video1UUID} -i server/tests/fixtures/video_short2.webm` - await servers[0].cliCommand.execWithEnv(command) + await servers[0].cli.execWithEnv(command) await waitJobs(servers) for (const server of servers) { - const { data: videos } = await server.videosCommand.list() + const { data: videos } = await server.videos.list() expect(videos).to.have.lengthOf(2) const video = videos.find(({ uuid }) => uuid === video1UUID) - const videoDetails = await server.videosCommand.get({ id: video.uuid }) + const videoDetails = await server.videos.get({ id: video.uuid }) expect(videoDetails.files).to.have.lengthOf(2) const [ video720, video480 ] = videoDetails.files diff --git a/server/tests/cli/create-transcoding-job.ts b/server/tests/cli/create-transcoding-job.ts index f629306e6..c9bbab802 100644 --- a/server/tests/cli/create-transcoding-job.ts +++ b/server/tests/cli/create-transcoding-job.ts @@ -42,12 +42,12 @@ describe('Test create transcoding jobs', function () { servers = await flushAndRunMultipleServers(2) await setAccessTokensToServers(servers) - await servers[0].configCommand.updateCustomSubConfig({ newConfig: config }) + await servers[0].config.updateCustomSubConfig({ newConfig: config }) await doubleFollow(servers[0], servers[1]) for (let i = 1; i <= 5; i++) { - const { uuid } = await servers[0].videosCommand.upload({ attributes: { name: 'video' + i } }) + const { uuid } = await servers[0].videos.upload({ attributes: { name: 'video' + i } }) videosUUID.push(uuid) } @@ -58,11 +58,11 @@ describe('Test create transcoding jobs', function () { this.timeout(30000) for (const server of servers) { - const { data } = await server.videosCommand.list() + const { data } = await server.videos.list() expect(data).to.have.lengthOf(videosUUID.length) for (const video of data) { - const videoDetail = await server.videosCommand.get({ id: video.uuid }) + const videoDetail = await server.videos.get({ id: video.uuid }) expect(videoDetail.files).to.have.lengthOf(1) expect(videoDetail.streamingPlaylists).to.have.lengthOf(0) } @@ -72,16 +72,16 @@ describe('Test create transcoding jobs', function () { it('Should run a transcoding job on video 2', async function () { this.timeout(60000) - await servers[0].cliCommand.execWithEnv(`npm run create-transcoding-job -- -v ${videosUUID[1]}`) + await servers[0].cli.execWithEnv(`npm run create-transcoding-job -- -v ${videosUUID[1]}`) await waitJobs(servers) for (const server of servers) { - const { data } = await server.videosCommand.list() + const { data } = await server.videos.list() let infoHashes: { [id: number]: string } for (const video of data) { - const videoDetail = await server.videosCommand.get({ id: video.uuid }) + const videoDetail = await server.videos.get({ id: video.uuid }) if (video.uuid === videosUUID[1]) { expect(videoDetail.files).to.have.lengthOf(4) @@ -110,15 +110,15 @@ describe('Test create transcoding jobs', function () { it('Should run a transcoding job on video 1 with resolution', async function () { this.timeout(60000) - await servers[0].cliCommand.execWithEnv(`npm run create-transcoding-job -- -v ${videosUUID[0]} -r 480`) + await servers[0].cli.execWithEnv(`npm run create-transcoding-job -- -v ${videosUUID[0]} -r 480`) await waitJobs(servers) for (const server of servers) { - const { data } = await server.videosCommand.list() + const { data } = await server.videos.list() expect(data).to.have.lengthOf(videosUUID.length) - const videoDetails = await server.videosCommand.get({ id: videosUUID[0] }) + const videoDetails = await server.videos.get({ id: videosUUID[0] }) expect(videoDetails.files).to.have.lengthOf(2) expect(videoDetails.files[0].resolution.id).to.equal(720) @@ -131,12 +131,12 @@ describe('Test create transcoding jobs', function () { it('Should generate an HLS resolution', async function () { this.timeout(120000) - await servers[0].cliCommand.execWithEnv(`npm run create-transcoding-job -- -v ${videosUUID[2]} --generate-hls -r 480`) + await servers[0].cli.execWithEnv(`npm run create-transcoding-job -- -v ${videosUUID[2]} --generate-hls -r 480`) await waitJobs(servers) for (const server of servers) { - const videoDetails = await server.videosCommand.get({ id: videosUUID[2] }) + const videoDetails = await server.videos.get({ id: videosUUID[2] }) expect(videoDetails.files).to.have.lengthOf(1) expect(videoDetails.streamingPlaylists).to.have.lengthOf(1) @@ -150,12 +150,12 @@ describe('Test create transcoding jobs', function () { it('Should not duplicate an HLS resolution', async function () { this.timeout(120000) - await servers[0].cliCommand.execWithEnv(`npm run create-transcoding-job -- -v ${videosUUID[2]} --generate-hls -r 480`) + await servers[0].cli.execWithEnv(`npm run create-transcoding-job -- -v ${videosUUID[2]} --generate-hls -r 480`) await waitJobs(servers) for (const server of servers) { - const videoDetails = await server.videosCommand.get({ id: videosUUID[2] }) + const videoDetails = await server.videos.get({ id: videosUUID[2] }) const files = videoDetails.streamingPlaylists[0].files expect(files).to.have.lengthOf(1) @@ -166,12 +166,12 @@ describe('Test create transcoding jobs', function () { it('Should generate all HLS resolutions', async function () { this.timeout(120000) - await servers[0].cliCommand.execWithEnv(`npm run create-transcoding-job -- -v ${videosUUID[3]} --generate-hls`) + await servers[0].cli.execWithEnv(`npm run create-transcoding-job -- -v ${videosUUID[3]} --generate-hls`) await waitJobs(servers) for (const server of servers) { - const videoDetails = await server.videosCommand.get({ id: videosUUID[3] }) + const videoDetails = await server.videos.get({ id: videosUUID[3] }) expect(videoDetails.files).to.have.lengthOf(1) expect(videoDetails.streamingPlaylists).to.have.lengthOf(1) @@ -185,14 +185,14 @@ describe('Test create transcoding jobs', function () { this.timeout(120000) config.transcoding.hls.enabled = true - await servers[0].configCommand.updateCustomSubConfig({ newConfig: config }) + await servers[0].config.updateCustomSubConfig({ newConfig: config }) - await servers[0].cliCommand.execWithEnv(`npm run create-transcoding-job -- -v ${videosUUID[4]}`) + await servers[0].cli.execWithEnv(`npm run create-transcoding-job -- -v ${videosUUID[4]}`) await waitJobs(servers) for (const server of servers) { - const videoDetails = await server.videosCommand.get({ id: videosUUID[4] }) + const videoDetails = await server.videos.get({ id: videosUUID[4] }) expect(videoDetails.files).to.have.lengthOf(4) expect(videoDetails.streamingPlaylists).to.have.lengthOf(1) diff --git a/server/tests/cli/optimize-old-videos.ts b/server/tests/cli/optimize-old-videos.ts index ef8603a33..eefc95a6d 100644 --- a/server/tests/cli/optimize-old-videos.ts +++ b/server/tests/cli/optimize-old-videos.ts @@ -41,8 +41,8 @@ describe('Test optimize old videos', function () { } // Upload two videos for our needs - await servers[0].videosCommand.upload({ attributes: { name: 'video1', fixture: tempFixturePath } }) - await servers[0].videosCommand.upload({ attributes: { name: 'video2', fixture: tempFixturePath } }) + await servers[0].videos.upload({ attributes: { name: 'video1', fixture: tempFixturePath } }) + await servers[0].videos.upload({ attributes: { name: 'video2', fixture: tempFixturePath } }) await waitJobs(servers) }) @@ -51,11 +51,11 @@ describe('Test optimize old videos', function () { this.timeout(30000) for (const server of servers) { - const { data } = await server.videosCommand.list() + const { data } = await server.videos.list() expect(data).to.have.lengthOf(2) for (const video of data) { - const videoDetails = await server.videosCommand.get({ id: video.uuid }) + const videoDetails = await server.videos.get({ id: video.uuid }) expect(videoDetails.files).to.have.lengthOf(1) } } @@ -64,29 +64,29 @@ describe('Test optimize old videos', function () { it('Should run optimize script', async function () { this.timeout(200000) - await servers[0].cliCommand.execWithEnv('npm run optimize-old-videos') + await servers[0].cli.execWithEnv('npm run optimize-old-videos') await waitJobs(servers) for (const server of servers) { - const { data } = await server.videosCommand.list() + const { data } = await server.videos.list() expect(data).to.have.lengthOf(2) for (const video of data) { - await server.videosCommand.view({ id: video.uuid }) + await server.videos.view({ id: video.uuid }) // Refresh video await waitJobs(servers) await wait(5000) await waitJobs(servers) - const videoDetails = await server.videosCommand.get({ id: video.uuid }) + const videoDetails = await server.videos.get({ id: video.uuid }) expect(videoDetails.files).to.have.lengthOf(1) const file = videoDetails.files[0] expect(file.size).to.be.below(8000000) - const path = servers[0].serversCommand.buildDirectory(join('videos', video.uuid + '-' + file.resolution.id + '.mp4')) + const path = servers[0].servers.buildDirectory(join('videos', video.uuid + '-' + file.resolution.id + '.mp4')) const bitrate = await getVideoFileBitrate(path) const fps = await getVideoFileFPS(path) const resolution = await getVideoFileResolution(path) diff --git a/server/tests/cli/peertube.ts b/server/tests/cli/peertube.ts index fe5f63191..a83aa7724 100644 --- a/server/tests/cli/peertube.ts +++ b/server/tests/cli/peertube.ts @@ -30,16 +30,16 @@ describe('Test CLI wrapper', function () { server = await flushAndRunServer(1) await setAccessTokensToServers([ server ]) - await server.usersCommand.create({ username: 'user_1', password: 'super_password' }) + await server.users.create({ username: 'user_1', password: 'super_password' }) - userAccessToken = await server.loginCommand.getAccessToken({ username: 'user_1', password: 'super_password' }) + userAccessToken = await server.login.getAccessToken({ username: 'user_1', password: 'super_password' }) { const attributes = { name: 'user_channel', displayName: 'User channel', support: 'super support text' } - await server.channelsCommand.create({ token: userAccessToken, attributes }) + await server.channels.create({ token: userAccessToken, attributes }) } - cliCommand = server.cliCommand + cliCommand = server.cli }) describe('Authentication and instance selection', function () { @@ -48,7 +48,7 @@ describe('Test CLI wrapper', function () { const stdout = await cliCommand.execWithEnv(`${cmd} token --url ${server.url} --username user_1 --password super_password`) const token = stdout.trim() - const body = await server.usersCommand.getMyInfo({ token }) + const body = await server.users.getMyInfo({ token }) expect(body.username).to.equal('user_1') }) @@ -103,10 +103,10 @@ describe('Test CLI wrapper', function () { }) it('Should have the video uploaded', async function () { - const { total, data } = await server.videosCommand.list() + const { total, data } = await server.videos.list() expect(total).to.equal(1) - const video = await server.videosCommand.get({ id: data[0].uuid }) + const video = await server.videos.get({ id: data[0].uuid }) expect(video.name).to.equal('test upload') expect(video.support).to.equal('support_text') expect(video.channel.name).to.equal('user_channel') @@ -128,19 +128,19 @@ describe('Test CLI wrapper', function () { await waitJobs([ server ]) - const { total, data } = await server.videosCommand.list() + const { total, data } = await server.videos.list() expect(total).to.equal(2) const video = data.find(v => v.name === 'small video - youtube') expect(video).to.not.be.undefined - const videoDetails = await server.videosCommand.get({ id: video.id }) + const videoDetails = await server.videos.get({ id: video.id }) expect(videoDetails.channel.name).to.equal('user_channel') expect(videoDetails.support).to.equal('super support text') expect(videoDetails.nsfw).to.be.false // So we can reimport it - await server.videosCommand.remove({ token: userAccessToken, id: video.id }) + await server.videos.remove({ token: userAccessToken, id: video.id }) }) it('Should import and override some imported attributes', async function () { @@ -155,13 +155,13 @@ describe('Test CLI wrapper', function () { await waitJobs([ server ]) { - const { total, data } = await server.videosCommand.list() + const { total, data } = await server.videos.list() expect(total).to.equal(2) const video = data.find(v => v.name === 'toto') expect(video).to.not.be.undefined - const videoDetails = await server.videosCommand.get({ id: video.id }) + const videoDetails = await server.videos.get({ id: video.id }) expect(videoDetails.channel.name).to.equal('user_channel') expect(videoDetails.support).to.equal('support') expect(videoDetails.nsfw).to.be.true @@ -225,10 +225,10 @@ describe('Test CLI wrapper', function () { servers = [ server, anotherServer ] await waitJobs(servers) - const { uuid } = await anotherServer.videosCommand.quickUpload({ name: 'super video' }) + const { uuid } = await anotherServer.videos.quickUpload({ name: 'super video' }) await waitJobs(servers) - video1Server2 = await server.videosCommand.getId({ uuid }) + video1Server2 = await server.videos.getId({ uuid }) }) it('Should add a redundancy', async function () { diff --git a/server/tests/cli/plugins.ts b/server/tests/cli/plugins.ts index 5344bfc96..178a7a2d9 100644 --- a/server/tests/cli/plugins.ts +++ b/server/tests/cli/plugins.ts @@ -27,13 +27,13 @@ describe('Test plugin scripts', function () { const packagePath = PluginsCommand.getPluginTestPath() - await server.cliCommand.execWithEnv(`npm run plugin:install -- --plugin-path ${packagePath}`) + await server.cli.execWithEnv(`npm run plugin:install -- --plugin-path ${packagePath}`) }) it('Should install a theme from stateless CLI', async function () { this.timeout(60000) - await server.cliCommand.execWithEnv(`npm run plugin:install -- --npm-name peertube-theme-background-red`) + await server.cli.execWithEnv(`npm run plugin:install -- --npm-name peertube-theme-background-red`) }) it('Should have the theme and the plugin registered when we restart peertube', async function () { @@ -42,7 +42,7 @@ describe('Test plugin scripts', function () { await killallServers([ server ]) await reRunServer(server) - const config = await server.configCommand.getConfig() + const config = await server.config.getConfig() const plugin = config.plugin.registered .find(p => p.name === 'test') @@ -56,7 +56,7 @@ describe('Test plugin scripts', function () { it('Should uninstall a plugin from stateless CLI', async function () { this.timeout(60000) - await server.cliCommand.execWithEnv(`npm run plugin:uninstall -- --npm-name peertube-plugin-test`) + await server.cli.execWithEnv(`npm run plugin:uninstall -- --npm-name peertube-plugin-test`) }) it('Should have removed the plugin on another peertube restart', async function () { @@ -65,7 +65,7 @@ describe('Test plugin scripts', function () { await killallServers([ server ]) await reRunServer(server) - const config = await server.configCommand.getConfig() + const config = await server.config.getConfig() const plugin = config.plugin.registered .find(p => p.name === 'test') diff --git a/server/tests/cli/prune-storage.ts b/server/tests/cli/prune-storage.ts index a4556312b..9912a36e0 100644 --- a/server/tests/cli/prune-storage.ts +++ b/server/tests/cli/prune-storage.ts @@ -24,13 +24,13 @@ import { VideoPlaylistPrivacy } from '@shared/models' const expect = chai.expect async function countFiles (server: ServerInfo, directory: string) { - const files = await readdir(server.serversCommand.buildDirectory(directory)) + const files = await readdir(server.servers.buildDirectory(directory)) return files.length } async function assertNotExists (server: ServerInfo, directory: string, substring: string) { - const files = await readdir(server.serversCommand.buildDirectory(directory)) + const files = await readdir(server.servers.buildDirectory(directory)) for (const f of files) { expect(f).to.not.contain(substring) @@ -68,16 +68,16 @@ describe('Test prune storage scripts', function () { await setDefaultVideoChannel(servers) for (const server of servers) { - await server.videosCommand.upload({ attributes: { name: 'video 1' } }) - await server.videosCommand.upload({ attributes: { name: 'video 2' } }) + await server.videos.upload({ attributes: { name: 'video 1' } }) + await server.videos.upload({ attributes: { name: 'video 2' } }) - await server.usersCommand.updateMyAvatar({ fixture: 'avatar.png' }) + await server.users.updateMyAvatar({ fixture: 'avatar.png' }) - await server.playlistsCommand.create({ + await server.playlists.create({ attributes: { displayName: 'playlist', privacy: VideoPlaylistPrivacy.PUBLIC, - videoChannelId: server.videoChannel.id, + videoChannelId: server.store.channel.id, thumbnailfile: 'thumbnail.jpg' } }) @@ -87,7 +87,7 @@ describe('Test prune storage scripts', function () { // Lazy load the remote avatar { - const account = await servers[0].accountsCommand.get({ accountName: 'root@localhost:' + servers[1].port }) + const account = await servers[0].accounts.get({ accountName: 'root@localhost:' + servers[1].port }) await makeGetRequest({ url: servers[0].url, path: account.avatar.path, @@ -96,7 +96,7 @@ describe('Test prune storage scripts', function () { } { - const account = await servers[1].accountsCommand.get({ accountName: 'root@localhost:' + servers[0].port }) + const account = await servers[1].accounts.get({ accountName: 'root@localhost:' + servers[0].port }) await makeGetRequest({ url: servers[1].url, path: account.avatar.path, @@ -119,7 +119,7 @@ describe('Test prune storage scripts', function () { it('Should create some dirty files', async function () { for (let i = 0; i < 2; i++) { { - const base = servers[0].serversCommand.buildDirectory('videos') + const base = servers[0].servers.buildDirectory('videos') const n1 = buildUUID() + '.mp4' const n2 = buildUUID() + '.webm' @@ -131,7 +131,7 @@ describe('Test prune storage scripts', function () { } { - const base = servers[0].serversCommand.buildDirectory('torrents') + const base = servers[0].servers.buildDirectory('torrents') const n1 = buildUUID() + '-240.torrent' const n2 = buildUUID() + '-480.torrent' @@ -143,7 +143,7 @@ describe('Test prune storage scripts', function () { } { - const base = servers[0].serversCommand.buildDirectory('thumbnails') + const base = servers[0].servers.buildDirectory('thumbnails') const n1 = buildUUID() + '.jpg' const n2 = buildUUID() + '.jpg' @@ -155,7 +155,7 @@ describe('Test prune storage scripts', function () { } { - const base = servers[0].serversCommand.buildDirectory('previews') + const base = servers[0].servers.buildDirectory('previews') const n1 = buildUUID() + '.jpg' const n2 = buildUUID() + '.jpg' @@ -167,7 +167,7 @@ describe('Test prune storage scripts', function () { } { - const base = servers[0].serversCommand.buildDirectory('avatars') + const base = servers[0].servers.buildDirectory('avatars') const n1 = buildUUID() + '.png' const n2 = buildUUID() + '.jpg' @@ -183,7 +183,7 @@ describe('Test prune storage scripts', function () { it('Should run prune storage', async function () { this.timeout(30000) - const env = servers[0].cliCommand.getEnv() + const env = servers[0].cli.getEnv() await CLICommand.exec(`echo y | ${env} npm run prune-storage`) }) diff --git a/server/tests/cli/regenerate-thumbnails.ts b/server/tests/cli/regenerate-thumbnails.ts index d59520783..2df1a1157 100644 --- a/server/tests/cli/regenerate-thumbnails.ts +++ b/server/tests/cli/regenerate-thumbnails.ts @@ -15,7 +15,7 @@ import { } from '../../../shared/extra-utils' async function testThumbnail (server: ServerInfo, videoId: number | string) { - const video = await server.videosCommand.get({ id: videoId }) + const video = await server.videos.get({ id: videoId }) const requests = [ makeRawRequest(join(server.url, video.thumbnailPath), HttpStatusCode.OK_200), @@ -47,22 +47,22 @@ describe('Test regenerate thumbnails script', function () { await doubleFollow(servers[0], servers[1]) { - const videoUUID1 = (await servers[0].videosCommand.quickUpload({ name: 'video 1' })).uuid - video1 = await servers[0].videosCommand.get({ id: videoUUID1 }) + const videoUUID1 = (await servers[0].videos.quickUpload({ name: 'video 1' })).uuid + video1 = await servers[0].videos.get({ id: videoUUID1 }) - thumbnail1Path = join(servers[0].serversCommand.buildDirectory('thumbnails'), basename(video1.thumbnailPath)) + thumbnail1Path = join(servers[0].servers.buildDirectory('thumbnails'), basename(video1.thumbnailPath)) - const videoUUID2 = (await servers[0].videosCommand.quickUpload({ name: 'video 2' })).uuid - video2 = await servers[0].videosCommand.get({ id: videoUUID2 }) + const videoUUID2 = (await servers[0].videos.quickUpload({ name: 'video 2' })).uuid + video2 = await servers[0].videos.get({ id: videoUUID2 }) } { - const videoUUID = (await servers[1].videosCommand.quickUpload({ name: 'video 3' })).uuid + const videoUUID = (await servers[1].videos.quickUpload({ name: 'video 3' })).uuid await waitJobs(servers) - remoteVideo = await servers[0].videosCommand.get({ id: videoUUID }) + remoteVideo = await servers[0].videos.get({ id: videoUUID }) - thumbnailRemotePath = join(servers[0].serversCommand.buildDirectory('thumbnails'), basename(remoteVideo.thumbnailPath)) + thumbnailRemotePath = join(servers[0].servers.buildDirectory('thumbnails'), basename(remoteVideo.thumbnailPath)) } await writeFile(thumbnail1Path, '') @@ -89,7 +89,7 @@ describe('Test regenerate thumbnails script', function () { it('Should regenerate local thumbnails from the CLI', async function () { this.timeout(15000) - await servers[0].cliCommand.execWithEnv(`npm run regenerate-thumbnails`) + await servers[0].cli.execWithEnv(`npm run regenerate-thumbnails`) }) it('Should have generated new thumbnail files', async function () { diff --git a/server/tests/cli/reset-password.ts b/server/tests/cli/reset-password.ts index 5e1e1c2af..e0d6f220a 100644 --- a/server/tests/cli/reset-password.ts +++ b/server/tests/cli/reset-password.ts @@ -9,16 +9,16 @@ describe('Test reset password scripts', function () { server = await flushAndRunServer(1) await setAccessTokensToServers([ server ]) - await server.usersCommand.create({ username: 'user_1', password: 'super password' }) + await server.users.create({ username: 'user_1', password: 'super password' }) }) it('Should change the user password from CLI', async function () { this.timeout(60000) - const env = server.cliCommand.getEnv() + const env = server.cli.getEnv() await CLICommand.exec(`echo coucou | ${env} npm run reset-password -- -u user_1`) - await server.loginCommand.login({ user: { username: 'user_1', password: 'coucou' } }) + await server.login.login({ user: { username: 'user_1', password: 'coucou' } }) }) after(async function () { diff --git a/server/tests/cli/update-host.ts b/server/tests/cli/update-host.ts index d90b4a64d..d2d196456 100644 --- a/server/tests/cli/update-host.ts +++ b/server/tests/cli/update-host.ts @@ -30,11 +30,11 @@ describe('Test update host scripts', function () { await setAccessTokensToServers([ server ]) // Upload two videos for our needs - const { uuid: video1UUID } = await server.videosCommand.upload() - await server.videosCommand.upload() + const { uuid: video1UUID } = await server.videos.upload() + await server.videos.upload() // Create a user - await server.usersCommand.create({ username: 'toto', password: 'coucou' }) + await server.users.create({ username: 'toto', password: 'coucou' }) // Create channel const videoChannel = { @@ -42,11 +42,11 @@ describe('Test update host scripts', function () { displayName: 'second video channel', description: 'super video channel description' } - await server.channelsCommand.create({ attributes: videoChannel }) + await server.channels.create({ attributes: videoChannel }) // Create comments const text = 'my super first comment' - await server.commentsCommand.createThread({ videoId: video1UUID, text }) + await server.comments.createThread({ videoId: video1UUID, text }) await waitJobs(server) }) @@ -58,11 +58,11 @@ describe('Test update host scripts', function () { // Run server with standard configuration await reRunServer(server) - await server.cliCommand.execWithEnv(`npm run update-host`) + await server.cli.execWithEnv(`npm run update-host`) }) it('Should have updated videos url', async function () { - const { total, data } = await server.videosCommand.list() + const { total, data } = await server.videos.list() expect(total).to.equal(2) for (const video of data) { @@ -70,7 +70,7 @@ describe('Test update host scripts', function () { expect(body.id).to.equal('http://localhost:9002/videos/watch/' + video.uuid) - const videoDetails = await server.videosCommand.get({ id: video.uuid }) + const videoDetails = await server.videos.get({ id: video.uuid }) expect(videoDetails.trackerUrls[0]).to.include(server.host) expect(videoDetails.streamingPlaylists[0].playlistUrl).to.include(server.host) @@ -79,7 +79,7 @@ describe('Test update host scripts', function () { }) it('Should have updated video channels url', async function () { - const { data, total } = await server.channelsCommand.list({ sort: '-name' }) + const { data, total } = await server.channels.list({ sort: '-name' }) expect(total).to.equal(3) for (const channel of data) { @@ -90,7 +90,7 @@ describe('Test update host scripts', function () { }) it('Should have updated accounts url', async function () { - const body = await server.accountsCommand.list() + const body = await server.accounts.list() expect(body.total).to.equal(3) for (const account of body.data) { @@ -104,11 +104,11 @@ describe('Test update host scripts', function () { it('Should have updated torrent hosts', async function () { this.timeout(30000) - const { data } = await server.videosCommand.list() + const { data } = await server.videos.list() expect(data).to.have.lengthOf(2) for (const video of data) { - const videoDetails = await server.videosCommand.get({ id: video.id }) + const videoDetails = await server.videos.get({ id: video.id }) expect(videoDetails.files).to.have.lengthOf(4) diff --git a/server/tests/client.ts b/server/tests/client.ts index e91d4c671..caf6fb00c 100644 --- a/server/tests/client.ts +++ b/server/tests/client.ts @@ -59,8 +59,8 @@ describe('Test a client controllers', function () { await setDefaultVideoChannel(servers) - await servers[0].channelsCommand.update({ - channelName: servers[0].videoChannel.name, + await servers[0].channels.update({ + channelName: servers[0].store.channel.name, attributes: { description: channelDescription } }) @@ -68,13 +68,13 @@ describe('Test a client controllers', function () { { const attributes = { name: videoName, description: videoDescription } - await servers[0].videosCommand.upload({ attributes }) + await servers[0].videos.upload({ attributes }) - const { data } = await servers[0].videosCommand.list() + const { data } = await servers[0].videos.list() expect(data.length).to.equal(1) const video = data[0] - servers[0].video = video + servers[0].store.video = video videoIds = [ video.id, video.uuid, video.shortUUID ] } @@ -85,21 +85,21 @@ describe('Test a client controllers', function () { displayName: playlistName, description: playlistDescription, privacy: VideoPlaylistPrivacy.PUBLIC, - videoChannelId: servers[0].videoChannel.id + videoChannelId: servers[0].store.channel.id } - playlist = await servers[0].playlistsCommand.create({ attributes }) + playlist = await servers[0].playlists.create({ attributes }) playlistIds = [ playlist.id, playlist.shortUUID, playlist.uuid ] - await servers[0].playlistsCommand.addElement({ playlistId: playlist.shortUUID, attributes: { videoId: servers[0].video.id } }) + await servers[0].playlists.addElement({ playlistId: playlist.shortUUID, attributes: { videoId: servers[0].store.video.id } }) } // Account { - await servers[0].usersCommand.updateMe({ description: 'my account description' }) + await servers[0].users.updateMe({ description: 'my account description' }) - account = await servers[0].accountsCommand.get({ accountName: `${servers[0].user.username}@${servers[0].host}` }) + account = await servers[0].accounts.get({ accountName: `${servers[0].store.user.username}@${servers[0].host}` }) } await waitJobs(servers) @@ -120,8 +120,8 @@ describe('Test a client controllers', function () { const port = servers[0].port const expectedLink = '` + `url=http%3A%2F%2Flocalhost%3A${port}%2Fw%2F${servers[0].store.video.uuid}" ` + + `title="${servers[0].store.video.name}" />` expect(res.text).to.contain(expectedLink) } @@ -159,17 +159,17 @@ describe('Test a client controllers', function () { expect(text).to.contain(``) expect(text).to.contain(``) expect(text).to.contain('') - expect(text).to.contain(``) + expect(text).to.contain(``) } async function channelPageTest (path: string) { const res = await makeGetRequest({ url: servers[0].url, path, accept: 'text/html', statusCodeExpected: HttpStatusCode.OK_200 }) const text = res.text - expect(text).to.contain(``) + expect(text).to.contain(``) expect(text).to.contain(``) expect(text).to.contain('') - expect(text).to.contain(``) + expect(text).to.contain(``) } async function watchVideoPageTest (path: string) { @@ -179,7 +179,7 @@ describe('Test a client controllers', function () { expect(text).to.contain(``) expect(text).to.contain(``) expect(text).to.contain('') - expect(text).to.contain(``) + expect(text).to.contain(``) } async function watchPlaylistPageTest (path: string) { @@ -193,15 +193,15 @@ describe('Test a client controllers', function () { } it('Should have valid Open Graph tags on the account page', async function () { - await accountPageTest('/accounts/' + servers[0].user.username) - await accountPageTest('/a/' + servers[0].user.username) - await accountPageTest('/@' + servers[0].user.username) + await accountPageTest('/accounts/' + servers[0].store.user.username) + await accountPageTest('/a/' + servers[0].store.user.username) + await accountPageTest('/@' + servers[0].store.user.username) }) it('Should have valid Open Graph tags on the channel page', async function () { - await channelPageTest('/video-channels/' + servers[0].videoChannel.name) - await channelPageTest('/c/' + servers[0].videoChannel.name) - await channelPageTest('/@' + servers[0].videoChannel.name) + await channelPageTest('/video-channels/' + servers[0].store.channel.name) + await channelPageTest('/c/' + servers[0].store.channel.name) + await channelPageTest('/@' + servers[0].store.channel.name) }) it('Should have valid Open Graph tags on the watch page', async function () { @@ -241,7 +241,7 @@ describe('Test a client controllers', function () { expect(text).to.contain('') expect(text).to.contain('') - expect(text).to.contain(``) + expect(text).to.contain(``) expect(text).to.contain(``) } @@ -288,22 +288,22 @@ describe('Test a client controllers', function () { }) it('Should have valid twitter card on the channel page', async function () { - await channelPageTest('/video-channels/' + servers[0].videoChannel.name) - await channelPageTest('/c/' + servers[0].videoChannel.name) - await channelPageTest('/@' + servers[0].videoChannel.name) + await channelPageTest('/video-channels/' + servers[0].store.channel.name) + await channelPageTest('/c/' + servers[0].store.channel.name) + await channelPageTest('/@' + servers[0].store.channel.name) }) }) describe('Whitelisted', function () { before(async function () { - const config = await servers[0].configCommand.getCustomConfig() + const config = await servers[0].config.getCustomConfig() config.services.twitter = { username: '@Kuja', whitelisted: true } - await servers[0].configCommand.updateCustomConfig({ newCustomConfig: config }) + await servers[0].config.updateCustomConfig({ newCustomConfig: config }) }) async function accountPageTest (path: string) { @@ -361,9 +361,9 @@ describe('Test a client controllers', function () { }) it('Should have valid twitter card on the channel page', async function () { - await channelPageTest('/video-channels/' + servers[0].videoChannel.name) - await channelPageTest('/c/' + servers[0].videoChannel.name) - await channelPageTest('/@' + servers[0].videoChannel.name) + await channelPageTest('/video-channels/' + servers[0].store.channel.name) + await channelPageTest('/c/' + servers[0].store.channel.name) + await channelPageTest('/@' + servers[0].store.channel.name) }) }) }) @@ -371,7 +371,7 @@ describe('Test a client controllers', function () { describe('Index HTML', function () { it('Should have valid index html tags (title, description...)', async function () { - const config = await servers[0].configCommand.getConfig() + const config = await servers[0].config.getConfig() const res = await makeHTMLRequest(servers[0].url, '/videos/trending') const description = 'PeerTube, an ActivityPub-federated video streaming platform using P2P directly in your web browser.' @@ -379,7 +379,7 @@ describe('Test a client controllers', function () { }) it('Should update the customized configuration and have the correct index html tags', async function () { - await servers[0].configCommand.updateCustomSubConfig({ + await servers[0].config.updateCustomSubConfig({ newConfig: { instance: { name: 'PeerTube updated', @@ -396,14 +396,14 @@ describe('Test a client controllers', function () { } }) - const config = await servers[0].configCommand.getConfig() + const config = await servers[0].config.getConfig() const res = await makeHTMLRequest(servers[0].url, '/videos/trending') checkIndexTags(res.text, 'PeerTube updated', 'my short description', 'body { background-color: red; }', config) }) it('Should have valid index html updated tags (title, description...)', async function () { - const config = await servers[0].configCommand.getConfig() + const config = await servers[0].config.getConfig() const res = await makeHTMLRequest(servers[0].url, '/videos/trending') checkIndexTags(res.text, 'PeerTube updated', 'my short description', 'body { background-color: red; }', config) @@ -413,7 +413,7 @@ describe('Test a client controllers', function () { for (const basePath of watchVideoBasePaths) { for (const id of videoIds) { const res = await makeHTMLRequest(servers[1].url, basePath + id) - expect(res.text).to.contain(``) + expect(res.text).to.contain(``) } } }) @@ -451,8 +451,8 @@ describe('Test a client controllers', function () { describe('Embed HTML', function () { it('Should have the correct embed html tags', async function () { - const config = await servers[0].configCommand.getConfig() - const res = await makeHTMLRequest(servers[0].url, servers[0].video.embedPath) + const config = await servers[0].config.getConfig() + const res = await makeHTMLRequest(servers[0].url, servers[0].store.video.embedPath) checkIndexTags(res.text, 'PeerTube updated', 'my short description', 'body { background-color: red; }', config) }) diff --git a/server/tests/external-plugins/auth-ldap.ts b/server/tests/external-plugins/auth-ldap.ts index b626ab2bb..ef624152e 100644 --- a/server/tests/external-plugins/auth-ldap.ts +++ b/server/tests/external-plugins/auth-ldap.ts @@ -16,15 +16,15 @@ describe('Official plugin auth-ldap', function () { server = await flushAndRunServer(1) await setAccessTokensToServers([ server ]) - await server.pluginsCommand.install({ npmName: 'peertube-plugin-auth-ldap' }) + await server.plugins.install({ npmName: 'peertube-plugin-auth-ldap' }) }) it('Should not login with without LDAP settings', async function () { - await server.loginCommand.login({ user: { username: 'fry', password: 'fry' }, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) + await server.login.login({ user: { username: 'fry', password: 'fry' }, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) it('Should not login with bad LDAP settings', async function () { - await server.pluginsCommand.updateSettings({ + await server.plugins.updateSettings({ npmName: 'peertube-plugin-auth-ldap', settings: { 'bind-credentials': 'GoodNewsEveryone', @@ -38,11 +38,11 @@ describe('Official plugin auth-ldap', function () { } }) - await server.loginCommand.login({ user: { username: 'fry', password: 'fry' }, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) + await server.login.login({ user: { username: 'fry', password: 'fry' }, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) it('Should not login with good LDAP settings but wrong username/password', async function () { - await server.pluginsCommand.updateSettings({ + await server.plugins.updateSettings({ npmName: 'peertube-plugin-auth-ldap', settings: { 'bind-credentials': 'GoodNewsEveryone', @@ -56,20 +56,20 @@ describe('Official plugin auth-ldap', function () { } }) - await server.loginCommand.login({ user: { username: 'fry', password: 'bad password' }, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) - await server.loginCommand.login({ user: { username: 'fryr', password: 'fry' }, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) + await server.login.login({ user: { username: 'fry', password: 'bad password' }, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) + await server.login.login({ user: { username: 'fryr', password: 'fry' }, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) it('Should login with the appropriate username/password', async function () { - accessToken = await server.loginCommand.getAccessToken({ username: 'fry', password: 'fry' }) + accessToken = await server.login.getAccessToken({ username: 'fry', password: 'fry' }) }) it('Should login with the appropriate email/password', async function () { - accessToken = await server.loginCommand.getAccessToken({ username: 'fry@planetexpress.com', password: 'fry' }) + accessToken = await server.login.getAccessToken({ username: 'fry@planetexpress.com', password: 'fry' }) }) it('Should login get my profile', async function () { - const body = await server.usersCommand.getMyInfo({ token: accessToken }) + const body = await server.users.getMyInfo({ token: accessToken }) expect(body.username).to.equal('fry') expect(body.email).to.equal('fry@planetexpress.com') @@ -77,28 +77,28 @@ describe('Official plugin auth-ldap', function () { }) it('Should upload a video', async function () { - await server.videosCommand.upload({ token: accessToken, attributes: { name: 'my super video' } }) + await server.videos.upload({ token: accessToken, attributes: { name: 'my super video' } }) }) it('Should not be able to login if the user is banned', async function () { - await server.usersCommand.banUser({ userId }) + await server.users.banUser({ userId }) - await server.loginCommand.login({ + await server.login.login({ user: { username: 'fry@planetexpress.com', password: 'fry' }, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) it('Should be able to login if the user is unbanned', async function () { - await server.usersCommand.unbanUser({ userId }) + await server.users.unbanUser({ userId }) - await server.loginCommand.login({ user: { username: 'fry@planetexpress.com', password: 'fry' } }) + await server.login.login({ user: { username: 'fry@planetexpress.com', password: 'fry' } }) }) it('Should not login if the plugin is uninstalled', async function () { - await server.pluginsCommand.uninstall({ npmName: 'peertube-plugin-auth-ldap' }) + await server.plugins.uninstall({ npmName: 'peertube-plugin-auth-ldap' }) - await server.loginCommand.login({ + await server.login.login({ user: { username: 'fry@planetexpress.com', password: 'fry' }, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) diff --git a/server/tests/external-plugins/auto-block-videos.ts b/server/tests/external-plugins/auto-block-videos.ts index 1cce15a2f..3b4b48bf0 100644 --- a/server/tests/external-plugins/auto-block-videos.ts +++ b/server/tests/external-plugins/auto-block-videos.ts @@ -16,7 +16,7 @@ import { import { Video } from '@shared/models' async function check (server: ServerInfo, videoUUID: string, exists = true) { - const { data } = await server.videosCommand.list() + const { data } = await server.videos.list() const video = data.find(v => v.uuid === videoUUID) @@ -38,24 +38,24 @@ describe('Official plugin auto-block videos', function () { await setAccessTokensToServers(servers) for (const server of servers) { - await server.pluginsCommand.install({ npmName: 'peertube-plugin-auto-block-videos' }) + await server.plugins.install({ npmName: 'peertube-plugin-auto-block-videos' }) } blocklistServer = new MockBlocklist() port = await blocklistServer.initialize() - await await servers[0].videosCommand.quickUpload({ name: 'video server 1' }) - await await servers[1].videosCommand.quickUpload({ name: 'video server 2' }) - await await servers[1].videosCommand.quickUpload({ name: 'video 2 server 2' }) - await await servers[1].videosCommand.quickUpload({ name: 'video 3 server 2' }) + await await servers[0].videos.quickUpload({ name: 'video server 1' }) + await await servers[1].videos.quickUpload({ name: 'video server 2' }) + await await servers[1].videos.quickUpload({ name: 'video 2 server 2' }) + await await servers[1].videos.quickUpload({ name: 'video 3 server 2' }) { - const { data } = await servers[0].videosCommand.list() + const { data } = await servers[0].videos.list() server1Videos = data.map(v => Object.assign(v, { url: servers[0].url + '/videos/watch/' + v.uuid })) } { - const { data } = await servers[1].videosCommand.list() + const { data } = await servers[1].videos.list() server2Videos = data.map(v => Object.assign(v, { url: servers[1].url + '/videos/watch/' + v.uuid })) } @@ -63,7 +63,7 @@ describe('Official plugin auto-block videos', function () { }) it('Should update plugin settings', async function () { - await servers[0].pluginsCommand.updateSettings({ + await servers[0].plugins.updateSettings({ npmName: 'peertube-plugin-auto-block-videos', settings: { 'blocklist-urls': `http://localhost:${port}/blocklist`, @@ -91,7 +91,7 @@ describe('Official plugin auto-block videos', function () { }) it('Should have video in blacklists', async function () { - const body = await servers[0].blacklistCommand.list() + const body = await servers[0].blacklist.list() const videoBlacklists = body.data expect(videoBlacklists).to.have.lengthOf(1) @@ -156,7 +156,7 @@ describe('Official plugin auto-block videos', function () { await check(servers[0], video.uuid, false) - await servers[0].blacklistCommand.remove({ videoId: video.uuid }) + await servers[0].blacklist.remove({ videoId: video.uuid }) await check(servers[0], video.uuid, true) diff --git a/server/tests/external-plugins/auto-mute.ts b/server/tests/external-plugins/auto-mute.ts index 81a96744e..25b56a546 100644 --- a/server/tests/external-plugins/auto-mute.ts +++ b/server/tests/external-plugins/auto-mute.ts @@ -29,20 +29,20 @@ describe('Official plugin auto-mute', function () { await setAccessTokensToServers(servers) for (const server of servers) { - await server.pluginsCommand.install({ npmName: 'peertube-plugin-auto-mute' }) + await server.plugins.install({ npmName: 'peertube-plugin-auto-mute' }) } blocklistServer = new MockBlocklist() port = await blocklistServer.initialize() - await await servers[0].videosCommand.quickUpload({ name: 'video server 1' }) - await await servers[1].videosCommand.quickUpload({ name: 'video server 2' }) + await await servers[0].videos.quickUpload({ name: 'video server 1' }) + await await servers[1].videos.quickUpload({ name: 'video server 2' }) await doubleFollow(servers[0], servers[1]) }) it('Should update plugin settings', async function () { - await servers[0].pluginsCommand.updateSettings({ + await servers[0].plugins.updateSettings({ npmName: 'peertube-plugin-auto-mute', settings: { 'blocklist-urls': `http://localhost:${port}/blocklist`, @@ -64,7 +64,7 @@ describe('Official plugin auto-mute', function () { await wait(2000) - const { total } = await servers[0].videosCommand.list() + const { total } = await servers[0].videos.list() expect(total).to.equal(1) }) @@ -82,7 +82,7 @@ describe('Official plugin auto-mute', function () { await wait(2000) - const { total } = await servers[0].videosCommand.list() + const { total } = await servers[0].videos.list() expect(total).to.equal(2) }) @@ -99,7 +99,7 @@ describe('Official plugin auto-mute', function () { await wait(2000) - const { total } = await servers[0].videosCommand.list() + const { total } = await servers[0].videos.list() expect(total).to.equal(1) }) @@ -117,7 +117,7 @@ describe('Official plugin auto-mute', function () { await wait(2000) - const { total } = await servers[0].videosCommand.list() + const { total } = await servers[0].videos.list() expect(total).to.equal(2) }) @@ -138,14 +138,14 @@ describe('Official plugin auto-mute', function () { await wait(2000) { - const { total } = await servers[0].videosCommand.list() + const { total } = await servers[0].videos.list() expect(total).to.equal(1) } - await servers[0].blocklistCommand.removeFromServerBlocklist({ account }) + await servers[0].blocklist.removeFromServerBlocklist({ account }) { - const { total } = await servers[0].videosCommand.list() + const { total } = await servers[0].videos.list() expect(total).to.equal(2) } @@ -154,7 +154,7 @@ describe('Official plugin auto-mute', function () { await wait(2000) { - const { total } = await servers[0].videosCommand.list() + const { total } = await servers[0].videos.list() expect(total).to.equal(2) } }) @@ -168,7 +168,7 @@ describe('Official plugin auto-mute', function () { }) it('Should enable auto mute list', async function () { - await servers[0].pluginsCommand.updateSettings({ + await servers[0].plugins.updateSettings({ npmName: 'peertube-plugin-auto-mute', settings: { 'blocklist-urls': '', @@ -187,7 +187,7 @@ describe('Official plugin auto-mute', function () { it('Should mute an account on server 1, and server 2 auto mutes it', async function () { this.timeout(20000) - await servers[1].pluginsCommand.updateSettings({ + await servers[1].plugins.updateSettings({ npmName: 'peertube-plugin-auto-mute', settings: { 'blocklist-urls': 'http://localhost:' + servers[0].port + autoMuteListPath, @@ -196,8 +196,8 @@ describe('Official plugin auto-mute', function () { } }) - await servers[0].blocklistCommand.addToServerBlocklist({ account: 'root@localhost:' + servers[1].port }) - await servers[0].blocklistCommand.addToMyBlocklist({ server: 'localhost:' + servers[1].port }) + await servers[0].blocklist.addToServerBlocklist({ account: 'root@localhost:' + servers[1].port }) + await servers[0].blocklist.addToMyBlocklist({ server: 'localhost:' + servers[1].port }) const res = await makeGetRequest({ url: servers[0].url, @@ -213,7 +213,7 @@ describe('Official plugin auto-mute', function () { await wait(2000) for (const server of servers) { - const { total } = await server.videosCommand.list() + const { total } = await server.videos.list() expect(total).to.equal(1) } }) diff --git a/server/tests/feeds/feeds.ts b/server/tests/feeds/feeds.ts index c66cdde1b..8bdafc644 100644 --- a/server/tests/feeds/feeds.ts +++ b/server/tests/feeds/feeds.ts @@ -47,26 +47,26 @@ describe('Test syndication feeds', () => { await doubleFollow(servers[0], servers[1]) { - const user = await servers[0].usersCommand.getMyInfo() + const user = await servers[0].users.getMyInfo() rootAccountId = user.account.id rootChannelId = user.videoChannels[0].id } { const attr = { username: 'john', password: 'password' } - await servers[0].usersCommand.create({ username: attr.username, password: attr.password }) - userAccessToken = await servers[0].loginCommand.getAccessToken(attr) + await servers[0].users.create({ username: attr.username, password: attr.password }) + userAccessToken = await servers[0].login.getAccessToken(attr) - const user = await servers[0].usersCommand.getMyInfo({ token: userAccessToken }) + const user = await servers[0].users.getMyInfo({ token: userAccessToken }) userAccountId = user.account.id userChannelId = user.videoChannels[0].id - const token = await servers[0].usersCommand.getMyScopedTokens({ token: userAccessToken }) + const token = await servers[0].users.getMyScopedTokens({ token: userAccessToken }) userFeedToken = token.feedToken } { - await servers[0].videosCommand.upload({ token: userAccessToken, attributes: { name: 'user video' } }) + await servers[0].videos.upload({ token: userAccessToken, attributes: { name: 'user video' } }) } { @@ -75,17 +75,17 @@ describe('Test syndication feeds', () => { description: 'my super description for server 1', fixture: 'video_short.webm' } - const { id } = await servers[0].videosCommand.upload({ attributes }) + const { id } = await servers[0].videos.upload({ attributes }) - await servers[0].commentsCommand.createThread({ videoId: id, text: 'super comment 1' }) - await servers[0].commentsCommand.createThread({ videoId: id, text: 'super comment 2' }) + await servers[0].comments.createThread({ videoId: id, text: 'super comment 1' }) + await servers[0].comments.createThread({ videoId: id, text: 'super comment 2' }) } { const attributes = { name: 'unlisted video', privacy: VideoPrivacy.UNLISTED } - const { id } = await servers[0].videosCommand.upload({ attributes }) + const { id } = await servers[0].videos.upload({ attributes }) - await servers[0].commentsCommand.createThread({ videoId: id, text: 'comment on unlisted video' }) + await servers[0].comments.createThread({ videoId: id, text: 'comment on unlisted video' }) } await waitJobs(servers) @@ -95,17 +95,17 @@ describe('Test syndication feeds', () => { it('Should be well formed XML (covers RSS 2.0 and ATOM 1.0 endpoints)', async function () { for (const feed of [ 'video-comments' as 'video-comments', 'videos' as 'videos' ]) { - const rss = await servers[0].feedCommand.getXML({ feed }) + const rss = await servers[0].feed.getXML({ feed }) expect(rss).xml.to.be.valid() - const atom = await servers[0].feedCommand.getXML({ feed, format: 'atom' }) + const atom = await servers[0].feed.getXML({ feed, format: 'atom' }) expect(atom).xml.to.be.valid() } }) it('Should be well formed JSON (covers JSON feed 1.0 endpoint)', async function () { for (const feed of [ 'video-comments' as 'video-comments', 'videos' as 'videos' ]) { - const jsonText = await servers[0].feedCommand.getJSON({ feed }) + const jsonText = await servers[0].feed.getJSON({ feed }) expect(JSON.parse(jsonText)).to.be.jsonSchema({ type: 'object' }) } }) @@ -115,7 +115,7 @@ describe('Test syndication feeds', () => { it('Should contain a valid enclosure (covers RSS 2.0 endpoint)', async function () { for (const server of servers) { - const rss = await server.feedCommand.getXML({ feed: 'videos' }) + const rss = await server.feed.getXML({ feed: 'videos' }) expect(xmlParser.validate(rss)).to.be.true const xmlDoc = xmlParser.parse(rss, { parseAttributeValue: true, ignoreAttributes: false }) @@ -130,7 +130,7 @@ describe('Test syndication feeds', () => { it('Should contain a valid \'attachments\' object (covers JSON feed 1.0 endpoint)', async function () { for (const server of servers) { - const json = await server.feedCommand.getJSON({ feed: 'videos' }) + const json = await server.feed.getJSON({ feed: 'videos' }) const jsonObj = JSON.parse(json) expect(jsonObj.items.length).to.be.equal(2) expect(jsonObj.items[0].attachments).to.exist @@ -143,7 +143,7 @@ describe('Test syndication feeds', () => { it('Should filter by account', async function () { { - const json = await servers[0].feedCommand.getJSON({ feed: 'videos', query: { accountId: rootAccountId } }) + const json = await servers[0].feed.getJSON({ feed: 'videos', query: { accountId: rootAccountId } }) const jsonObj = JSON.parse(json) expect(jsonObj.items.length).to.be.equal(1) expect(jsonObj.items[0].title).to.equal('my super name for server 1') @@ -151,7 +151,7 @@ describe('Test syndication feeds', () => { } { - const json = await servers[0].feedCommand.getJSON({ feed: 'videos', query: { accountId: userAccountId } }) + const json = await servers[0].feed.getJSON({ feed: 'videos', query: { accountId: userAccountId } }) const jsonObj = JSON.parse(json) expect(jsonObj.items.length).to.be.equal(1) expect(jsonObj.items[0].title).to.equal('user video') @@ -160,14 +160,14 @@ describe('Test syndication feeds', () => { for (const server of servers) { { - const json = await server.feedCommand.getJSON({ feed: 'videos', query: { accountName: 'root@localhost:' + servers[0].port } }) + const json = await server.feed.getJSON({ feed: 'videos', query: { accountName: 'root@localhost:' + servers[0].port } }) const jsonObj = JSON.parse(json) expect(jsonObj.items.length).to.be.equal(1) expect(jsonObj.items[0].title).to.equal('my super name for server 1') } { - const json = await server.feedCommand.getJSON({ feed: 'videos', query: { accountName: 'john@localhost:' + servers[0].port } }) + const json = await server.feed.getJSON({ feed: 'videos', query: { accountName: 'john@localhost:' + servers[0].port } }) const jsonObj = JSON.parse(json) expect(jsonObj.items.length).to.be.equal(1) expect(jsonObj.items[0].title).to.equal('user video') @@ -177,7 +177,7 @@ describe('Test syndication feeds', () => { it('Should filter by video channel', async function () { { - const json = await servers[0].feedCommand.getJSON({ feed: 'videos', query: { videoChannelId: rootChannelId } }) + const json = await servers[0].feed.getJSON({ feed: 'videos', query: { videoChannelId: rootChannelId } }) const jsonObj = JSON.parse(json) expect(jsonObj.items.length).to.be.equal(1) expect(jsonObj.items[0].title).to.equal('my super name for server 1') @@ -185,7 +185,7 @@ describe('Test syndication feeds', () => { } { - const json = await servers[0].feedCommand.getJSON({ feed: 'videos', query: { videoChannelId: userChannelId } }) + const json = await servers[0].feed.getJSON({ feed: 'videos', query: { videoChannelId: userChannelId } }) const jsonObj = JSON.parse(json) expect(jsonObj.items.length).to.be.equal(1) expect(jsonObj.items[0].title).to.equal('user video') @@ -195,7 +195,7 @@ describe('Test syndication feeds', () => { for (const server of servers) { { const query = { videoChannelName: 'root_channel@localhost:' + servers[0].port } - const json = await server.feedCommand.getJSON({ feed: 'videos', query }) + const json = await server.feed.getJSON({ feed: 'videos', query }) const jsonObj = JSON.parse(json) expect(jsonObj.items.length).to.be.equal(1) expect(jsonObj.items[0].title).to.equal('my super name for server 1') @@ -203,7 +203,7 @@ describe('Test syndication feeds', () => { { const query = { videoChannelName: 'john_channel@localhost:' + servers[0].port } - const json = await server.feedCommand.getJSON({ feed: 'videos', query }) + const json = await server.feed.getJSON({ feed: 'videos', query }) const jsonObj = JSON.parse(json) expect(jsonObj.items.length).to.be.equal(1) expect(jsonObj.items[0].title).to.equal('user video') @@ -214,11 +214,11 @@ describe('Test syndication feeds', () => { it('Should correctly have videos feed with HLS only', async function () { this.timeout(120000) - await serverHLSOnly.videosCommand.upload({ attributes: { name: 'hls only video' } }) + await serverHLSOnly.videos.upload({ attributes: { name: 'hls only video' } }) await waitJobs([ serverHLSOnly ]) - const json = await serverHLSOnly.feedCommand.getJSON({ feed: 'videos' }) + const json = await serverHLSOnly.feed.getJSON({ feed: 'videos' }) const jsonObj = JSON.parse(json) expect(jsonObj.items.length).to.be.equal(1) expect(jsonObj.items[0].attachments).to.exist @@ -236,7 +236,7 @@ describe('Test syndication feeds', () => { it('Should contain valid comments (covers JSON feed 1.0 endpoint) and not from unlisted videos', async function () { for (const server of servers) { - const json = await server.feedCommand.getJSON({ feed: 'video-comments' }) + const json = await server.feed.getJSON({ feed: 'video-comments' }) const jsonObj = JSON.parse(json) expect(jsonObj.items.length).to.be.equal(2) @@ -250,31 +250,31 @@ describe('Test syndication feeds', () => { const remoteHandle = 'root@localhost:' + servers[0].port - await servers[1].blocklistCommand.addToServerBlocklist({ account: remoteHandle }) + await servers[1].blocklist.addToServerBlocklist({ account: remoteHandle }) { - const json = await servers[1].feedCommand.getJSON({ feed: 'video-comments', query: { version: 2 } }) + const json = await servers[1].feed.getJSON({ feed: 'video-comments', query: { version: 2 } }) const jsonObj = JSON.parse(json) expect(jsonObj.items.length).to.be.equal(0) } - await servers[1].blocklistCommand.removeFromServerBlocklist({ account: remoteHandle }) + await servers[1].blocklist.removeFromServerBlocklist({ account: remoteHandle }) { - const videoUUID = (await servers[1].videosCommand.quickUpload({ name: 'server 2' })).uuid + const videoUUID = (await servers[1].videos.quickUpload({ name: 'server 2' })).uuid await waitJobs(servers) - await servers[0].commentsCommand.createThread({ videoId: videoUUID, text: 'super comment' }) + await servers[0].comments.createThread({ videoId: videoUUID, text: 'super comment' }) await waitJobs(servers) - const json = await servers[1].feedCommand.getJSON({ feed: 'video-comments', query: { version: 3 } }) + const json = await servers[1].feed.getJSON({ feed: 'video-comments', query: { version: 3 } }) const jsonObj = JSON.parse(json) expect(jsonObj.items.length).to.be.equal(3) } - await servers[1].blocklistCommand.addToMyBlocklist({ account: remoteHandle }) + await servers[1].blocklist.addToMyBlocklist({ account: remoteHandle }) { - const json = await servers[1].feedCommand.getJSON({ feed: 'video-comments', query: { version: 4 } }) + const json = await servers[1].feed.getJSON({ feed: 'video-comments', query: { version: 4 } }) const jsonObj = JSON.parse(json) expect(jsonObj.items.length).to.be.equal(2) } @@ -287,25 +287,25 @@ describe('Test syndication feeds', () => { it('Should list no videos for a user with no videos and no subscriptions', async function () { const attr = { username: 'feeduser', password: 'password' } - await servers[0].usersCommand.create({ username: attr.username, password: attr.password }) - const feeduserAccessToken = await servers[0].loginCommand.getAccessToken(attr) + await servers[0].users.create({ username: attr.username, password: attr.password }) + const feeduserAccessToken = await servers[0].login.getAccessToken(attr) { - const user = await servers[0].usersCommand.getMyInfo({ token: feeduserAccessToken }) + const user = await servers[0].users.getMyInfo({ token: feeduserAccessToken }) feeduserAccountId = user.account.id } { - const token = await servers[0].usersCommand.getMyScopedTokens({ token: feeduserAccessToken }) + const token = await servers[0].users.getMyScopedTokens({ token: feeduserAccessToken }) feeduserFeedToken = token.feedToken } { - const body = await servers[0].subscriptionsCommand.listVideos({ token: feeduserAccessToken }) + const body = await servers[0].subscriptions.listVideos({ token: feeduserAccessToken }) expect(body.total).to.equal(0) const query = { accountId: feeduserAccountId, token: feeduserFeedToken } - const json = await servers[0].feedCommand.getJSON({ feed: 'subscriptions', query }) + const json = await servers[0].feed.getJSON({ feed: 'subscriptions', query }) const jsonObj = JSON.parse(json) expect(jsonObj.items.length).to.be.equal(0) // no subscription, it should not list the instance's videos but list 0 videos } @@ -313,20 +313,20 @@ describe('Test syndication feeds', () => { it('Should fail with an invalid token', async function () { const query = { accountId: feeduserAccountId, token: 'toto' } - await servers[0].feedCommand.getJSON({ feed: 'subscriptions', query, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) + await servers[0].feed.getJSON({ feed: 'subscriptions', query, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) it('Should fail with a token of another user', async function () { const query = { accountId: feeduserAccountId, token: userFeedToken } - await servers[0].feedCommand.getJSON({ feed: 'subscriptions', query, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) + await servers[0].feed.getJSON({ feed: 'subscriptions', query, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) it('Should list no videos for a user with videos but no subscriptions', async function () { - const body = await servers[0].subscriptionsCommand.listVideos({ token: userAccessToken }) + const body = await servers[0].subscriptions.listVideos({ token: userAccessToken }) expect(body.total).to.equal(0) const query = { accountId: userAccountId, token: userFeedToken } - const json = await servers[0].feedCommand.getJSON({ feed: 'subscriptions', query }) + const json = await servers[0].feed.getJSON({ feed: 'subscriptions', query }) const jsonObj = JSON.parse(json) expect(jsonObj.items.length).to.be.equal(0) // no subscription, it should not list the instance's videos but list 0 videos }) @@ -334,16 +334,16 @@ describe('Test syndication feeds', () => { it('Should list self videos for a user with a subscription to themselves', async function () { this.timeout(30000) - await servers[0].subscriptionsCommand.add({ token: userAccessToken, targetUri: 'john_channel@localhost:' + servers[0].port }) + await servers[0].subscriptions.add({ token: userAccessToken, targetUri: 'john_channel@localhost:' + servers[0].port }) await waitJobs(servers) { - const body = await servers[0].subscriptionsCommand.listVideos({ token: userAccessToken }) + const body = await servers[0].subscriptions.listVideos({ token: userAccessToken }) expect(body.total).to.equal(1) expect(body.data[0].name).to.equal('user video') const query = { accountId: userAccountId, token: userFeedToken, version: 1 } - const json = await servers[0].feedCommand.getJSON({ feed: 'subscriptions', query }) + const json = await servers[0].feed.getJSON({ feed: 'subscriptions', query }) const jsonObj = JSON.parse(json) expect(jsonObj.items.length).to.be.equal(1) // subscribed to self, it should not list the instance's videos but list john's } @@ -352,33 +352,33 @@ describe('Test syndication feeds', () => { it('Should list videos of a user\'s subscription', async function () { this.timeout(30000) - await servers[0].subscriptionsCommand.add({ token: userAccessToken, targetUri: 'root_channel@localhost:' + servers[0].port }) + await servers[0].subscriptions.add({ token: userAccessToken, targetUri: 'root_channel@localhost:' + servers[0].port }) await waitJobs(servers) { - const body = await servers[0].subscriptionsCommand.listVideos({ token: userAccessToken }) + const body = await servers[0].subscriptions.listVideos({ token: userAccessToken }) expect(body.total).to.equal(2, "there should be 2 videos part of the subscription") const query = { accountId: userAccountId, token: userFeedToken, version: 2 } - const json = await servers[0].feedCommand.getJSON({ feed: 'subscriptions', query }) + const json = await servers[0].feed.getJSON({ feed: 'subscriptions', query }) const jsonObj = JSON.parse(json) expect(jsonObj.items.length).to.be.equal(2) // subscribed to root, it should not list the instance's videos but list root/john's } }) it('Should renew the token, and so have an invalid old token', async function () { - await servers[0].usersCommand.renewMyScopedTokens({ token: userAccessToken }) + await servers[0].users.renewMyScopedTokens({ token: userAccessToken }) const query = { accountId: userAccountId, token: userFeedToken, version: 3 } - await servers[0].feedCommand.getJSON({ feed: 'subscriptions', query, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) + await servers[0].feed.getJSON({ feed: 'subscriptions', query, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) it('Should succeed with the new token', async function () { - const token = await servers[0].usersCommand.getMyScopedTokens({ token: userAccessToken }) + const token = await servers[0].users.getMyScopedTokens({ token: userAccessToken }) userFeedToken = token.feedToken const query = { accountId: userAccountId, token: userFeedToken, version: 4 } - await servers[0].feedCommand.getJSON({ feed: 'subscriptions', query }) + await servers[0].feed.getJSON({ feed: 'subscriptions', query }) }) }) diff --git a/server/tests/misc-endpoints.ts b/server/tests/misc-endpoints.ts index b5b10bd5e..f7c9e6c26 100644 --- a/server/tests/misc-endpoints.ts +++ b/server/tests/misc-endpoints.ts @@ -158,15 +158,15 @@ describe('Test misc endpoints', function () { it('Should add videos, channel and accounts and get sitemap', async function () { this.timeout(35000) - await server.videosCommand.upload({ attributes: { name: 'video 1', nsfw: false } }) - await server.videosCommand.upload({ attributes: { name: 'video 2', nsfw: false } }) - await server.videosCommand.upload({ attributes: { name: 'video 3', privacy: VideoPrivacy.PRIVATE } }) + await server.videos.upload({ attributes: { name: 'video 1', nsfw: false } }) + await server.videos.upload({ attributes: { name: 'video 2', nsfw: false } }) + await server.videos.upload({ attributes: { name: 'video 3', privacy: VideoPrivacy.PRIVATE } }) - await server.channelsCommand.create({ attributes: { name: 'channel1', displayName: 'channel 1' } }) - await server.channelsCommand.create({ attributes: { name: 'channel2', displayName: 'channel 2' } }) + await server.channels.create({ attributes: { name: 'channel1', displayName: 'channel 1' } }) + await server.channels.create({ attributes: { name: 'channel2', displayName: 'channel 2' } }) - await server.usersCommand.create({ username: 'user1', password: 'password' }) - await server.usersCommand.create({ username: 'user2', password: 'password' }) + await server.users.create({ username: 'user1', password: 'password' }) + await server.users.create({ username: 'user2', password: 'password' }) const res = await makeGetRequest({ url: server.url, diff --git a/server/tests/plugins/action-hooks.ts b/server/tests/plugins/action-hooks.ts index 9e12c8aa7..12d5c23c5 100644 --- a/server/tests/plugins/action-hooks.ts +++ b/server/tests/plugins/action-hooks.ts @@ -19,7 +19,7 @@ describe('Test plugin action hooks', function () { let threadId: number function checkHook (hook: ServerHookName) { - return servers[0].serversCommand.waitUntilLog('Run hook ' + hook) + return servers[0].servers.waitUntilLog('Run hook ' + hook) } before(async function () { @@ -29,7 +29,7 @@ describe('Test plugin action hooks', function () { await setAccessTokensToServers(servers) await setDefaultVideoChannel(servers) - await servers[0].pluginsCommand.install({ path: PluginsCommand.getPluginTestPath() }) + await servers[0].plugins.install({ path: PluginsCommand.getPluginTestPath() }) await killallServers([ servers[0] ]) @@ -49,20 +49,20 @@ describe('Test plugin action hooks', function () { describe('Videos hooks', function () { it('Should run action:api.video.uploaded', async function () { - const { uuid } = await servers[0].videosCommand.upload({ attributes: { name: 'video' } }) + const { uuid } = await servers[0].videos.upload({ attributes: { name: 'video' } }) videoUUID = uuid await checkHook('action:api.video.uploaded') }) it('Should run action:api.video.updated', async function () { - await servers[0].videosCommand.update({ id: videoUUID, attributes: { name: 'video updated' } }) + await servers[0].videos.update({ id: videoUUID, attributes: { name: 'video updated' } }) await checkHook('action:api.video.updated') }) it('Should run action:api.video.viewed', async function () { - await servers[0].videosCommand.view({ id: videoUUID }) + await servers[0].videos.view({ id: videoUUID }) await checkHook('action:api.video.viewed') }) @@ -74,10 +74,10 @@ describe('Test plugin action hooks', function () { const attributes = { name: 'live', privacy: VideoPrivacy.PUBLIC, - channelId: servers[0].videoChannel.id + channelId: servers[0].store.channel.id } - await servers[0].liveCommand.create({ fields: attributes }) + await servers[0].live.create({ fields: attributes }) await checkHook('action:api.live-video.created') }) @@ -85,20 +85,20 @@ describe('Test plugin action hooks', function () { describe('Comments hooks', function () { it('Should run action:api.video-thread.created', async function () { - const created = await servers[0].commentsCommand.createThread({ videoId: videoUUID, text: 'thread' }) + const created = await servers[0].comments.createThread({ videoId: videoUUID, text: 'thread' }) threadId = created.id await checkHook('action:api.video-thread.created') }) it('Should run action:api.video-comment-reply.created', async function () { - await servers[0].commentsCommand.addReply({ videoId: videoUUID, toCommentId: threadId, text: 'reply' }) + await servers[0].comments.addReply({ videoId: videoUUID, toCommentId: threadId, text: 'reply' }) await checkHook('action:api.video-comment-reply.created') }) it('Should run action:api.video-comment.deleted', async function () { - await servers[0].commentsCommand.delete({ videoId: videoUUID, commentId: threadId }) + await servers[0].comments.delete({ videoId: videoUUID, commentId: threadId }) await checkHook('action:api.video-comment.deleted') }) @@ -108,44 +108,44 @@ describe('Test plugin action hooks', function () { let userId: number it('Should run action:api.user.registered', async function () { - await servers[0].usersCommand.register({ username: 'registered_user' }) + await servers[0].users.register({ username: 'registered_user' }) await checkHook('action:api.user.registered') }) it('Should run action:api.user.created', async function () { - const user = await servers[0].usersCommand.create({ username: 'created_user' }) + const user = await servers[0].users.create({ username: 'created_user' }) userId = user.id await checkHook('action:api.user.created') }) it('Should run action:api.user.oauth2-got-token', async function () { - await servers[0].loginCommand.getAccessToken('created_user', 'super_password') + await servers[0].login.getAccessToken('created_user', 'super_password') await checkHook('action:api.user.oauth2-got-token') }) it('Should run action:api.user.blocked', async function () { - await servers[0].usersCommand.banUser({ userId }) + await servers[0].users.banUser({ userId }) await checkHook('action:api.user.blocked') }) it('Should run action:api.user.unblocked', async function () { - await servers[0].usersCommand.unbanUser({ userId }) + await servers[0].users.unbanUser({ userId }) await checkHook('action:api.user.unblocked') }) it('Should run action:api.user.updated', async function () { - await servers[0].usersCommand.update({ userId, videoQuota: 50 }) + await servers[0].users.update({ userId, videoQuota: 50 }) await checkHook('action:api.user.updated') }) it('Should run action:api.user.deleted', async function () { - await servers[0].usersCommand.remove({ userId }) + await servers[0].users.remove({ userId }) await checkHook('action:api.user.deleted') }) @@ -157,7 +157,7 @@ describe('Test plugin action hooks', function () { before(async function () { { - const { id } = await servers[0].playlistsCommand.create({ + const { id } = await servers[0].playlists.create({ attributes: { displayName: 'My playlist', privacy: VideoPlaylistPrivacy.PRIVATE @@ -167,13 +167,13 @@ describe('Test plugin action hooks', function () { } { - const { id } = await servers[0].videosCommand.upload({ attributes: { name: 'my super name' } }) + const { id } = await servers[0].videos.upload({ attributes: { name: 'my super name' } }) videoId = id } }) it('Should run action:api.video-playlist-element.created', async function () { - await servers[0].playlistsCommand.addElement({ playlistId, attributes: { videoId } }) + await servers[0].playlists.addElement({ playlistId, attributes: { videoId } }) await checkHook('action:api.video-playlist-element.created') }) diff --git a/server/tests/plugins/external-auth.ts b/server/tests/plugins/external-auth.ts index 3e8305611..48f942f7f 100644 --- a/server/tests/plugins/external-auth.ts +++ b/server/tests/plugins/external-auth.ts @@ -23,7 +23,7 @@ async function loginExternal (options: { statusCodeExpected?: HttpStatusCode statusCodeExpectedStep2?: HttpStatusCode }) { - const res = await options.server.pluginsCommand.getExternalAuth({ + const res = await options.server.plugins.getExternalAuth({ npmName: options.npmName, npmVersion: '0.0.1', authName: options.authName, @@ -36,7 +36,7 @@ async function loginExternal (options: { const location = res.header.location const { externalAuthToken } = decodeQueryString(location) - const resLogin = await options.server.loginCommand.loginUsingExternalToken({ + const resLogin = await options.server.login.loginUsingExternalToken({ username: options.username, externalAuthToken: externalAuthToken as string, expectedStatus: options.statusCodeExpectedStep2 @@ -63,12 +63,12 @@ describe('Test external auth plugins', function () { await setAccessTokensToServers([ server ]) for (const suffix of [ 'one', 'two', 'three' ]) { - await server.pluginsCommand.install({ path: PluginsCommand.getPluginTestPath('-external-auth-' + suffix) }) + await server.plugins.install({ path: PluginsCommand.getPluginTestPath('-external-auth-' + suffix) }) } }) it('Should display the correct configuration', async function () { - const config = await server.configCommand.getConfig() + const config = await server.config.getConfig() const auths = config.plugin.registeredExternalAuths expect(auths).to.have.lengthOf(8) @@ -80,7 +80,7 @@ describe('Test external auth plugins', function () { }) it('Should redirect for a Cyan login', async function () { - const res = await server.pluginsCommand.getExternalAuth({ + const res = await server.plugins.getExternalAuth({ npmName: 'test-external-auth-one', npmVersion: '0.0.1', authName: 'external-auth-1', @@ -102,14 +102,14 @@ describe('Test external auth plugins', function () { }) it('Should reject auto external login with a missing or invalid token', async function () { - const command = server.loginCommand + const command = server.login await command.loginUsingExternalToken({ username: 'cyan', externalAuthToken: '', expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) await command.loginUsingExternalToken({ username: 'cyan', externalAuthToken: 'blabla', expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) it('Should reject auto external login with a missing or invalid username', async function () { - const command = server.loginCommand + const command = server.login await command.loginUsingExternalToken({ username: '', externalAuthToken, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) await command.loginUsingExternalToken({ username: '', externalAuthToken, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) @@ -120,13 +120,13 @@ describe('Test external auth plugins', function () { await wait(5000) - await server.loginCommand.loginUsingExternalToken({ + await server.login.loginUsingExternalToken({ username: 'cyan', externalAuthToken, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) - await server.serversCommand.waitUntilLog('expired external auth token', 2) + await server.servers.waitUntilLog('expired external auth token', 2) }) it('Should auto login Cyan, create the user and use the token', async function () { @@ -146,7 +146,7 @@ describe('Test external auth plugins', function () { } { - const body = await server.usersCommand.getMyInfo({ token: cyanAccessToken }) + const body = await server.users.getMyInfo({ token: cyanAccessToken }) expect(body.username).to.equal('cyan') expect(body.account.displayName).to.equal('cyan') expect(body.email).to.equal('cyan@example.com') @@ -168,7 +168,7 @@ describe('Test external auth plugins', function () { } { - const body = await server.usersCommand.getMyInfo({ token: kefkaAccessToken }) + const body = await server.users.getMyInfo({ token: kefkaAccessToken }) expect(body.username).to.equal('kefka') expect(body.account.displayName).to.equal('Kefka Palazzo') expect(body.email).to.equal('kefka@example.com') @@ -178,39 +178,39 @@ describe('Test external auth plugins', function () { it('Should refresh Cyan token, but not Kefka token', async function () { { - const resRefresh = await server.loginCommand.refreshToken({ refreshToken: cyanRefreshToken }) + const resRefresh = await server.login.refreshToken({ refreshToken: cyanRefreshToken }) cyanAccessToken = resRefresh.body.access_token cyanRefreshToken = resRefresh.body.refresh_token - const body = await server.usersCommand.getMyInfo({ token: cyanAccessToken }) + const body = await server.users.getMyInfo({ token: cyanAccessToken }) expect(body.username).to.equal('cyan') } { - await server.loginCommand.refreshToken({ refreshToken: kefkaRefreshToken, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) + await server.login.refreshToken({ refreshToken: kefkaRefreshToken, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) } }) it('Should update Cyan profile', async function () { - await server.usersCommand.updateMe({ + await server.users.updateMe({ token: cyanAccessToken, displayName: 'Cyan Garamonde', description: 'Retainer to the king of Doma' }) - const body = await server.usersCommand.getMyInfo({ token: cyanAccessToken }) + const body = await server.users.getMyInfo({ token: cyanAccessToken }) expect(body.account.displayName).to.equal('Cyan Garamonde') expect(body.account.description).to.equal('Retainer to the king of Doma') }) it('Should logout Cyan', async function () { - await server.loginCommand.logout({ token: cyanAccessToken }) + await server.login.logout({ token: cyanAccessToken }) }) it('Should have logged out Cyan', async function () { - await server.serversCommand.waitUntilLog('On logout cyan') + await server.servers.waitUntilLog('On logout cyan') - await server.usersCommand.getMyInfo({ token: cyanAccessToken, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) + await server.users.getMyInfo({ token: cyanAccessToken, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should login Cyan and keep the old existing profile', async function () { @@ -228,7 +228,7 @@ describe('Test external auth plugins', function () { cyanAccessToken = res.access_token } - const body = await server.usersCommand.getMyInfo({ token: cyanAccessToken }) + const body = await server.users.getMyInfo({ token: cyanAccessToken }) expect(body.username).to.equal('cyan') expect(body.account.displayName).to.equal('Cyan Garamonde') expect(body.account.description).to.equal('Retainer to the king of Doma') @@ -236,7 +236,7 @@ describe('Test external auth plugins', function () { }) it('Should not update an external auth email', async function () { - await server.usersCommand.updateMe({ + await server.users.updateMe({ token: cyanAccessToken, email: 'toto@example.com', currentPassword: 'toto', @@ -249,16 +249,16 @@ describe('Test external auth plugins', function () { await wait(5000) - await server.usersCommand.getMyInfo({ token: kefkaAccessToken, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) + await server.users.getMyInfo({ token: kefkaAccessToken, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should unregister external-auth-2 and do not login existing Kefka', async function () { - await server.pluginsCommand.updateSettings({ + await server.plugins.updateSettings({ npmName: 'peertube-plugin-test-external-auth-one', settings: { disableKefka: true } }) - await server.loginCommand.login({ user: { username: 'kefka', password: 'fake' }, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) + await server.login.login({ user: { username: 'kefka', password: 'fake' }, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) await loginExternal({ server, @@ -273,7 +273,7 @@ describe('Test external auth plugins', function () { }) it('Should have disabled this auth', async function () { - const config = await server.configCommand.getConfig() + const config = await server.config.getConfig() const auths = config.plugin.registeredExternalAuths expect(auths).to.have.lengthOf(7) @@ -283,7 +283,7 @@ describe('Test external auth plugins', function () { }) it('Should uninstall the plugin one and do not login Cyan', async function () { - await server.pluginsCommand.uninstall({ npmName: 'peertube-plugin-test-external-auth-one' }) + await server.plugins.uninstall({ npmName: 'peertube-plugin-test-external-auth-one' }) await loginExternal({ server, @@ -296,9 +296,9 @@ describe('Test external auth plugins', function () { statusCodeExpected: HttpStatusCode.NOT_FOUND_404 }) - await server.loginCommand.login({ user: { username: 'cyan', password: null }, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) - await server.loginCommand.login({ user: { username: 'cyan', password: '' }, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) - await server.loginCommand.login({ user: { username: 'cyan', password: 'fake' }, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) + await server.login.login({ user: { username: 'cyan', password: null }, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) + await server.login.login({ user: { username: 'cyan', password: '' }, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) + await server.login.login({ user: { username: 'cyan', password: 'fake' }, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) it('Should not login kefka with another plugin', async function () { @@ -320,7 +320,7 @@ describe('Test external auth plugins', function () { }) it('Should not login an existing user', async function () { - await server.usersCommand.create({ username: 'existing_user', password: 'super_password' }) + await server.users.create({ username: 'existing_user', password: 'super_password' }) await loginExternal({ server, @@ -332,7 +332,7 @@ describe('Test external auth plugins', function () { }) it('Should display the correct configuration', async function () { - const config = await server.configCommand.getConfig() + const config = await server.config.getConfig() const auths = config.plugin.registeredExternalAuths expect(auths).to.have.lengthOf(6) @@ -353,7 +353,7 @@ describe('Test external auth plugins', function () { username: 'cid' }) - const { redirectUrl } = await server.loginCommand.logout({ token: resLogin.access_token }) + const { redirectUrl } = await server.login.logout({ token: resLogin.access_token }) expect(redirectUrl).to.equal('https://example.com/redirectUrl') }) @@ -365,7 +365,7 @@ describe('Test external auth plugins', function () { username: 'cid' }) - const { redirectUrl } = await server.loginCommand.logout({ token: resLogin.access_token }) + const { redirectUrl } = await server.login.logout({ token: resLogin.access_token }) expect(redirectUrl).to.equal('https://example.com/redirectUrl?access_token=' + resLogin.access_token) }) }) diff --git a/server/tests/plugins/filter-hooks.ts b/server/tests/plugins/filter-hooks.ts index e82aa3bfb..18479dcf5 100644 --- a/server/tests/plugins/filter-hooks.ts +++ b/server/tests/plugins/filter-hooks.ts @@ -32,17 +32,17 @@ describe('Test plugin filter hooks', function () { await setDefaultVideoChannel(servers) await doubleFollow(servers[0], servers[1]) - await servers[0].pluginsCommand.install({ path: PluginsCommand.getPluginTestPath() }) - await servers[0].pluginsCommand.install({ path: PluginsCommand.getPluginTestPath('-filter-translations') }) + await servers[0].plugins.install({ path: PluginsCommand.getPluginTestPath() }) + await servers[0].plugins.install({ path: PluginsCommand.getPluginTestPath('-filter-translations') }) for (let i = 0; i < 10; i++) { - await servers[0].videosCommand.upload({ attributes: { name: 'default video ' + i } }) + await servers[0].videos.upload({ attributes: { name: 'default video ' + i } }) } - const { data } = await servers[0].videosCommand.list() + const { data } = await servers[0].videos.list() videoUUID = data[0].uuid - await servers[0].configCommand.updateCustomSubConfig({ + await servers[0].config.updateCustomSubConfig({ newConfig: { live: { enabled: true }, signup: { enabled: true }, @@ -57,98 +57,98 @@ describe('Test plugin filter hooks', function () { }) it('Should run filter:api.videos.list.params', async function () { - const { data } = await servers[0].videosCommand.list({ start: 0, count: 2 }) + const { data } = await servers[0].videos.list({ start: 0, count: 2 }) // 2 plugins do +1 to the count parameter expect(data).to.have.lengthOf(4) }) it('Should run filter:api.videos.list.result', async function () { - const { total } = await servers[0].videosCommand.list({ start: 0, count: 0 }) + const { total } = await servers[0].videos.list({ start: 0, count: 0 }) // Plugin do +1 to the total result expect(total).to.equal(11) }) it('Should run filter:api.accounts.videos.list.params', async function () { - const { data } = await servers[0].videosCommand.listByAccount({ accountName: 'root', start: 0, count: 2 }) + const { data } = await servers[0].videos.listByAccount({ accountName: 'root', start: 0, count: 2 }) // 1 plugin do +1 to the count parameter expect(data).to.have.lengthOf(3) }) it('Should run filter:api.accounts.videos.list.result', async function () { - const { total } = await servers[0].videosCommand.listByAccount({ accountName: 'root', start: 0, count: 2 }) + const { total } = await servers[0].videos.listByAccount({ accountName: 'root', start: 0, count: 2 }) // Plugin do +2 to the total result expect(total).to.equal(12) }) it('Should run filter:api.video-channels.videos.list.params', async function () { - const { data } = await servers[0].videosCommand.listByChannel({ videoChannelName: 'root_channel', start: 0, count: 2 }) + const { data } = await servers[0].videos.listByChannel({ videoChannelName: 'root_channel', start: 0, count: 2 }) // 1 plugin do +3 to the count parameter expect(data).to.have.lengthOf(5) }) it('Should run filter:api.video-channels.videos.list.result', async function () { - const { total } = await servers[0].videosCommand.listByChannel({ videoChannelName: 'root_channel', start: 0, count: 2 }) + const { total } = await servers[0].videos.listByChannel({ videoChannelName: 'root_channel', start: 0, count: 2 }) // Plugin do +3 to the total result expect(total).to.equal(13) }) it('Should run filter:api.user.me.videos.list.params', async function () { - const { data } = await servers[0].videosCommand.listMyVideos({ start: 0, count: 2 }) + const { data } = await servers[0].videos.listMyVideos({ start: 0, count: 2 }) // 1 plugin do +4 to the count parameter expect(data).to.have.lengthOf(6) }) it('Should run filter:api.user.me.videos.list.result', async function () { - const { total } = await servers[0].videosCommand.listMyVideos({ start: 0, count: 2 }) + const { total } = await servers[0].videos.listMyVideos({ start: 0, count: 2 }) // Plugin do +4 to the total result expect(total).to.equal(14) }) it('Should run filter:api.video.get.result', async function () { - const video = await servers[0].videosCommand.get({ id: videoUUID }) + const video = await servers[0].videos.get({ id: videoUUID }) expect(video.name).to.contain('<3') }) it('Should run filter:api.video.upload.accept.result', async function () { - await servers[0].videosCommand.upload({ attributes: { name: 'video with bad word' }, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) + await servers[0].videos.upload({ attributes: { name: 'video with bad word' }, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) it('Should run filter:api.live-video.create.accept.result', async function () { const attributes = { name: 'video with bad word', privacy: VideoPrivacy.PUBLIC, - channelId: servers[0].videoChannel.id + channelId: servers[0].store.channel.id } - await servers[0].liveCommand.create({ fields: attributes, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) + await servers[0].live.create({ fields: attributes, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) it('Should run filter:api.video.pre-import-url.accept.result', async function () { const attributes = { name: 'normal title', privacy: VideoPrivacy.PUBLIC, - channelId: servers[0].videoChannel.id, + channelId: servers[0].store.channel.id, targetUrl: ImportsCommand.getGoodVideoUrl() + 'bad' } - await servers[0].importsCommand.importVideo({ attributes, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) + await servers[0].imports.importVideo({ attributes, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) it('Should run filter:api.video.pre-import-torrent.accept.result', async function () { const attributes = { name: 'bad torrent', privacy: VideoPrivacy.PUBLIC, - channelId: servers[0].videoChannel.id, + channelId: servers[0].store.channel.id, torrentfile: 'video-720p.torrent' as any } - await servers[0].importsCommand.importVideo({ attributes, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) + await servers[0].imports.importVideo({ attributes, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) it('Should run filter:api.video.post-import-url.accept.result', async function () { @@ -160,17 +160,17 @@ describe('Test plugin filter hooks', function () { const attributes = { name: 'title with bad word', privacy: VideoPrivacy.PUBLIC, - channelId: servers[0].videoChannel.id, + channelId: servers[0].store.channel.id, targetUrl: ImportsCommand.getGoodVideoUrl() } - const body = await servers[0].importsCommand.importVideo({ attributes }) + const body = await servers[0].imports.importVideo({ attributes }) videoImportId = body.id } await waitJobs(servers) { - const body = await servers[0].importsCommand.getMyVideoImports() + const body = await servers[0].imports.getMyVideoImports() const videoImports = body.data const videoImport = videoImports.find(i => i.id === videoImportId) @@ -189,17 +189,17 @@ describe('Test plugin filter hooks', function () { const attributes = { name: 'title with bad word', privacy: VideoPrivacy.PUBLIC, - channelId: servers[0].videoChannel.id, + channelId: servers[0].store.channel.id, torrentfile: 'video-720p.torrent' as any } - const body = await servers[0].importsCommand.importVideo({ attributes }) + const body = await servers[0].imports.importVideo({ attributes }) videoImportId = body.id } await waitJobs(servers) { - const { data: videoImports } = await servers[0].importsCommand.getMyVideoImports() + const { data: videoImports } = await servers[0].imports.getMyVideoImports() const videoImport = videoImports.find(i => i.id === videoImportId) @@ -209,7 +209,7 @@ describe('Test plugin filter hooks', function () { }) it('Should run filter:api.video-thread.create.accept.result', async function () { - await servers[0].commentsCommand.createThread({ + await servers[0].comments.createThread({ videoId: videoUUID, text: 'comment with bad word', expectedStatus: HttpStatusCode.FORBIDDEN_403 @@ -217,16 +217,16 @@ describe('Test plugin filter hooks', function () { }) it('Should run filter:api.video-comment-reply.create.accept.result', async function () { - const created = await servers[0].commentsCommand.createThread({ videoId: videoUUID, text: 'thread' }) + const created = await servers[0].comments.createThread({ videoId: videoUUID, text: 'thread' }) threadId = created.id - await servers[0].commentsCommand.addReply({ + await servers[0].comments.addReply({ videoId: videoUUID, toCommentId: threadId, text: 'comment with bad word', expectedStatus: HttpStatusCode.FORBIDDEN_403 }) - await servers[0].commentsCommand.addReply({ + await servers[0].comments.addReply({ videoId: videoUUID, toCommentId: threadId, text: 'comment with good word', @@ -235,14 +235,14 @@ describe('Test plugin filter hooks', function () { }) it('Should run filter:api.video-threads.list.params', async function () { - const { data } = await servers[0].commentsCommand.listThreads({ videoId: videoUUID, start: 0, count: 0 }) + const { data } = await servers[0].comments.listThreads({ videoId: videoUUID, start: 0, count: 0 }) // our plugin do +1 to the count parameter expect(data).to.have.lengthOf(1) }) it('Should run filter:api.video-threads.list.result', async function () { - const { total } = await servers[0].commentsCommand.listThreads({ videoId: videoUUID, start: 0, count: 0 }) + const { total } = await servers[0].comments.listThreads({ videoId: videoUUID, start: 0, count: 0 }) // Plugin do +1 to the total result expect(total).to.equal(2) @@ -251,7 +251,7 @@ describe('Test plugin filter hooks', function () { it('Should run filter:api.video-thread-comments.list.params') it('Should run filter:api.video-thread-comments.list.result', async function () { - const thread = await servers[0].commentsCommand.getThread({ videoId: videoUUID, threadId }) + const thread = await servers[0].comments.getThread({ videoId: videoUUID, threadId }) expect(thread.comment.text.endsWith(' <3')).to.be.true }) @@ -259,12 +259,12 @@ describe('Test plugin filter hooks', function () { describe('Should run filter:video.auto-blacklist.result', function () { async function checkIsBlacklisted (id: number | string, value: boolean) { - const video = await servers[0].videosCommand.getWithToken({ id }) + const video = await servers[0].videos.getWithToken({ id }) expect(video.blacklisted).to.equal(value) } it('Should blacklist on upload', async function () { - const { uuid } = await servers[0].videosCommand.upload({ attributes: { name: 'video please blacklist me' } }) + const { uuid } = await servers[0].videos.upload({ attributes: { name: 'video please blacklist me' } }) await checkIsBlacklisted(uuid, true) }) @@ -274,24 +274,24 @@ describe('Test plugin filter hooks', function () { const attributes = { name: 'video please blacklist me', targetUrl: ImportsCommand.getGoodVideoUrl(), - channelId: servers[0].videoChannel.id + channelId: servers[0].store.channel.id } - const body = await servers[0].importsCommand.importVideo({ attributes }) + const body = await servers[0].imports.importVideo({ attributes }) await checkIsBlacklisted(body.video.uuid, true) }) it('Should blacklist on update', async function () { - const { uuid } = await servers[0].videosCommand.upload({ attributes: { name: 'video' } }) + const { uuid } = await servers[0].videos.upload({ attributes: { name: 'video' } }) await checkIsBlacklisted(uuid, false) - await servers[0].videosCommand.update({ id: uuid, attributes: { name: 'please blacklist me' } }) + await servers[0].videos.update({ id: uuid, attributes: { name: 'please blacklist me' } }) await checkIsBlacklisted(uuid, true) }) it('Should blacklist on remote upload', async function () { this.timeout(120000) - const { uuid } = await servers[1].videosCommand.upload({ attributes: { name: 'remote please blacklist me' } }) + const { uuid } = await servers[1].videos.upload({ attributes: { name: 'remote please blacklist me' } }) await waitJobs(servers) await checkIsBlacklisted(uuid, true) @@ -300,12 +300,12 @@ describe('Test plugin filter hooks', function () { it('Should blacklist on remote update', async function () { this.timeout(120000) - const { uuid } = await servers[1].videosCommand.upload({ attributes: { name: 'video' } }) + const { uuid } = await servers[1].videos.upload({ attributes: { name: 'video' } }) await waitJobs(servers) await checkIsBlacklisted(uuid, false) - await servers[1].videosCommand.update({ id: uuid, attributes: { name: 'please blacklist me' } }) + await servers[1].videos.update({ id: uuid, attributes: { name: 'please blacklist me' } }) await waitJobs(servers) await checkIsBlacklisted(uuid, true) @@ -315,16 +315,16 @@ describe('Test plugin filter hooks', function () { describe('Should run filter:api.user.signup.allowed.result', function () { it('Should run on config endpoint', async function () { - const body = await servers[0].configCommand.getConfig() + const body = await servers[0].config.getConfig() expect(body.signup.allowed).to.be.true }) it('Should allow a signup', async function () { - await servers[0].usersCommand.register({ username: 'john', password: 'password' }) + await servers[0].users.register({ username: 'john', password: 'password' }) }) it('Should not allow a signup', async function () { - const res = await servers[0].usersCommand.register({ + const res = await servers[0].users.register({ username: 'jma', password: 'password', expectedStatus: HttpStatusCode.FORBIDDEN_403 @@ -340,7 +340,7 @@ describe('Test plugin filter hooks', function () { before(async function () { this.timeout(120000) - await servers[0].configCommand.updateCustomSubConfig({ + await servers[0].config.updateCustomSubConfig({ newConfig: { transcoding: { webtorrent: { @@ -356,14 +356,14 @@ describe('Test plugin filter hooks', function () { const uuids: string[] = [] for (const name of [ 'bad torrent', 'bad file', 'bad playlist file' ]) { - const uuid = (await servers[0].videosCommand.quickUpload({ name: name })).uuid + const uuid = (await servers[0].videos.quickUpload({ name: name })).uuid uuids.push(uuid) } await waitJobs(servers) for (const uuid of uuids) { - downloadVideos.push(await servers[0].videosCommand.get({ id: uuid })) + downloadVideos.push(await servers[0].videos.get({ id: uuid })) } }) @@ -403,7 +403,7 @@ describe('Test plugin filter hooks', function () { before(async function () { this.timeout(60000) - await servers[0].configCommand.updateCustomSubConfig({ + await servers[0].config.updateCustomSubConfig({ newConfig: { transcoding: { enabled: false @@ -413,15 +413,15 @@ describe('Test plugin filter hooks', function () { for (const name of [ 'bad embed', 'good embed' ]) { { - const uuid = (await servers[0].videosCommand.quickUpload({ name: name })).uuid - embedVideos.push(await servers[0].videosCommand.get({ id: uuid })) + const uuid = (await servers[0].videos.quickUpload({ name: name })).uuid + embedVideos.push(await servers[0].videos.get({ id: uuid })) } { - const attributes = { displayName: name, videoChannelId: servers[0].videoChannel.id, privacy: VideoPlaylistPrivacy.PUBLIC } - const { id } = await servers[0].playlistsCommand.create({ attributes }) + const attributes = { displayName: name, videoChannelId: servers[0].store.channel.id, privacy: VideoPlaylistPrivacy.PUBLIC } + const { id } = await servers[0].playlists.create({ attributes }) - const playlist = await servers[0].playlistsCommand.get({ playlistId: id }) + const playlist = await servers[0].playlists.get({ playlistId: id }) embedPlaylists.push(playlist) } } @@ -441,7 +441,7 @@ describe('Test plugin filter hooks', function () { describe('Search filters', function () { before(async function () { - await servers[0].configCommand.updateCustomSubConfig({ + await servers[0].config.updateCustomSubConfig({ newConfig: { search: { searchIndex: { @@ -455,78 +455,78 @@ describe('Test plugin filter hooks', function () { }) it('Should run filter:api.search.videos.local.list.{params,result}', async function () { - await servers[0].searchCommand.advancedVideoSearch({ + await servers[0].search.advancedVideoSearch({ search: { search: 'Sun Quan' } }) - await servers[0].serversCommand.waitUntilLog('Run hook filter:api.search.videos.local.list.params', 1) - await servers[0].serversCommand.waitUntilLog('Run hook filter:api.search.videos.local.list.result', 1) + await servers[0].servers.waitUntilLog('Run hook filter:api.search.videos.local.list.params', 1) + await servers[0].servers.waitUntilLog('Run hook filter:api.search.videos.local.list.result', 1) }) it('Should run filter:api.search.videos.index.list.{params,result}', async function () { - await servers[0].searchCommand.advancedVideoSearch({ + await servers[0].search.advancedVideoSearch({ search: { search: 'Sun Quan', searchTarget: 'search-index' } }) - await servers[0].serversCommand.waitUntilLog('Run hook filter:api.search.videos.local.list.params', 1) - await servers[0].serversCommand.waitUntilLog('Run hook filter:api.search.videos.local.list.result', 1) - await servers[0].serversCommand.waitUntilLog('Run hook filter:api.search.videos.index.list.params', 1) - await servers[0].serversCommand.waitUntilLog('Run hook filter:api.search.videos.index.list.result', 1) + await servers[0].servers.waitUntilLog('Run hook filter:api.search.videos.local.list.params', 1) + await servers[0].servers.waitUntilLog('Run hook filter:api.search.videos.local.list.result', 1) + await servers[0].servers.waitUntilLog('Run hook filter:api.search.videos.index.list.params', 1) + await servers[0].servers.waitUntilLog('Run hook filter:api.search.videos.index.list.result', 1) }) it('Should run filter:api.search.video-channels.local.list.{params,result}', async function () { - await servers[0].searchCommand.advancedChannelSearch({ + await servers[0].search.advancedChannelSearch({ search: { search: 'Sun Ce' } }) - await servers[0].serversCommand.waitUntilLog('Run hook filter:api.search.video-channels.local.list.params', 1) - await servers[0].serversCommand.waitUntilLog('Run hook filter:api.search.video-channels.local.list.result', 1) + await servers[0].servers.waitUntilLog('Run hook filter:api.search.video-channels.local.list.params', 1) + await servers[0].servers.waitUntilLog('Run hook filter:api.search.video-channels.local.list.result', 1) }) it('Should run filter:api.search.video-channels.index.list.{params,result}', async function () { - await servers[0].searchCommand.advancedChannelSearch({ + await servers[0].search.advancedChannelSearch({ search: { search: 'Sun Ce', searchTarget: 'search-index' } }) - await servers[0].serversCommand.waitUntilLog('Run hook filter:api.search.video-channels.local.list.params', 1) - await servers[0].serversCommand.waitUntilLog('Run hook filter:api.search.video-channels.local.list.result', 1) - await servers[0].serversCommand.waitUntilLog('Run hook filter:api.search.video-channels.index.list.params', 1) - await servers[0].serversCommand.waitUntilLog('Run hook filter:api.search.video-channels.index.list.result', 1) + await servers[0].servers.waitUntilLog('Run hook filter:api.search.video-channels.local.list.params', 1) + await servers[0].servers.waitUntilLog('Run hook filter:api.search.video-channels.local.list.result', 1) + await servers[0].servers.waitUntilLog('Run hook filter:api.search.video-channels.index.list.params', 1) + await servers[0].servers.waitUntilLog('Run hook filter:api.search.video-channels.index.list.result', 1) }) it('Should run filter:api.search.video-playlists.local.list.{params,result}', async function () { - await servers[0].searchCommand.advancedPlaylistSearch({ + await servers[0].search.advancedPlaylistSearch({ search: { search: 'Sun Jian' } }) - await servers[0].serversCommand.waitUntilLog('Run hook filter:api.search.video-playlists.local.list.params', 1) - await servers[0].serversCommand.waitUntilLog('Run hook filter:api.search.video-playlists.local.list.result', 1) + await servers[0].servers.waitUntilLog('Run hook filter:api.search.video-playlists.local.list.params', 1) + await servers[0].servers.waitUntilLog('Run hook filter:api.search.video-playlists.local.list.result', 1) }) it('Should run filter:api.search.video-playlists.index.list.{params,result}', async function () { - await servers[0].searchCommand.advancedPlaylistSearch({ + await servers[0].search.advancedPlaylistSearch({ search: { search: 'Sun Jian', searchTarget: 'search-index' } }) - await servers[0].serversCommand.waitUntilLog('Run hook filter:api.search.video-playlists.local.list.params', 1) - await servers[0].serversCommand.waitUntilLog('Run hook filter:api.search.video-playlists.local.list.result', 1) - await servers[0].serversCommand.waitUntilLog('Run hook filter:api.search.video-playlists.index.list.params', 1) - await servers[0].serversCommand.waitUntilLog('Run hook filter:api.search.video-playlists.index.list.result', 1) + await servers[0].servers.waitUntilLog('Run hook filter:api.search.video-playlists.local.list.params', 1) + await servers[0].servers.waitUntilLog('Run hook filter:api.search.video-playlists.local.list.result', 1) + await servers[0].servers.waitUntilLog('Run hook filter:api.search.video-playlists.index.list.params', 1) + await servers[0].servers.waitUntilLog('Run hook filter:api.search.video-playlists.index.list.result', 1) }) }) diff --git a/server/tests/plugins/html-injection.ts b/server/tests/plugins/html-injection.ts index 80d67ae0e..0cb89f511 100644 --- a/server/tests/plugins/html-injection.ts +++ b/server/tests/plugins/html-injection.ts @@ -23,7 +23,7 @@ describe('Test plugins HTML injection', function () { server = await flushAndRunServer(1) await setAccessTokensToServers([ server ]) - command = server.pluginsCommand + command = server.plugins }) it('Should not inject global css file in HTML', async function () { diff --git a/server/tests/plugins/id-and-pass-auth.ts b/server/tests/plugins/id-and-pass-auth.ts index 787080e7c..203996af8 100644 --- a/server/tests/plugins/id-and-pass-auth.ts +++ b/server/tests/plugins/id-and-pass-auth.ts @@ -22,12 +22,12 @@ describe('Test id and pass auth plugins', function () { await setAccessTokensToServers([ server ]) for (const suffix of [ 'one', 'two', 'three' ]) { - await server.pluginsCommand.install({ path: PluginsCommand.getPluginTestPath('-id-pass-auth-' + suffix) }) + await server.plugins.install({ path: PluginsCommand.getPluginTestPath('-id-pass-auth-' + suffix) }) } }) it('Should display the correct configuration', async function () { - const config = await server.configCommand.getConfig() + const config = await server.config.getConfig() const auths = config.plugin.registeredIdAndPassAuths expect(auths).to.have.lengthOf(8) @@ -39,13 +39,13 @@ describe('Test id and pass auth plugins', function () { }) it('Should not login', async function () { - await server.loginCommand.login({ user: { username: 'toto', password: 'password' }, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) + await server.login.login({ user: { username: 'toto', password: 'password' }, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) it('Should login Spyro, create the user and use the token', async function () { - const accessToken = await server.loginCommand.getAccessToken({ username: 'spyro', password: 'spyro password' }) + const accessToken = await server.login.getAccessToken({ username: 'spyro', password: 'spyro password' }) - const body = await server.usersCommand.getMyInfo({ token: accessToken }) + const body = await server.users.getMyInfo({ token: accessToken }) expect(body.username).to.equal('spyro') expect(body.account.displayName).to.equal('Spyro the Dragon') @@ -54,13 +54,13 @@ describe('Test id and pass auth plugins', function () { it('Should login Crash, create the user and use the token', async function () { { - const body = await server.loginCommand.login({ user: { username: 'crash', password: 'crash password' } }) + const body = await server.login.login({ user: { username: 'crash', password: 'crash password' } }) crashAccessToken = body.access_token crashRefreshToken = body.refresh_token } { - const body = await server.usersCommand.getMyInfo({ token: crashAccessToken }) + const body = await server.users.getMyInfo({ token: crashAccessToken }) expect(body.username).to.equal('crash') expect(body.account.displayName).to.equal('Crash Bandicoot') @@ -70,13 +70,13 @@ describe('Test id and pass auth plugins', function () { it('Should login the first Laguna, create the user and use the token', async function () { { - const body = await server.loginCommand.login({ user: { username: 'laguna', password: 'laguna password' } }) + const body = await server.login.login({ user: { username: 'laguna', password: 'laguna password' } }) lagunaAccessToken = body.access_token lagunaRefreshToken = body.refresh_token } { - const body = await server.usersCommand.getMyInfo({ token: lagunaAccessToken }) + const body = await server.users.getMyInfo({ token: lagunaAccessToken }) expect(body.username).to.equal('laguna') expect(body.account.displayName).to.equal('laguna') @@ -86,46 +86,46 @@ describe('Test id and pass auth plugins', function () { it('Should refresh crash token, but not laguna token', async function () { { - const resRefresh = await server.loginCommand.refreshToken({ refreshToken: crashRefreshToken }) + const resRefresh = await server.login.refreshToken({ refreshToken: crashRefreshToken }) crashAccessToken = resRefresh.body.access_token crashRefreshToken = resRefresh.body.refresh_token - const body = await server.usersCommand.getMyInfo({ token: crashAccessToken }) + const body = await server.users.getMyInfo({ token: crashAccessToken }) expect(body.username).to.equal('crash') } { - await server.loginCommand.refreshToken({ refreshToken: lagunaRefreshToken, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) + await server.login.refreshToken({ refreshToken: lagunaRefreshToken, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) } }) it('Should update Crash profile', async function () { - await server.usersCommand.updateMe({ + await server.users.updateMe({ token: crashAccessToken, displayName: 'Beautiful Crash', description: 'Mutant eastern barred bandicoot' }) - const body = await server.usersCommand.getMyInfo({ token: crashAccessToken }) + const body = await server.users.getMyInfo({ token: crashAccessToken }) expect(body.account.displayName).to.equal('Beautiful Crash') expect(body.account.description).to.equal('Mutant eastern barred bandicoot') }) it('Should logout Crash', async function () { - await server.loginCommand.logout({ token: crashAccessToken }) + await server.login.logout({ token: crashAccessToken }) }) it('Should have logged out Crash', async function () { - await server.serversCommand.waitUntilLog('On logout for auth 1 - 2') + await server.servers.waitUntilLog('On logout for auth 1 - 2') - await server.usersCommand.getMyInfo({ token: crashAccessToken, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) + await server.users.getMyInfo({ token: crashAccessToken, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should login Crash and keep the old existing profile', async function () { - crashAccessToken = await server.loginCommand.getAccessToken({ username: 'crash', password: 'crash password' }) + crashAccessToken = await server.login.getAccessToken({ username: 'crash', password: 'crash password' }) - const body = await server.usersCommand.getMyInfo({ token: crashAccessToken }) + const body = await server.users.getMyInfo({ token: crashAccessToken }) expect(body.username).to.equal('crash') expect(body.account.displayName).to.equal('Beautiful Crash') @@ -138,38 +138,38 @@ describe('Test id and pass auth plugins', function () { await wait(5000) - await server.usersCommand.getMyInfo({ token: lagunaAccessToken, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) + await server.users.getMyInfo({ token: lagunaAccessToken, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should reject an invalid username, email, role or display name', async function () { - const command = server.loginCommand + const command = server.login await command.login({ user: { username: 'ward', password: 'ward password' }, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) - await server.serversCommand.waitUntilLog('valid username') + await server.servers.waitUntilLog('valid username') await command.login({ user: { username: 'kiros', password: 'kiros password' }, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) - await server.serversCommand.waitUntilLog('valid display name') + await server.servers.waitUntilLog('valid display name') await command.login({ user: { username: 'raine', password: 'raine password' }, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) - await server.serversCommand.waitUntilLog('valid role') + await server.servers.waitUntilLog('valid role') await command.login({ user: { username: 'ellone', password: 'elonne password' }, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) - await server.serversCommand.waitUntilLog('valid email') + await server.servers.waitUntilLog('valid email') }) it('Should unregister spyro-auth and do not login existing Spyro', async function () { - await server.pluginsCommand.updateSettings({ + await server.plugins.updateSettings({ npmName: 'peertube-plugin-test-id-pass-auth-one', settings: { disableSpyro: true } }) - const command = server.loginCommand + const command = server.login await command.login({ user: { username: 'spyro', password: 'spyro password' }, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) await command.login({ user: { username: 'spyro', password: 'fake' }, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) it('Should have disabled this auth', async function () { - const config = await server.configCommand.getConfig() + const config = await server.config.getConfig() const auths = config.plugin.registeredIdAndPassAuths expect(auths).to.have.lengthOf(7) @@ -179,16 +179,16 @@ describe('Test id and pass auth plugins', function () { }) it('Should uninstall the plugin one and do not login existing Crash', async function () { - await server.pluginsCommand.uninstall({ npmName: 'peertube-plugin-test-id-pass-auth-one' }) + await server.plugins.uninstall({ npmName: 'peertube-plugin-test-id-pass-auth-one' }) - await server.loginCommand.login({ + await server.login.login({ user: { username: 'crash', password: 'crash password' }, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) it('Should display the correct configuration', async function () { - const config = await server.configCommand.getConfig() + const config = await server.config.getConfig() const auths = config.plugin.registeredIdAndPassAuths expect(auths).to.have.lengthOf(6) @@ -198,7 +198,7 @@ describe('Test id and pass auth plugins', function () { }) it('Should display plugin auth information in users list', async function () { - const { data } = await server.usersCommand.list() + const { data } = await server.users.list() const root = data.find(u => u.username === 'root') const crash = data.find(u => u.username === 'crash') diff --git a/server/tests/plugins/plugin-helpers.ts b/server/tests/plugins/plugin-helpers.ts index 509aba13d..cf16aaa9d 100644 --- a/server/tests/plugins/plugin-helpers.ts +++ b/server/tests/plugins/plugin-helpers.ts @@ -39,28 +39,28 @@ describe('Test plugin helpers', function () { await doubleFollow(servers[0], servers[1]) - await servers[0].pluginsCommand.install({ path: PluginsCommand.getPluginTestPath('-four') }) + await servers[0].plugins.install({ path: PluginsCommand.getPluginTestPath('-four') }) }) describe('Logger', function () { it('Should have logged things', async function () { - await servers[0].serversCommand.waitUntilLog('localhost:' + servers[0].port + ' peertube-plugin-test-four', 1, false) - await servers[0].serversCommand.waitUntilLog('Hello world from plugin four', 1) + await servers[0].servers.waitUntilLog('localhost:' + servers[0].port + ' peertube-plugin-test-four', 1, false) + await servers[0].servers.waitUntilLog('Hello world from plugin four', 1) }) }) describe('Database', function () { it('Should have made a query', async function () { - await servers[0].serversCommand.waitUntilLog(`root email is admin${servers[0].internalServerNumber}@example.com`) + await servers[0].servers.waitUntilLog(`root email is admin${servers[0].internalServerNumber}@example.com`) }) }) describe('Config', function () { it('Should have the correct webserver url', async function () { - await servers[0].serversCommand.waitUntilLog(`server url is http://localhost:${servers[0].port}`) + await servers[0].servers.waitUntilLog(`server url is http://localhost:${servers[0].port}`) }) it('Should have the correct config', async function () { @@ -78,7 +78,7 @@ describe('Test plugin helpers', function () { describe('Server', function () { it('Should get the server actor', async function () { - await servers[0].serversCommand.waitUntilLog('server actor name is peertube') + await servers[0].servers.waitUntilLog('server actor name is peertube') }) }) @@ -140,17 +140,17 @@ describe('Test plugin helpers', function () { this.timeout(60000) { - const res = await await servers[0].videosCommand.quickUpload({ name: 'video server 1' }) + const res = await await servers[0].videos.quickUpload({ name: 'video server 1' }) videoUUIDServer1 = res.uuid } { - await await servers[1].videosCommand.quickUpload({ name: 'video server 2' }) + await await servers[1].videos.quickUpload({ name: 'video server 2' }) } await waitJobs(servers) - const { data } = await servers[0].videosCommand.list() + const { data } = await servers[0].videos.list() expect(data).to.have.lengthOf(2) }) @@ -159,7 +159,7 @@ describe('Test plugin helpers', function () { this.timeout(10000) await postCommand(servers[0], 'blockServer', { hostToBlock: `localhost:${servers[1].port}` }) - const { data } = await servers[0].videosCommand.list() + const { data } = await servers[0].videos.list() expect(data).to.have.lengthOf(1) expect(data[0].name).to.equal('video server 1') @@ -168,7 +168,7 @@ describe('Test plugin helpers', function () { it('Should unmute server 2', async function () { await postCommand(servers[0], 'unblockServer', { hostToUnblock: `localhost:${servers[1].port}` }) - const { data } = await servers[0].videosCommand.list() + const { data } = await servers[0].videos.list() expect(data).to.have.lengthOf(2) }) @@ -176,7 +176,7 @@ describe('Test plugin helpers', function () { it('Should mute account of server 2', async function () { await postCommand(servers[0], 'blockAccount', { handleToBlock: `root@localhost:${servers[1].port}` }) - const { data } = await servers[0].videosCommand.list() + const { data } = await servers[0].videos.list() expect(data).to.have.lengthOf(1) expect(data[0].name).to.equal('video server 1') @@ -185,7 +185,7 @@ describe('Test plugin helpers', function () { it('Should unmute account of server 2', async function () { await postCommand(servers[0], 'unblockAccount', { handleToUnblock: `root@localhost:${servers[1].port}` }) - const { data } = await servers[0].videosCommand.list() + const { data } = await servers[0].videos.list() expect(data).to.have.lengthOf(2) }) @@ -198,7 +198,7 @@ describe('Test plugin helpers', function () { await waitJobs(servers) for (const server of servers) { - const { data } = await server.videosCommand.list() + const { data } = await server.videos.list() expect(data).to.have.lengthOf(1) expect(data[0].name).to.equal('video server 2') @@ -213,7 +213,7 @@ describe('Test plugin helpers', function () { await waitJobs(servers) for (const server of servers) { - const { data } = await server.videosCommand.list() + const { data } = await server.videos.list() expect(data).to.have.lengthOf(2) } @@ -224,7 +224,7 @@ describe('Test plugin helpers', function () { let videoUUID: string before(async () => { - const res = await await servers[0].videosCommand.quickUpload({ name: 'video1' }) + const res = await await servers[0].videos.quickUpload({ name: 'video1' }) videoUUID = res.uuid }) @@ -232,15 +232,15 @@ describe('Test plugin helpers', function () { this.timeout(40000) // Should not throw -> video exists - await servers[0].videosCommand.get({ id: videoUUID }) + await servers[0].videos.get({ id: videoUUID }) // Should delete the video - await servers[0].videosCommand.view({ id: videoUUID }) + await servers[0].videos.view({ id: videoUUID }) - await servers[0].serversCommand.waitUntilLog('Video deleted by plugin four.') + await servers[0].servers.waitUntilLog('Video deleted by plugin four.') try { // Should throw because the video should have been deleted - await servers[0].videosCommand.get({ id: videoUUID }) + await servers[0].videos.get({ id: videoUUID }) throw new Error('Video exists') } catch (err) { if (err.message.includes('exists')) throw err @@ -250,7 +250,7 @@ describe('Test plugin helpers', function () { }) it('Should have fetched the video by URL', async function () { - await servers[0].serversCommand.waitUntilLog(`video from DB uuid is ${videoUUID}`) + await servers[0].servers.waitUntilLog(`video from DB uuid is ${videoUUID}`) }) }) diff --git a/server/tests/plugins/plugin-router.ts b/server/tests/plugins/plugin-router.ts index 81e18dabd..1c53dd80c 100644 --- a/server/tests/plugins/plugin-router.ts +++ b/server/tests/plugins/plugin-router.ts @@ -26,7 +26,7 @@ describe('Test plugin helpers', function () { server = await flushAndRunServer(1) await setAccessTokensToServers([ server ]) - await server.pluginsCommand.install({ path: PluginsCommand.getPluginTestPath('-five') }) + await server.plugins.install({ path: PluginsCommand.getPluginTestPath('-five') }) }) it('Should answer "pong"', async function () { @@ -82,7 +82,7 @@ describe('Test plugin helpers', function () { }) it('Should remove the plugin and remove the routes', async function () { - await server.pluginsCommand.uninstall({ npmName: 'peertube-plugin-test-five' }) + await server.plugins.uninstall({ npmName: 'peertube-plugin-test-five' }) for (const path of basePaths) { await makeGetRequest({ diff --git a/server/tests/plugins/plugin-storage.ts b/server/tests/plugins/plugin-storage.ts index 9babfc83e..30e231439 100644 --- a/server/tests/plugins/plugin-storage.ts +++ b/server/tests/plugins/plugin-storage.ts @@ -16,13 +16,13 @@ describe('Test plugin storage', function () { server = await flushAndRunServer(1) await setAccessTokensToServers([ server ]) - await server.pluginsCommand.install({ path: PluginsCommand.getPluginTestPath('-six') }) + await server.plugins.install({ path: PluginsCommand.getPluginTestPath('-six') }) }) describe('DB storage', function () { it('Should correctly store a subkey', async function () { - await server.serversCommand.waitUntilLog('superkey stored value is toto') + await server.servers.waitUntilLog('superkey stored value is toto') }) }) @@ -38,12 +38,12 @@ describe('Test plugin storage', function () { } before(function () { - dataPath = server.serversCommand.buildDirectory('plugins/data') + dataPath = server.servers.buildDirectory('plugins/data') pluginDataPath = join(dataPath, 'peertube-plugin-test-six') }) it('Should have created the directory on install', async function () { - const dataPath = server.serversCommand.buildDirectory('plugins/data') + const dataPath = server.servers.buildDirectory('plugins/data') const pluginDataPath = join(dataPath, 'peertube-plugin-test-six') expect(await pathExists(dataPath)).to.be.true @@ -64,14 +64,14 @@ describe('Test plugin storage', function () { }) it('Should still have the file after an uninstallation', async function () { - await server.pluginsCommand.uninstall({ npmName: 'peertube-plugin-test-six' }) + await server.plugins.uninstall({ npmName: 'peertube-plugin-test-six' }) const content = await getFileContent() expect(content).to.equal('Prince Ali') }) it('Should still have the file after the reinstallation', async function () { - await server.pluginsCommand.install({ path: PluginsCommand.getPluginTestPath('-six') }) + await server.plugins.install({ path: PluginsCommand.getPluginTestPath('-six') }) const content = await getFileContent() expect(content).to.equal('Prince Ali') diff --git a/server/tests/plugins/plugin-transcoding.ts b/server/tests/plugins/plugin-transcoding.ts index a3613293a..3a03065b0 100644 --- a/server/tests/plugins/plugin-transcoding.ts +++ b/server/tests/plugins/plugin-transcoding.ts @@ -19,17 +19,17 @@ import { VideoPrivacy } from '@shared/models' async function createLiveWrapper (server: ServerInfo) { const liveAttributes = { name: 'live video', - channelId: server.videoChannel.id, + channelId: server.store.channel.id, privacy: VideoPrivacy.PUBLIC } - const { uuid } = await server.liveCommand.create({ fields: liveAttributes }) + const { uuid } = await server.live.create({ fields: liveAttributes }) return uuid } function updateConf (server: ServerInfo, vodProfile: string, liveProfile: string) { - return server.configCommand.updateCustomSubConfig({ + return server.config.updateCustomSubConfig({ newConfig: { transcoding: { enabled: true, @@ -79,7 +79,7 @@ describe('Test transcoding plugins', function () { describe('When using a plugin adding profiles to existing encoders', function () { async function checkVideoFPS (uuid: string, type: 'above' | 'below', fps: number) { - const video = await server.videosCommand.get({ id: uuid }) + const video = await server.videos.get({ id: uuid }) const files = video.files.concat(...video.streamingPlaylists.map(p => p.files)) for (const file of files) { @@ -103,11 +103,11 @@ describe('Test transcoding plugins', function () { } before(async function () { - await server.pluginsCommand.install({ path: PluginsCommand.getPluginTestPath('-transcoding-one') }) + await server.plugins.install({ path: PluginsCommand.getPluginTestPath('-transcoding-one') }) }) it('Should have the appropriate available profiles', async function () { - const config = await server.configCommand.getConfig() + const config = await server.config.getConfig() expect(config.transcoding.availableProfiles).to.have.members([ 'default', 'low-vod', 'input-options-vod', 'bad-scale-vod' ]) expect(config.live.transcoding.availableProfiles).to.have.members([ 'default', 'low-live', 'input-options-live', 'bad-scale-live' ]) @@ -116,7 +116,7 @@ describe('Test transcoding plugins', function () { it('Should not use the plugin profile if not chosen by the admin', async function () { this.timeout(240000) - const videoUUID = (await server.videosCommand.quickUpload({ name: 'video' })).uuid + const videoUUID = (await server.videos.quickUpload({ name: 'video' })).uuid await waitJobs([ server ]) await checkVideoFPS(videoUUID, 'above', 20) @@ -127,7 +127,7 @@ describe('Test transcoding plugins', function () { await updateConf(server, 'low-vod', 'default') - const videoUUID = (await server.videosCommand.quickUpload({ name: 'video' })).uuid + const videoUUID = (await server.videos.quickUpload({ name: 'video' })).uuid await waitJobs([ server ]) await checkVideoFPS(videoUUID, 'below', 12) @@ -138,7 +138,7 @@ describe('Test transcoding plugins', function () { await updateConf(server, 'input-options-vod', 'default') - const videoUUID = (await server.videosCommand.quickUpload({ name: 'video' })).uuid + const videoUUID = (await server.videos.quickUpload({ name: 'video' })).uuid await waitJobs([ server ]) await checkVideoFPS(videoUUID, 'below', 6) @@ -149,11 +149,11 @@ describe('Test transcoding plugins', function () { await updateConf(server, 'bad-scale-vod', 'default') - const videoUUID = (await server.videosCommand.quickUpload({ name: 'video' })).uuid + const videoUUID = (await server.videos.quickUpload({ name: 'video' })).uuid await waitJobs([ server ]) // Transcoding failed - const video = await server.videosCommand.get({ id: videoUUID }) + const video = await server.videos.get({ id: videoUUID }) expect(video.files).to.have.lengthOf(1) expect(video.streamingPlaylists).to.have.lengthOf(0) }) @@ -163,8 +163,8 @@ describe('Test transcoding plugins', function () { const liveVideoId = await createLiveWrapper(server) - await server.liveCommand.sendRTMPStreamInVideo({ videoId: liveVideoId, fixtureName: 'video_short2.webm' }) - await server.liveCommand.waitUntilPublished({ videoId: liveVideoId }) + await server.live.sendRTMPStreamInVideo({ videoId: liveVideoId, fixtureName: 'video_short2.webm' }) + await server.live.waitUntilPublished({ videoId: liveVideoId }) await waitJobs([ server ]) await checkLiveFPS(liveVideoId, 'above', 20) @@ -177,8 +177,8 @@ describe('Test transcoding plugins', function () { const liveVideoId = await createLiveWrapper(server) - await server.liveCommand.sendRTMPStreamInVideo({ videoId: liveVideoId, fixtureName: 'video_short2.webm' }) - await server.liveCommand.waitUntilPublished({ videoId: liveVideoId }) + await server.live.sendRTMPStreamInVideo({ videoId: liveVideoId, fixtureName: 'video_short2.webm' }) + await server.live.waitUntilPublished({ videoId: liveVideoId }) await waitJobs([ server ]) await checkLiveFPS(liveVideoId, 'below', 12) @@ -191,8 +191,8 @@ describe('Test transcoding plugins', function () { const liveVideoId = await createLiveWrapper(server) - await server.liveCommand.sendRTMPStreamInVideo({ videoId: liveVideoId, fixtureName: 'video_short2.webm' }) - await server.liveCommand.waitUntilPublished({ videoId: liveVideoId }) + await server.live.sendRTMPStreamInVideo({ videoId: liveVideoId, fixtureName: 'video_short2.webm' }) + await server.live.waitUntilPublished({ videoId: liveVideoId }) await waitJobs([ server ]) await checkLiveFPS(liveVideoId, 'below', 6) @@ -205,21 +205,21 @@ describe('Test transcoding plugins', function () { const liveVideoId = await createLiveWrapper(server) - const command = await server.liveCommand.sendRTMPStreamInVideo({ videoId: liveVideoId, fixtureName: 'video_short2.webm' }) + const command = await server.live.sendRTMPStreamInVideo({ videoId: liveVideoId, fixtureName: 'video_short2.webm' }) await testFfmpegStreamError(command, true) }) it('Should default to the default profile if the specified profile does not exist', async function () { this.timeout(240000) - await server.pluginsCommand.uninstall({ npmName: 'peertube-plugin-test-transcoding-one' }) + await server.plugins.uninstall({ npmName: 'peertube-plugin-test-transcoding-one' }) - const config = await server.configCommand.getConfig() + const config = await server.config.getConfig() expect(config.transcoding.availableProfiles).to.deep.equal([ 'default' ]) expect(config.live.transcoding.availableProfiles).to.deep.equal([ 'default' ]) - const videoUUID = (await server.videosCommand.quickUpload({ name: 'video' })).uuid + const videoUUID = (await server.videos.quickUpload({ name: 'video' })).uuid await waitJobs([ server ]) await checkVideoFPS(videoUUID, 'above', 20) @@ -230,7 +230,7 @@ describe('Test transcoding plugins', function () { describe('When using a plugin adding new encoders', function () { before(async function () { - await server.pluginsCommand.install({ path: PluginsCommand.getPluginTestPath('-transcoding-two') }) + await server.plugins.install({ path: PluginsCommand.getPluginTestPath('-transcoding-two') }) await updateConf(server, 'test-vod-profile', 'test-live-profile') }) @@ -238,10 +238,10 @@ describe('Test transcoding plugins', function () { it('Should use the new vod encoders', async function () { this.timeout(240000) - const videoUUID = (await server.videosCommand.quickUpload({ name: 'video', fixture: 'video_short_240p.mp4' })).uuid + const videoUUID = (await server.videos.quickUpload({ name: 'video', fixture: 'video_short_240p.mp4' })).uuid await waitJobs([ server ]) - const path = server.serversCommand.buildDirectory(join('videos', videoUUID + '-240.mp4')) + const path = server.servers.buildDirectory(join('videos', videoUUID + '-240.mp4')) const audioProbe = await getAudioStream(path) expect(audioProbe.audioStream.codec_name).to.equal('opus') @@ -254,8 +254,8 @@ describe('Test transcoding plugins', function () { const liveVideoId = await createLiveWrapper(server) - await server.liveCommand.sendRTMPStreamInVideo({ videoId: liveVideoId, fixtureName: 'video_short2.webm' }) - await server.liveCommand.waitUntilPublished({ videoId: liveVideoId }) + await server.live.sendRTMPStreamInVideo({ videoId: liveVideoId, fixtureName: 'video_short2.webm' }) + await server.live.waitUntilPublished({ videoId: liveVideoId }) await waitJobs([ server ]) const playlistUrl = `${server.url}/static/streaming-playlists/hls/${liveVideoId}/0.m3u8` diff --git a/server/tests/plugins/plugin-unloading.ts b/server/tests/plugins/plugin-unloading.ts index f430f82b8..26a27abca 100644 --- a/server/tests/plugins/plugin-unloading.ts +++ b/server/tests/plugins/plugin-unloading.ts @@ -16,7 +16,7 @@ describe('Test plugins module unloading', function () { server = await flushAndRunServer(1) await setAccessTokensToServers([ server ]) - await server.pluginsCommand.install({ path: PluginsCommand.getPluginTestPath('-unloading') }) + await server.plugins.install({ path: PluginsCommand.getPluginTestPath('-unloading') }) }) it('Should return a numeric value', async function () { @@ -41,7 +41,7 @@ describe('Test plugins module unloading', function () { }) it('Should uninstall the plugin and free the route', async function () { - await server.pluginsCommand.uninstall({ npmName: 'peertube-plugin-test-unloading' }) + await server.plugins.uninstall({ npmName: 'peertube-plugin-test-unloading' }) await makeGetRequest({ url: server.url, @@ -51,7 +51,7 @@ describe('Test plugins module unloading', function () { }) it('Should return a different numeric value', async function () { - await server.pluginsCommand.install({ path: PluginsCommand.getPluginTestPath('-unloading') }) + await server.plugins.install({ path: PluginsCommand.getPluginTestPath('-unloading') }) const res = await makeGetRequest({ url: server.url, diff --git a/server/tests/plugins/translations.ts b/server/tests/plugins/translations.ts index 0e11a0b53..d8d878026 100644 --- a/server/tests/plugins/translations.ts +++ b/server/tests/plugins/translations.ts @@ -17,7 +17,7 @@ describe('Test plugin translations', function () { server = await flushAndRunServer(1) await setAccessTokensToServers([ server ]) - command = server.pluginsCommand + command = server.plugins await command.install({ path: PluginsCommand.getPluginTestPath() }) await command.install({ path: PluginsCommand.getPluginTestPath('-filter-translations') }) diff --git a/server/tests/plugins/video-constants.ts b/server/tests/plugins/video-constants.ts index 641e37fbb..facc6bbc1 100644 --- a/server/tests/plugins/video-constants.ts +++ b/server/tests/plugins/video-constants.ts @@ -17,11 +17,11 @@ describe('Test plugin altering video constants', function () { server = await flushAndRunServer(1) await setAccessTokensToServers([ server ]) - await server.pluginsCommand.install({ path: PluginsCommand.getPluginTestPath('-video-constants') }) + await server.plugins.install({ path: PluginsCommand.getPluginTestPath('-video-constants') }) }) it('Should have updated languages', async function () { - const languages = await server.videosCommand.getLanguages() + const languages = await server.videos.getLanguages() expect(languages['en']).to.not.exist expect(languages['fr']).to.not.exist @@ -32,7 +32,7 @@ describe('Test plugin altering video constants', function () { }) it('Should have updated categories', async function () { - const categories = await server.videosCommand.getCategories() + const categories = await server.videos.getCategories() expect(categories[1]).to.not.exist expect(categories[2]).to.not.exist @@ -42,7 +42,7 @@ describe('Test plugin altering video constants', function () { }) it('Should have updated licences', async function () { - const licences = await server.videosCommand.getLicences() + const licences = await server.videos.getLicences() expect(licences[1]).to.not.exist expect(licences[7]).to.not.exist @@ -52,7 +52,7 @@ describe('Test plugin altering video constants', function () { }) it('Should have updated video privacies', async function () { - const privacies = await server.videosCommand.getPrivacies() + const privacies = await server.videos.getPrivacies() expect(privacies[1]).to.exist expect(privacies[2]).to.not.exist @@ -61,7 +61,7 @@ describe('Test plugin altering video constants', function () { }) it('Should have updated playlist privacies', async function () { - const playlistPrivacies = await server.playlistsCommand.getPrivacies() + const playlistPrivacies = await server.playlists.getPrivacies() expect(playlistPrivacies[1]).to.exist expect(playlistPrivacies[2]).to.exist @@ -70,29 +70,29 @@ describe('Test plugin altering video constants', function () { it('Should not be able to create a video with this privacy', async function () { const attributes = { name: 'video', privacy: 2 } - await server.videosCommand.upload({ attributes, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) + await server.videos.upload({ attributes, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) it('Should not be able to create a video with this privacy', async function () { const attributes = { displayName: 'video playlist', privacy: VideoPlaylistPrivacy.PRIVATE } - await server.playlistsCommand.create({ attributes, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) + await server.playlists.create({ attributes, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) it('Should be able to upload a video with these values', async function () { const attributes = { name: 'video', category: 42, licence: 42, language: 'al_bhed2' } - const { uuid } = await server.videosCommand.upload({ attributes }) + const { uuid } = await server.videos.upload({ attributes }) - const video = await server.videosCommand.get({ id: uuid }) + const video = await server.videos.get({ id: uuid }) expect(video.language.label).to.equal('Al Bhed 2') expect(video.licence.label).to.equal('Best licence') expect(video.category.label).to.equal('Best category') }) it('Should uninstall the plugin and reset languages, categories, licences and privacies', async function () { - await server.pluginsCommand.uninstall({ npmName: 'peertube-plugin-test-video-constants' }) + await server.plugins.uninstall({ npmName: 'peertube-plugin-test-video-constants' }) { - const languages = await server.videosCommand.getLanguages() + const languages = await server.videos.getLanguages() expect(languages['en']).to.equal('English') expect(languages['fr']).to.equal('French') @@ -103,7 +103,7 @@ describe('Test plugin altering video constants', function () { } { - const categories = await server.videosCommand.getCategories() + const categories = await server.videos.getCategories() expect(categories[1]).to.equal('Music') expect(categories[2]).to.equal('Films') @@ -113,7 +113,7 @@ describe('Test plugin altering video constants', function () { } { - const licences = await server.videosCommand.getLicences() + const licences = await server.videos.getLicences() expect(licences[1]).to.equal('Attribution') expect(licences[7]).to.equal('Public Domain Dedication') @@ -123,7 +123,7 @@ describe('Test plugin altering video constants', function () { } { - const privacies = await server.videosCommand.getPrivacies() + const privacies = await server.videos.getPrivacies() expect(privacies[1]).to.exist expect(privacies[2]).to.exist @@ -132,7 +132,7 @@ describe('Test plugin altering video constants', function () { } { - const playlistPrivacies = await server.playlistsCommand.getPrivacies() + const playlistPrivacies = await server.playlists.getPrivacies() expect(playlistPrivacies[1]).to.exist expect(playlistPrivacies[2]).to.exist diff --git a/server/tools/cli.ts b/server/tools/cli.ts index 163ed62d1..7d5eb72ed 100644 --- a/server/tools/cli.ts +++ b/server/tools/cli.ts @@ -15,8 +15,8 @@ const config = require('application-config')(configName) const version = require('../../../package.json').version async function getAdminTokenOrDie (server: ServerInfo, username: string, password: string) { - const token = await server.loginCommand.getAccessToken(username, password) - const me = await server.usersCommand.getMyInfo({ token }) + const token = await server.login.getAccessToken(username, password) + const me = await server.users.getMyInfo({ token }) if (me.role !== UserRole.ADMINISTRATOR) { console.error('You must be an administrator.') @@ -160,7 +160,7 @@ async function buildVideoAttributesFromCommander (server: ServerInfo, command: C Object.assign(videoAttributes, booleanAttributes) if (options.channelName) { - const videoChannel = await server.channelsCommand.get({ channelName: options.channelName }) + const videoChannel = await server.channels.get({ channelName: options.channelName }) Object.assign(videoAttributes, { channelId: videoChannel.id }) @@ -187,10 +187,10 @@ function buildServer (url: string): ServerInfo { } async function assignToken (server: ServerInfo, username: string, password: string) { - const bodyClient = await server.loginCommand.getClient() + const bodyClient = await server.login.getClient() const client = { id: bodyClient.client_id, secret: bodyClient.client_secret } - const body = await server.loginCommand.login({ client, user: { username, password } }) + const body = await server.login.login({ client, user: { username, password } }) server.accessToken = body.access_token } diff --git a/server/tools/peertube-import-videos.ts b/server/tools/peertube-import-videos.ts index fc76735b9..caf1facc7 100644 --- a/server/tools/peertube-import-videos.ts +++ b/server/tools/peertube-import-videos.ts @@ -150,7 +150,7 @@ async function processVideo (parameters: { } const server = buildServer(url) - const { data } = await server.searchCommand.advancedVideoSearch({ + const { data } = await server.search.advancedVideoSearch({ search: { search: videoInfo.title, sort: '-match', @@ -249,14 +249,14 @@ async function uploadVideoOnPeerTube (parameters: { log.info('\nUploading on PeerTube video "%s".', attributes.name) try { - await server.videosCommand.upload({ attributes }) + await server.videos.upload({ attributes }) } catch (err) { if (err.message.indexOf('401') !== -1) { log.info('Got 401 Unauthorized, token may have expired, renewing token and retry.') - server.accessToken = await server.loginCommand.getAccessToken(username, password) + server.accessToken = await server.login.getAccessToken(username, password) - await server.videosCommand.upload({ attributes }) + await server.videos.upload({ attributes }) } else { exitError(err.message) } @@ -277,7 +277,7 @@ async function getCategory (server: ServerInfo, categories: string[]) { if (categoryString === 'News & Politics') return 11 - const categoriesServer = await server.videosCommand.getCategories() + const categoriesServer = await server.videos.getCategories() for (const key of Object.keys(categoriesServer)) { const categoryServer = categoriesServer[key] diff --git a/server/tools/peertube-plugins.ts b/server/tools/peertube-plugins.ts index 22a09b779..d9c285115 100644 --- a/server/tools/peertube-plugins.ts +++ b/server/tools/peertube-plugins.ts @@ -69,7 +69,7 @@ async function pluginsListCLI (command: Command, options: OptionValues) { if (options.onlyThemes) pluginType = PluginType.THEME if (options.onlyPlugins) pluginType = PluginType.PLUGIN - const { data } = await server.pluginsCommand.list({ start: 0, count: 100, sort: 'name', pluginType }) + const { data } = await server.plugins.list({ start: 0, count: 100, sort: 'name', pluginType }) const table = new CliTable3({ head: [ 'name', 'version', 'homepage' ], @@ -109,7 +109,7 @@ async function installPluginCLI (command: Command, options: OptionValues) { await assignToken(server, username, password) try { - await server.pluginsCommand.install({ npmName: options.npmName, path: options.path }) + await server.plugins.install({ npmName: options.npmName, path: options.path }) } catch (err) { console.error('Cannot install plugin.', err) process.exit(-1) @@ -136,7 +136,7 @@ async function updatePluginCLI (command: Command, options: OptionValues) { await assignToken(server, username, password) try { - await server.pluginsCommand.update({ npmName: options.npmName, path: options.path }) + await server.plugins.update({ npmName: options.npmName, path: options.path }) } catch (err) { console.error('Cannot update plugin.', err) process.exit(-1) @@ -158,7 +158,7 @@ async function uninstallPluginCLI (command: Command, options: OptionValues) { await assignToken(server, username, password) try { - await server.pluginsCommand.uninstall({ npmName: options.npmName }) + await server.plugins.uninstall({ npmName: options.npmName }) } catch (err) { console.error('Cannot uninstall plugin.', err) process.exit(-1) diff --git a/server/tools/peertube-redundancy.ts b/server/tools/peertube-redundancy.ts index 0f6b3086c..5fda68c8e 100644 --- a/server/tools/peertube-redundancy.ts +++ b/server/tools/peertube-redundancy.ts @@ -63,7 +63,7 @@ async function listRedundanciesCLI (target: VideoRedundanciesTarget) { const server = buildServer(url) await assignToken(server, username, password) - const { data } = await server.redundancyCommand.listVideos({ start: 0, count: 100, sort: 'name', target }) + const { data } = await server.redundancy.listVideos({ start: 0, count: 100, sort: 'name', target }) const table = new CliTable3({ head: [ 'video id', 'video name', 'video url', 'files', 'playlists', 'by instances', 'total size' ] @@ -114,7 +114,7 @@ async function addRedundancyCLI (options: { video: number }, command: Command) { } try { - await server.redundancyCommand.addVideo({ videoId: options.video }) + await server.redundancy.addVideo({ videoId: options.video }) console.log('Video will be duplicated by your instance!') @@ -145,11 +145,11 @@ async function removeRedundancyCLI (options: { video: number }, command: Command const videoId = parseInt(options.video + '', 10) - const myVideoRedundancies = await server.redundancyCommand.listVideos({ target: 'my-videos' }) + const myVideoRedundancies = await server.redundancy.listVideos({ target: 'my-videos' }) let videoRedundancy = myVideoRedundancies.data.find(r => videoId === r.id) if (!videoRedundancy) { - const remoteVideoRedundancies = await server.redundancyCommand.listVideos({ target: 'remote-videos' }) + const remoteVideoRedundancies = await server.redundancy.listVideos({ target: 'remote-videos' }) videoRedundancy = remoteVideoRedundancies.data.find(r => videoId === r.id) } @@ -164,7 +164,7 @@ async function removeRedundancyCLI (options: { video: number }, command: Command .map(r => r.id) for (const id of ids) { - await server.redundancyCommand.removeVideo({ redundancyId: id }) + await server.redundancy.removeVideo({ redundancyId: id }) } console.log('Video redundancy removed!') diff --git a/server/tools/peertube-upload.ts b/server/tools/peertube-upload.ts index 597137e4c..01fb1fe8d 100644 --- a/server/tools/peertube-upload.ts +++ b/server/tools/peertube-upload.ts @@ -62,7 +62,7 @@ async function run (url: string, username: string, password: string) { } try { - await server.videosCommand.upload({ attributes }) + await server.videos.upload({ attributes }) console.log(`Video ${options.videoName} uploaded.`) process.exit(0) } catch (err) { diff --git a/server/tools/test-live.ts b/server/tools/test-live.ts index 7004e98e8..bc31b6926 100644 --- a/server/tools/test-live.ts +++ b/server/tools/test-live.ts @@ -54,15 +54,15 @@ async function run () { const attributes: LiveVideoCreate = { name: 'live', saveReplay: true, - channelId: server.videoChannel.id, + channelId: server.store.channel.id, privacy: VideoPrivacy.PUBLIC } console.log('Creating live.') - const { uuid: liveVideoUUID } = await server.liveCommand.create({ fields: attributes }) + const { uuid: liveVideoUUID } = await server.live.create({ fields: attributes }) - const live = await server.liveCommand.get({ videoId: liveVideoUUID }) + const live = await server.live.get({ videoId: liveVideoUUID }) console.log('Sending RTMP stream.') @@ -82,7 +82,7 @@ async function run () { // ---------------------------------------------------------------------------- async function buildConfig (server: ServerInfo, commandType: CommandType) { - await server.configCommand.updateCustomSubConfig({ + await server.config.updateCustomSubConfig({ newConfig: { instance: { customizations: { diff --git a/shared/extra-utils/miscs/checks.ts b/shared/extra-utils/miscs/checks.ts index 86b861cd2..8f7bdb9b5 100644 --- a/shared/extra-utils/miscs/checks.ts +++ b/shared/extra-utils/miscs/checks.ts @@ -34,7 +34,7 @@ async function testImage (url: string, imageName: string, imagePath: string, ext } async function testFileExistsOrNot (server: ServerInfo, directory: string, filePath: string, exist: boolean) { - const base = server.serversCommand.buildDirectory(directory) + const base = server.servers.buildDirectory(directory) expect(await pathExists(join(base, filePath))).to.equal(exist) } diff --git a/shared/extra-utils/miscs/webtorrent.ts b/shared/extra-utils/miscs/webtorrent.ts index 63e648309..84e390b2a 100644 --- a/shared/extra-utils/miscs/webtorrent.ts +++ b/shared/extra-utils/miscs/webtorrent.ts @@ -17,7 +17,7 @@ function webtorrentAdd (torrent: string, refreshWebTorrent = false) { async function parseTorrentVideo (server: ServerInfo, videoUUID: string, resolution: number) { const torrentName = videoUUID + '-' + resolution + '.torrent' - const torrentPath = server.serversCommand.buildDirectory(join('torrents', torrentName)) + const torrentPath = server.servers.buildDirectory(join('torrents', torrentName)) const data = await readFile(torrentPath) diff --git a/shared/extra-utils/server/follows.ts b/shared/extra-utils/server/follows.ts index c23cebd81..50ae898cc 100644 --- a/shared/extra-utils/server/follows.ts +++ b/shared/extra-utils/server/follows.ts @@ -3,8 +3,8 @@ import { ServerInfo } from './servers' async function doubleFollow (server1: ServerInfo, server2: ServerInfo) { await Promise.all([ - server1.followsCommand.follow({ targets: [ server2.url ] }), - server2.followsCommand.follow({ targets: [ server1.url ] }) + server1.follows.follow({ targets: [ server2.url ] }), + server2.follows.follow({ targets: [ server1.url ] }) ]) // Wait request propagation diff --git a/shared/extra-utils/server/jobs.ts b/shared/extra-utils/server/jobs.ts index 36ef882b3..754530977 100644 --- a/shared/extra-utils/server/jobs.ts +++ b/shared/extra-utils/server/jobs.ts @@ -23,7 +23,7 @@ async function waitJobs (serversArg: ServerInfo[] | ServerInfo) { // Check if each server has pending request for (const server of servers) { for (const state of states) { - const p = server.jobsCommand.getJobsList({ + const p = server.jobs.getJobsList({ state, start: 0, count: 10, @@ -39,7 +39,7 @@ async function waitJobs (serversArg: ServerInfo[] | ServerInfo) { tasks.push(p) } - const p = server.debugCommand.getDebug() + const p = server.debug.getDebug() .then(obj => { if (obj.activityPubMessagesWaiting !== 0) { pendingRequests = true diff --git a/shared/extra-utils/server/plugins-command.ts b/shared/extra-utils/server/plugins-command.ts index 5bed51d1a..98049ce19 100644 --- a/shared/extra-utils/server/plugins-command.ts +++ b/shared/extra-utils/server/plugins-command.ts @@ -251,6 +251,6 @@ export class PluginsCommand extends AbstractCommand { } private getPackageJSONPath (npmName: string) { - return this.server.serversCommand.buildDirectory(join('plugins', 'node_modules', npmName, 'package.json')) + return this.server.servers.buildDirectory(join('plugins', 'node_modules', npmName, 'package.json')) } } diff --git a/shared/extra-utils/server/plugins.ts b/shared/extra-utils/server/plugins.ts index 1084ea4f4..d1cc7e383 100644 --- a/shared/extra-utils/server/plugins.ts +++ b/shared/extra-utils/server/plugins.ts @@ -4,7 +4,7 @@ import { expect } from 'chai' import { ServerInfo } from '../server/servers' async function testHelloWorldRegisteredSettings (server: ServerInfo) { - const body = await server.pluginsCommand.getRegisteredSettings({ npmName: 'peertube-plugin-hello-world' }) + const body = await server.plugins.getRegisteredSettings({ npmName: 'peertube-plugin-hello-world' }) const registeredSettings = body.registeredSettings expect(registeredSettings).to.have.length.at.least(1) diff --git a/shared/extra-utils/server/servers-command.ts b/shared/extra-utils/server/servers-command.ts index 9ef68fede..a7c5a868d 100644 --- a/shared/extra-utils/server/servers-command.ts +++ b/shared/extra-utils/server/servers-command.ts @@ -37,7 +37,7 @@ export class ServersCommand extends AbstractCommand { if (isGithubCI()) { await ensureDir('artifacts') - const origin = this.server.serversCommand.buildDirectory('logs/peertube.log') + const origin = this.server.servers.buildDirectory('logs/peertube.log') const destname = `peertube-${this.server.internalServerNumber}.log` console.log('Saving logs %s.', destname) @@ -56,7 +56,7 @@ export class ServersCommand extends AbstractCommand { } async waitUntilLog (str: string, count = 1, strictCount = true) { - const logfile = this.server.serversCommand.buildDirectory('logs/peertube.log') + const logfile = this.server.servers.buildDirectory('logs/peertube.log') while (true) { const buf = await readFile(logfile) @@ -74,7 +74,7 @@ export class ServersCommand extends AbstractCommand { } async getServerFileSize (subPath: string) { - const path = this.server.serversCommand.buildDirectory(subPath) + const path = this.server.servers.buildDirectory(subPath) return getFileSize(path) } diff --git a/shared/extra-utils/server/servers.ts b/shared/extra-utils/server/servers.ts index fda5c3d6d..ea3f19a92 100644 --- a/shared/extra-utils/server/servers.ts +++ b/shared/extra-utils/server/servers.ts @@ -53,83 +53,81 @@ interface ServerInfo { parallel?: boolean internalServerNumber: number + serverNumber?: number + customConfigFile?: string - client?: { - id?: string - secret?: string - } + store?: { + client?: { + id?: string + secret?: string + } - user?: { - username: string - password: string - email?: string - } + user?: { + username: string + password: string + email?: string + } - customConfigFile?: string + channel?: VideoChannel - accessToken?: string - refreshToken?: string - videoChannel?: VideoChannel + video?: { + id: number + uuid: string + shortUUID: string + name?: string + url?: string - video?: { - id: number - uuid: string - shortUUID: string - name?: string - url?: string + account?: { + name: string + } - account?: { - name: string + embedPath?: string } - embedPath?: string + videos?: { id: number, uuid: string }[] } - remoteVideo?: { - id: number - uuid: string - } + accessToken?: string + refreshToken?: string - videos?: { id: number, uuid: string }[] - - bulkCommand?: BulkCommand - cliCommand?: CLICommand - customPageCommand?: CustomPagesCommand - feedCommand?: FeedCommand - logsCommand?: LogsCommand - abusesCommand?: AbusesCommand - overviewsCommand?: OverviewsCommand - searchCommand?: SearchCommand - contactFormCommand?: ContactFormCommand - debugCommand?: DebugCommand - followsCommand?: FollowsCommand - jobsCommand?: JobsCommand - pluginsCommand?: PluginsCommand - redundancyCommand?: RedundancyCommand - statsCommand?: StatsCommand - configCommand?: ConfigCommand - socketIOCommand?: SocketIOCommand - accountsCommand?: AccountsCommand - blocklistCommand?: BlocklistCommand - subscriptionsCommand?: SubscriptionsCommand - liveCommand?: LiveCommand - servicesCommand?: ServicesCommand - blacklistCommand?: BlacklistCommand - captionsCommand?: CaptionsCommand - changeOwnershipCommand?: ChangeOwnershipCommand - playlistsCommand?: PlaylistsCommand - historyCommand?: HistoryCommand - importsCommand?: ImportsCommand - streamingPlaylistsCommand?: StreamingPlaylistsCommand - channelsCommand?: ChannelsCommand - commentsCommand?: CommentsCommand - sqlCommand?: SQLCommand - notificationsCommand?: NotificationsCommand - serversCommand?: ServersCommand - loginCommand?: LoginCommand - usersCommand?: UsersCommand - videosCommand?: VideosCommand + bulk?: BulkCommand + cli?: CLICommand + customPage?: CustomPagesCommand + feed?: FeedCommand + logs?: LogsCommand + abuses?: AbusesCommand + overviews?: OverviewsCommand + search?: SearchCommand + contactForm?: ContactFormCommand + debug?: DebugCommand + follows?: FollowsCommand + jobs?: JobsCommand + plugins?: PluginsCommand + redundancy?: RedundancyCommand + stats?: StatsCommand + config?: ConfigCommand + socketIO?: SocketIOCommand + accounts?: AccountsCommand + blocklist?: BlocklistCommand + subscriptions?: SubscriptionsCommand + live?: LiveCommand + services?: ServicesCommand + blacklist?: BlacklistCommand + captions?: CaptionsCommand + changeOwnership?: ChangeOwnershipCommand + playlists?: PlaylistsCommand + history?: HistoryCommand + imports?: ImportsCommand + streamingPlaylists?: StreamingPlaylistsCommand + channels?: ChannelsCommand + comments?: CommentsCommand + sql?: SQLCommand + notifications?: NotificationsCommand + servers?: ServersCommand + login?: LoginCommand + users?: UsersCommand + videos?: VideosCommand } function flushAndRunMultipleServers (totalServers: number, configOverride?: Object) { @@ -189,13 +187,15 @@ async function flushAndRunServer (serverNumber: number, configOverride?: Object, url: `http://localhost:${port}`, host: `localhost:${port}`, hostname: 'localhost', - client: { - id: null, - secret: null - }, - user: { - username: null, - password: null + store: { + client: { + id: null, + secret: null + }, + user: { + username: null, + password: null + } } } @@ -291,10 +291,10 @@ async function runServer (server: ServerInfo, configOverrideArg?: any, args = [] const regexp = regexps[key] const matches = data.toString().match(regexp) if (matches !== null) { - if (key === 'client_id') server.client.id = matches[1] - else if (key === 'client_secret') server.client.secret = matches[1] - else if (key === 'user_username') server.user.username = matches[1] - else if (key === 'user_password') server.user.password = matches[1] + if (key === 'client_id') server.store.client.id = matches[1] + else if (key === 'client_secret') server.store.client.secret = matches[1] + else if (key === 'user_username') server.store.user.username = matches[1] + else if (key === 'user_password') server.store.user.password = matches[1] } } @@ -327,43 +327,43 @@ async function runServer (server: ServerInfo, configOverrideArg?: any, args = [] } function assignCommands (server: ServerInfo) { - server.bulkCommand = new BulkCommand(server) - server.cliCommand = new CLICommand(server) - server.customPageCommand = new CustomPagesCommand(server) - server.feedCommand = new FeedCommand(server) - server.logsCommand = new LogsCommand(server) - server.abusesCommand = new AbusesCommand(server) - server.overviewsCommand = new OverviewsCommand(server) - server.searchCommand = new SearchCommand(server) - server.contactFormCommand = new ContactFormCommand(server) - server.debugCommand = new DebugCommand(server) - server.followsCommand = new FollowsCommand(server) - server.jobsCommand = new JobsCommand(server) - server.pluginsCommand = new PluginsCommand(server) - server.redundancyCommand = new RedundancyCommand(server) - server.statsCommand = new StatsCommand(server) - server.configCommand = new ConfigCommand(server) - server.socketIOCommand = new SocketIOCommand(server) - server.accountsCommand = new AccountsCommand(server) - server.blocklistCommand = new BlocklistCommand(server) - server.subscriptionsCommand = new SubscriptionsCommand(server) - server.liveCommand = new LiveCommand(server) - server.servicesCommand = new ServicesCommand(server) - server.blacklistCommand = new BlacklistCommand(server) - server.captionsCommand = new CaptionsCommand(server) - server.changeOwnershipCommand = new ChangeOwnershipCommand(server) - server.playlistsCommand = new PlaylistsCommand(server) - server.historyCommand = new HistoryCommand(server) - server.importsCommand = new ImportsCommand(server) - server.streamingPlaylistsCommand = new StreamingPlaylistsCommand(server) - server.channelsCommand = new ChannelsCommand(server) - server.commentsCommand = new CommentsCommand(server) - server.sqlCommand = new SQLCommand(server) - server.notificationsCommand = new NotificationsCommand(server) - server.serversCommand = new ServersCommand(server) - server.loginCommand = new LoginCommand(server) - server.usersCommand = new UsersCommand(server) - server.videosCommand = new VideosCommand(server) + server.bulk = new BulkCommand(server) + server.cli = new CLICommand(server) + server.customPage = new CustomPagesCommand(server) + server.feed = new FeedCommand(server) + server.logs = new LogsCommand(server) + server.abuses = new AbusesCommand(server) + server.overviews = new OverviewsCommand(server) + server.search = new SearchCommand(server) + server.contactForm = new ContactFormCommand(server) + server.debug = new DebugCommand(server) + server.follows = new FollowsCommand(server) + server.jobs = new JobsCommand(server) + server.plugins = new PluginsCommand(server) + server.redundancy = new RedundancyCommand(server) + server.stats = new StatsCommand(server) + server.config = new ConfigCommand(server) + server.socketIO = new SocketIOCommand(server) + server.accounts = new AccountsCommand(server) + server.blocklist = new BlocklistCommand(server) + server.subscriptions = new SubscriptionsCommand(server) + server.live = new LiveCommand(server) + server.services = new ServicesCommand(server) + server.blacklist = new BlacklistCommand(server) + server.captions = new CaptionsCommand(server) + server.changeOwnership = new ChangeOwnershipCommand(server) + server.playlists = new PlaylistsCommand(server) + server.history = new HistoryCommand(server) + server.imports = new ImportsCommand(server) + server.streamingPlaylists = new StreamingPlaylistsCommand(server) + server.channels = new ChannelsCommand(server) + server.comments = new CommentsCommand(server) + server.sql = new SQLCommand(server) + server.notifications = new NotificationsCommand(server) + server.servers = new ServersCommand(server) + server.login = new LoginCommand(server) + server.users = new UsersCommand(server) + server.videos = new VideosCommand(server) } async function reRunServer (server: ServerInfo, configOverride?: any) { @@ -377,7 +377,7 @@ async function killallServers (servers: ServerInfo[]) { for (const server of servers) { if (!server.app) continue - await server.sqlCommand.cleanup() + await server.sql.cleanup() process.kill(-server.app.pid) @@ -394,7 +394,7 @@ async function cleanupTests (servers: ServerInfo[]) { let p: Promise[] = [] for (const server of servers) { - p = p.concat(server.serversCommand.cleanupTests()) + p = p.concat(server.servers.cleanupTests()) } return Promise.all(p) diff --git a/shared/extra-utils/users/accounts.ts b/shared/extra-utils/users/accounts.ts index ee94351e8..2c9a4b71c 100644 --- a/shared/extra-utils/users/accounts.ts +++ b/shared/extra-utils/users/accounts.ts @@ -14,7 +14,7 @@ async function expectAccountFollows (options: { }) { const { server, handle, followers, following } = options - const body = await server.accountsCommand.list() + const body = await server.accounts.list() const account = body.data.find(a => a.name + '@' + a.host === handle) const message = `${handle} on ${server.url}` diff --git a/shared/extra-utils/users/login-command.ts b/shared/extra-utils/users/login-command.ts index b4e3bb602..10c3db851 100644 --- a/shared/extra-utils/users/login-command.ts +++ b/shared/extra-utils/users/login-command.ts @@ -9,7 +9,7 @@ export class LoginCommand extends AbstractCommand { client?: { id?: string, secret?: string } user?: { username: string, password?: string } } = {}) { - const { client = this.server.client, user = this.server.user } = options + const { client = this.server.store.client, user = this.server.store.user } = options const path = '/api/v1/users/token' const body = { @@ -38,7 +38,7 @@ export class LoginCommand extends AbstractCommand { async getAccessToken (arg1?: { username: string, password?: string } | string, password?: string) { let user: { username: string, password?: string } - if (!arg1) user = this.server.user + if (!arg1) user = this.server.store.user else if (typeof arg1 === 'object') user = arg1 else user = { username: arg1, password } @@ -59,8 +59,8 @@ export class LoginCommand extends AbstractCommand { const path = '/api/v1/users/token' const body = { - client_id: this.server.client.id, - client_secret: this.server.client.secret, + client_id: this.server.store.client.id, + client_secret: this.server.store.client.secret, username: username, response_type: 'code', grant_type: 'password', @@ -100,8 +100,8 @@ export class LoginCommand extends AbstractCommand { const path = '/api/v1/users/token' const body = { - client_id: this.server.client.id, - client_secret: this.server.client.secret, + client_id: this.server.store.client.id, + client_secret: this.server.store.client.secret, refresh_token: options.refreshToken, response_type: 'code', grant_type: 'refresh_token' diff --git a/shared/extra-utils/users/login.ts b/shared/extra-utils/users/login.ts index d4ee8e517..d0c26a4f0 100644 --- a/shared/extra-utils/users/login.ts +++ b/shared/extra-utils/users/login.ts @@ -4,7 +4,7 @@ function setAccessTokensToServers (servers: ServerInfo[]) { const tasks: Promise[] = [] for (const server of servers) { - const p = server.loginCommand.getAccessToken() + const p = server.login.getAccessToken() .then(t => { server.accessToken = t }) tasks.push(p) } diff --git a/shared/extra-utils/users/notifications.ts b/shared/extra-utils/users/notifications.ts index 0af7d8a18..9196f0bf5 100644 --- a/shared/extra-utils/users/notifications.ts +++ b/shared/extra-utils/users/notifications.ts @@ -49,7 +49,7 @@ async function checkNotification ( const check = base.check || { web: true, mail: true } if (check.web) { - const notification = await base.server.notificationsCommand.getLastest({ token: base.token }) + const notification = await base.server.notifications.getLastest({ token: base.token }) if (notification || checkType !== 'absence') { notificationChecker(notification, checkType) @@ -651,31 +651,31 @@ async function prepareNotificationsTest (serversCount = 3, overrideConfigArg: an } const user = { username: 'user_1', password: 'super password' } - await servers[0].usersCommand.create({ ...user, videoQuota: 10 * 1000 * 1000 }) - const userAccessToken = await servers[0].loginCommand.getAccessToken(user) + await servers[0].users.create({ ...user, videoQuota: 10 * 1000 * 1000 }) + const userAccessToken = await servers[0].login.getAccessToken(user) - await servers[0].notificationsCommand.updateMySettings({ token: userAccessToken, settings: getAllNotificationsSettings() }) - await servers[0].notificationsCommand.updateMySettings({ settings: getAllNotificationsSettings() }) + await servers[0].notifications.updateMySettings({ token: userAccessToken, settings: getAllNotificationsSettings() }) + await servers[0].notifications.updateMySettings({ settings: getAllNotificationsSettings() }) if (serversCount > 1) { - await servers[1].notificationsCommand.updateMySettings({ settings: getAllNotificationsSettings() }) + await servers[1].notifications.updateMySettings({ settings: getAllNotificationsSettings() }) } { - const socket = servers[0].socketIOCommand.getUserNotificationSocket({ token: userAccessToken }) + const socket = servers[0].socketIO.getUserNotificationSocket({ token: userAccessToken }) socket.on('new-notification', n => userNotifications.push(n)) } { - const socket = servers[0].socketIOCommand.getUserNotificationSocket() + const socket = servers[0].socketIO.getUserNotificationSocket() socket.on('new-notification', n => adminNotifications.push(n)) } if (serversCount > 1) { - const socket = servers[1].socketIOCommand.getUserNotificationSocket() + const socket = servers[1].socketIO.getUserNotificationSocket() socket.on('new-notification', n => adminNotificationsServer2.push(n)) } - const { videoChannels } = await servers[0].usersCommand.getMyInfo() + const { videoChannels } = await servers[0].users.getMyInfo() const channelId = videoChannels[0].id return { diff --git a/shared/extra-utils/users/users-command.ts b/shared/extra-utils/users/users-command.ts index 202528b8d..59dc6d018 100644 --- a/shared/extra-utils/users/users-command.ts +++ b/shared/extra-utils/users/users-command.ts @@ -194,7 +194,7 @@ export class UsersCommand extends AbstractCommand { const password = 'password' const user = await this.create({ username, password }) - const token = await this.server.loginCommand.getAccessToken({ username, password }) + const token = await this.server.login.getAccessToken({ username, password }) const me = await this.getMyInfo({ token }) @@ -209,7 +209,7 @@ export class UsersCommand extends AbstractCommand { const password = 'password' await this.create({ username, password }) - return this.server.loginCommand.getAccessToken({ username, password }) + return this.server.login.getAccessToken({ username, password }) } register (options: OverrideCommandOptions & { diff --git a/shared/extra-utils/videos/channels.ts b/shared/extra-utils/videos/channels.ts index 9e7ec565d..81e818094 100644 --- a/shared/extra-utils/videos/channels.ts +++ b/shared/extra-utils/videos/channels.ts @@ -4,8 +4,8 @@ function setDefaultVideoChannel (servers: ServerInfo[]) { const tasks: Promise[] = [] for (const server of servers) { - const p = server.usersCommand.getMyInfo() - .then(user => { server.videoChannel = user.videoChannels[0] }) + const p = server.users.getMyInfo() + .then(user => { server.store.channel = user.videoChannels[0] }) tasks.push(p) } diff --git a/shared/extra-utils/videos/live-command.ts b/shared/extra-utils/videos/live-command.ts index 5adf601cc..fd66c9924 100644 --- a/shared/extra-utils/videos/live-command.ts +++ b/shared/extra-utils/videos/live-command.ts @@ -114,7 +114,7 @@ export class LiveCommand extends AbstractCommand { const { resolution, segment, videoUUID } = options const segmentName = `${resolution}-00000${segment}.ts` - return this.server.serversCommand.waitUntilLog(`${videoUUID}/${segmentName}`, 2, false) + return this.server.servers.waitUntilLog(`${videoUUID}/${segmentName}`, 2, false) } async waitUntilSaved (options: OverrideCommandOptions & { @@ -123,7 +123,7 @@ export class LiveCommand extends AbstractCommand { let video: VideoDetails do { - video = await this.server.videosCommand.getWithToken({ token: options.token, id: options.videoId }) + video = await this.server.videos.getWithToken({ token: options.token, id: options.videoId }) await wait(500) } while (video.isLive === true && video.state.id !== VideoState.PUBLISHED) @@ -132,7 +132,7 @@ export class LiveCommand extends AbstractCommand { async countPlaylists (options: OverrideCommandOptions & { videoUUID: string }) { - const basePath = this.server.serversCommand.buildDirectory('streaming-playlists') + const basePath = this.server.servers.buildDirectory('streaming-playlists') const hlsPath = join(basePath, 'hls', options.videoUUID) const files = await readdir(hlsPath) @@ -147,7 +147,7 @@ export class LiveCommand extends AbstractCommand { let video: VideoDetails do { - video = await this.server.videosCommand.getWithToken({ token: options.token, id: options.videoId }) + video = await this.server.videos.getWithToken({ token: options.token, id: options.videoId }) await wait(500) } while (video.state.id !== options.state) diff --git a/shared/extra-utils/videos/live.ts b/shared/extra-utils/videos/live.ts index 0efcc2883..353595811 100644 --- a/shared/extra-utils/videos/live.ts +++ b/shared/extra-utils/videos/live.ts @@ -72,12 +72,12 @@ async function stopFfmpeg (command: ffmpeg.FfmpegCommand) { async function waitUntilLivePublishedOnAllServers (servers: ServerInfo[], videoId: string) { for (const server of servers) { - await server.liveCommand.waitUntilPublished({ videoId }) + await server.live.waitUntilPublished({ videoId }) } } async function checkLiveCleanup (server: ServerInfo, videoUUID: string, resolutions: number[] = []) { - const basePath = server.serversCommand.buildDirectory('streaming-playlists') + const basePath = server.servers.buildDirectory('streaming-playlists') const hlsPath = join(basePath, 'hls', videoUUID) if (resolutions.length === 0) { diff --git a/shared/extra-utils/videos/playlists-command.ts b/shared/extra-utils/videos/playlists-command.ts index 75c8f2433..cbfc7e10f 100644 --- a/shared/extra-utils/videos/playlists-command.ts +++ b/shared/extra-utils/videos/playlists-command.ts @@ -184,7 +184,7 @@ export class PlaylistsCommand extends AbstractCommand { const attributes = { ...options.attributes, - videoId: await this.server.videosCommand.getId({ ...options, uuid: options.attributes.videoId }) + videoId: await this.server.videos.getId({ ...options, uuid: options.attributes.videoId }) } const path = '/api/v1/video-playlists/' + options.playlistId + '/videos' diff --git a/shared/extra-utils/videos/streaming-playlists.ts b/shared/extra-utils/videos/streaming-playlists.ts index 0324c739a..e8fd2f232 100644 --- a/shared/extra-utils/videos/streaming-playlists.ts +++ b/shared/extra-utils/videos/streaming-playlists.ts @@ -13,7 +13,7 @@ async function checkSegmentHash (options: { hlsPlaylist: VideoStreamingPlaylist }) { const { server, baseUrlPlaylist, baseUrlSegment, videoUUID, resolution, hlsPlaylist } = options - const command = server.streamingPlaylistsCommand + const command = server.streamingPlaylists const playlist = await command.get({ url: `${baseUrlPlaylist}/${videoUUID}/${resolution}.m3u8` }) @@ -43,7 +43,7 @@ async function checkLiveSegmentHash (options: { hlsPlaylist: VideoStreamingPlaylist }) { const { server, baseUrlSegment, videoUUID, segmentName, hlsPlaylist } = options - const command = server.streamingPlaylistsCommand + const command = server.streamingPlaylists const segmentBody = await command.getSegment({ url: `${baseUrlSegment}/${videoUUID}/${segmentName}` }) const shaBody = await command.getSegmentSha256({ url: hlsPlaylist.segmentsSha256Url }) @@ -58,7 +58,7 @@ async function checkResolutionsInMasterPlaylist (options: { }) { const { server, playlistUrl, resolutions } = options - const masterPlaylist = await server.streamingPlaylistsCommand.get({ url: playlistUrl }) + const masterPlaylist = await server.streamingPlaylists.get({ url: playlistUrl }) for (const resolution of resolutions) { const reg = new RegExp( diff --git a/shared/extra-utils/videos/videos-command.ts b/shared/extra-utils/videos/videos-command.ts index 574705474..5556cddf6 100644 --- a/shared/extra-utils/videos/videos-command.ts +++ b/shared/extra-utils/videos/videos-command.ts @@ -336,7 +336,7 @@ export class VideosCommand extends AbstractCommand { let defaultChannelId = 1 try { - const { videoChannels } = await this.server.usersCommand.getMyInfo({ token: options.token }) + const { videoChannels } = await this.server.users.getMyInfo({ token: options.token }) defaultChannelId = videoChannels[0].id } catch (e) { /* empty */ } diff --git a/shared/extra-utils/videos/videos.ts b/shared/extra-utils/videos/videos.ts index 19f0df8b8..86f49384d 100644 --- a/shared/extra-utils/videos/videos.ts +++ b/shared/extra-utils/videos/videos.ts @@ -27,7 +27,7 @@ async function checkVideoFilesWereRemoved ( ] ) { for (const directory of directories) { - const directoryPath = server.serversCommand.buildDirectory(directory) + const directoryPath = server.servers.buildDirectory(directory) const directoryExists = await pathExists(directoryPath) if (directoryExists === false) continue @@ -47,8 +47,8 @@ function checkUploadVideoParam ( mode: 'legacy' | 'resumable' = 'legacy' ) { return mode === 'legacy' - ? server.videosCommand.buildLegacyUpload({ token, attributes, expectedStatus }) - : server.videosCommand.buildResumeUpload({ token, attributes, expectedStatus }) + ? server.videos.buildLegacyUpload({ token, attributes, expectedStatus }) + : server.videos.buildResumeUpload({ token, attributes, expectedStatus }) } async function completeVideoCheck ( @@ -131,7 +131,7 @@ async function completeVideoCheck ( expect(video.originallyPublishedAt).to.be.null } - const videoDetails = await server.videosCommand.get({ id: video.uuid }) + const videoDetails = await server.videos.get({ id: video.uuid }) expect(videoDetails.files).to.have.lengthOf(attributes.files.length) expect(videoDetails.tags).to.deep.equal(attributes.tags) @@ -202,7 +202,7 @@ async function uploadRandomVideoOnServers ( additionalParams?: VideoEdit & { prefixName?: string } ) { const server = servers.find(s => s.serverNumber === serverNumber) - const res = await server.videosCommand.randomUpload({ wait: false, ...additionalParams }) + const res = await server.videos.randomUpload({ wait: false, ...additionalParams }) await waitJobs(servers) -- cgit v1.2.3 From 254d3579f5338f5fd775c17d15cdfc37078bcfb4 Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Fri, 16 Jul 2021 09:47:51 +0200 Subject: Use an object to represent a server --- scripts/benchmark.ts | 6 +- server/tests/api/activitypub/cleaner.ts | 8 +- server/tests/api/activitypub/client.ts | 8 +- server/tests/api/activitypub/fetch.ts | 6 +- server/tests/api/activitypub/refresher.ts | 11 +- server/tests/api/activitypub/security.ts | 17 +- server/tests/api/check-params/abuses.ts | 12 +- server/tests/api/check-params/accounts.ts | 8 +- server/tests/api/check-params/blocklist.ts | 10 +- server/tests/api/check-params/bulk.ts | 8 +- server/tests/api/check-params/config.ts | 8 +- server/tests/api/check-params/contact-form.ts | 10 +- server/tests/api/check-params/custom-pages.ts | 8 +- server/tests/api/check-params/debug.ts | 8 +- server/tests/api/check-params/follows.ts | 8 +- server/tests/api/check-params/jobs.ts | 8 +- server/tests/api/check-params/live.ts | 8 +- server/tests/api/check-params/logs.ts | 8 +- server/tests/api/check-params/plugins.ts | 8 +- server/tests/api/check-params/redundancy.ts | 8 +- server/tests/api/check-params/search.ts | 10 +- server/tests/api/check-params/services.ts | 10 +- server/tests/api/check-params/upload-quota.ts | 8 +- .../tests/api/check-params/user-notifications.ts | 8 +- .../tests/api/check-params/user-subscriptions.ts | 8 +- server/tests/api/check-params/users.ts | 15 +- server/tests/api/check-params/video-blacklist.ts | 8 +- server/tests/api/check-params/video-captions.ts | 8 +- server/tests/api/check-params/video-channels.ts | 8 +- server/tests/api/check-params/video-comments.ts | 8 +- server/tests/api/check-params/video-imports.ts | 8 +- server/tests/api/check-params/video-playlists.ts | 8 +- server/tests/api/check-params/videos-filter.ts | 10 +- server/tests/api/check-params/videos-history.ts | 8 +- server/tests/api/check-params/videos-overviews.ts | 6 +- server/tests/api/check-params/videos.ts | 8 +- server/tests/api/live/live-constraints.ts | 8 +- server/tests/api/live/live-permanent.ts | 8 +- server/tests/api/live/live-save-replay.ts | 8 +- server/tests/api/live/live-socket-messages.ts | 8 +- server/tests/api/live/live-views.ts | 8 +- server/tests/api/live/live.ts | 11 +- server/tests/api/moderation/abuses.ts | 12 +- .../tests/api/moderation/blocklist-notification.ts | 8 +- server/tests/api/moderation/blocklist.ts | 16 +- server/tests/api/moderation/video-blacklist.ts | 13 +- .../tests/api/notifications/admin-notifications.ts | 4 +- .../api/notifications/comments-notifications.ts | 4 +- .../api/notifications/moderation-notifications.ts | 4 +- .../tests/api/notifications/notifications-api.ts | 4 +- .../tests/api/notifications/user-notifications.ts | 4 +- server/tests/api/redundancy/manage-redundancy.ts | 8 +- .../tests/api/redundancy/redundancy-constraints.ts | 19 +- server/tests/api/redundancy/redundancy.ts | 33 +- .../search/search-activitypub-video-channels.ts | 8 +- .../search/search-activitypub-video-playlists.ts | 8 +- .../tests/api/search/search-activitypub-videos.ts | 8 +- server/tests/api/search/search-channels.ts | 6 +- server/tests/api/search/search-index.ts | 6 +- server/tests/api/search/search-playlists.ts | 8 +- server/tests/api/search/search-videos.ts | 8 +- server/tests/api/server/auto-follows.ts | 14 +- server/tests/api/server/bulk.ts | 8 +- server/tests/api/server/config.ts | 15 +- server/tests/api/server/contact-form.ts | 16 +- server/tests/api/server/email.ts | 6 +- server/tests/api/server/follow-constraints.ts | 6 +- server/tests/api/server/follows-moderation.ts | 12 +- server/tests/api/server/follows.ts | 8 +- server/tests/api/server/handle-down.ts | 13 +- server/tests/api/server/homepage.ts | 13 +- server/tests/api/server/jobs.ts | 8 +- server/tests/api/server/logs.ts | 11 +- server/tests/api/server/no-client.ts | 8 +- server/tests/api/server/plugins.ts | 13 +- server/tests/api/server/reverse-proxy.ts | 6 +- server/tests/api/server/services.ts | 6 +- server/tests/api/server/stats.ts | 8 +- server/tests/api/server/tracker.ts | 10 +- server/tests/api/users/user-subscriptions.ts | 8 +- server/tests/api/users/users-multiple-servers.ts | 8 +- server/tests/api/users/users-verification.ts | 6 +- server/tests/api/users/users.ts | 13 +- server/tests/api/videos/audio-only.ts | 6 +- server/tests/api/videos/multiple-servers.ts | 8 +- server/tests/api/videos/resumable-upload.ts | 8 +- server/tests/api/videos/single-server.ts | 8 +- server/tests/api/videos/video-captions.ts | 8 +- server/tests/api/videos/video-change-ownership.ts | 14 +- server/tests/api/videos/video-channels.ts | 10 +- server/tests/api/videos/video-comments.ts | 8 +- server/tests/api/videos/video-description.ts | 6 +- server/tests/api/videos/video-hls.ts | 10 +- server/tests/api/videos/video-imports.ts | 12 +- server/tests/api/videos/video-nsfw.ts | 6 +- .../tests/api/videos/video-playlist-thumbnails.ts | 12 +- server/tests/api/videos/video-playlists.ts | 18 +- server/tests/api/videos/video-privacy.ts | 8 +- server/tests/api/videos/video-schedule-update.ts | 8 +- server/tests/api/videos/video-transcoder.ts | 10 +- server/tests/api/videos/videos-filter.ts | 10 +- server/tests/api/videos/videos-history.ts | 13 +- server/tests/api/videos/videos-overview.ts | 6 +- server/tests/api/videos/videos-views-cleaner.ts | 13 +- server/tests/cli/create-import-video-file-job.ts | 6 +- server/tests/cli/create-transcoding-job.ts | 8 +- server/tests/cli/optimize-old-videos.ts | 8 +- server/tests/cli/peertube.ts | 14 +- server/tests/cli/plugins.ts | 13 +- server/tests/cli/prune-storage.ts | 14 +- server/tests/cli/regenerate-thumbnails.ts | 10 +- server/tests/cli/reset-password.ts | 6 +- server/tests/cli/update-host.ts | 11 +- server/tests/client.ts | 8 +- server/tests/external-plugins/auth-ldap.ts | 6 +- server/tests/external-plugins/auto-block-videos.ts | 13 +- server/tests/external-plugins/auto-mute.ts | 11 +- server/tests/feeds/feeds.ts | 14 +- server/tests/misc-endpoints.ts | 6 +- server/tests/plugins/action-hooks.ts | 11 +- server/tests/plugins/external-auth.ts | 10 +- server/tests/plugins/filter-hooks.ts | 8 +- server/tests/plugins/html-injection.ts | 8 +- server/tests/plugins/id-and-pass-auth.ts | 6 +- server/tests/plugins/plugin-helpers.ts | 10 +- server/tests/plugins/plugin-router.ts | 8 +- server/tests/plugins/plugin-storage.ts | 13 +- server/tests/plugins/plugin-transcoding.ts | 12 +- server/tests/plugins/plugin-unloading.ts | 13 +- server/tests/plugins/translations.ts | 7 +- server/tests/plugins/video-constants.ts | 6 +- server/tools/cli.ts | 15 +- server/tools/peertube-import-videos.ts | 4 +- server/tools/test-live.ts | 8 +- shared/extra-utils/miscs/checks.ts | 4 +- shared/extra-utils/miscs/webtorrent.ts | 4 +- shared/extra-utils/server/directories.ts | 6 +- shared/extra-utils/server/follows-command.ts | 6 +- shared/extra-utils/server/follows.ts | 4 +- shared/extra-utils/server/index.ts | 1 + shared/extra-utils/server/jobs.ts | 10 +- shared/extra-utils/server/plugins.ts | 4 +- shared/extra-utils/server/server.ts | 376 +++++++++++++++++++ shared/extra-utils/server/servers-command.ts | 2 +- shared/extra-utils/server/servers.ts | 400 +-------------------- shared/extra-utils/shared/abstract-command.ts | 4 +- shared/extra-utils/users/accounts.ts | 4 +- shared/extra-utils/users/login.ts | 4 +- shared/extra-utils/users/notifications.ts | 7 +- shared/extra-utils/videos/channels.ts | 4 +- shared/extra-utils/videos/live.ts | 6 +- shared/extra-utils/videos/streaming-playlists.ts | 8 +- shared/extra-utils/videos/videos-command.ts | 4 +- shared/extra-utils/videos/videos.ts | 10 +- 154 files changed, 1066 insertions(+), 1054 deletions(-) create mode 100644 shared/extra-utils/server/server.ts diff --git a/scripts/benchmark.ts b/scripts/benchmark.ts index 1d980063b..071c4dea7 100644 --- a/scripts/benchmark.ts +++ b/scripts/benchmark.ts @@ -1,12 +1,12 @@ import * as autocannon from 'autocannon' import { writeJson } from 'fs-extra' -import { flushAndRunServer, killallServers, ServerInfo, setAccessTokensToServers } from '@shared/extra-utils' +import { createSingleServer, killallServers, PeerTubeServer, setAccessTokensToServers } from '@shared/extra-utils' import { Video, VideoPrivacy } from '@shared/models' import { registerTSPaths } from '../server/helpers/register-ts-paths' registerTSPaths() -let server: ServerInfo +let server: PeerTubeServer let video: Video let threadId: number @@ -188,7 +188,7 @@ function runBenchmark (options: { } async function prepare () { - server = await flushAndRunServer(1, { + server = await createSingleServer(1, { rates_limit: { api: { max: 5_000_000 diff --git a/server/tests/api/activitypub/cleaner.ts b/server/tests/api/activitypub/cleaner.ts index 1421824da..a5ce449f3 100644 --- a/server/tests/api/activitypub/cleaner.ts +++ b/server/tests/api/activitypub/cleaner.ts @@ -5,8 +5,8 @@ import * as chai from 'chai' import { cleanupTests, doubleFollow, - flushAndRunMultipleServers, - ServerInfo, + createMultipleServers, + PeerTubeServer, setAccessTokensToServers, wait, waitJobs @@ -15,7 +15,7 @@ import { const expect = chai.expect describe('Test AP cleaner', function () { - let servers: ServerInfo[] = [] + let servers: PeerTubeServer[] = [] let videoUUID1: string let videoUUID2: string let videoUUID3: string @@ -30,7 +30,7 @@ describe('Test AP cleaner', function () { videos: { cleanup_remote_interactions: true } } } - servers = await flushAndRunMultipleServers(3, config) + servers = await createMultipleServers(3, config) // Get the access tokens await setAccessTokensToServers(servers) diff --git a/server/tests/api/activitypub/client.ts b/server/tests/api/activitypub/client.ts index 5845045a3..720231f02 100644 --- a/server/tests/api/activitypub/client.ts +++ b/server/tests/api/activitypub/client.ts @@ -6,9 +6,9 @@ import { HttpStatusCode } from '@shared/core-utils' import { cleanupTests, doubleFollow, - flushAndRunMultipleServers, + createMultipleServers, makeActivityPubGetRequest, - ServerInfo, + PeerTubeServer, setAccessTokensToServers, setDefaultVideoChannel } from '@shared/extra-utils' @@ -17,7 +17,7 @@ import { VideoPlaylistPrivacy } from '@shared/models' const expect = chai.expect describe('Test activitypub', function () { - let servers: ServerInfo[] = [] + let servers: PeerTubeServer[] = [] let video: { id: number, uuid: string, shortUUID: string } let playlist: { id: number, uuid: string, shortUUID: string } @@ -62,7 +62,7 @@ describe('Test activitypub', function () { before(async function () { this.timeout(30000) - servers = await flushAndRunMultipleServers(2) + servers = await createMultipleServers(2) await setAccessTokensToServers(servers) await setDefaultVideoChannel(servers) diff --git a/server/tests/api/activitypub/fetch.ts b/server/tests/api/activitypub/fetch.ts index 34694a773..ddfe6cfe0 100644 --- a/server/tests/api/activitypub/fetch.ts +++ b/server/tests/api/activitypub/fetch.ts @@ -2,19 +2,19 @@ import 'mocha' import * as chai from 'chai' -import { cleanupTests, doubleFollow, flushAndRunMultipleServers, ServerInfo, setAccessTokensToServers, waitJobs } from '@shared/extra-utils' +import { cleanupTests, doubleFollow, createMultipleServers, PeerTubeServer, setAccessTokensToServers, waitJobs } from '@shared/extra-utils' const expect = chai.expect describe('Test ActivityPub fetcher', function () { - let servers: ServerInfo[] + let servers: PeerTubeServer[] // --------------------------------------------------------------- before(async function () { this.timeout(60000) - servers = await flushAndRunMultipleServers(3) + servers = await createMultipleServers(3) // Get the access tokens await setAccessTokensToServers(servers) diff --git a/server/tests/api/activitypub/refresher.ts b/server/tests/api/activitypub/refresher.ts index d2f71e857..bbec0d309 100644 --- a/server/tests/api/activitypub/refresher.ts +++ b/server/tests/api/activitypub/refresher.ts @@ -5,10 +5,9 @@ import { HttpStatusCode } from '@shared/core-utils' import { cleanupTests, doubleFollow, - flushAndRunMultipleServers, + createMultipleServers, killallServers, - reRunServer, - ServerInfo, + PeerTubeServer, setAccessTokensToServers, setDefaultVideoChannel, wait, @@ -17,7 +16,7 @@ import { import { VideoPlaylistPrivacy } from '@shared/models' describe('Test AP refresher', function () { - let servers: ServerInfo[] = [] + let servers: PeerTubeServer[] = [] let videoUUID1: string let videoUUID2: string let videoUUID3: string @@ -27,7 +26,7 @@ describe('Test AP refresher', function () { before(async function () { this.timeout(60000) - servers = await flushAndRunMultipleServers(2, { transcoding: { enabled: false } }) + servers = await createMultipleServers(2, { transcoding: { enabled: false } }) // Get the access tokens await setAccessTokensToServers(servers) @@ -95,7 +94,7 @@ describe('Test AP refresher', function () { // The refresh should fail await waitJobs([ servers[0] ]) - await reRunServer(servers[1]) + await servers[1].run() await servers[0].videos.get({ id: videoUUID3 }) }) diff --git a/server/tests/api/activitypub/security.ts b/server/tests/api/activitypub/security.ts index ab0eb256e..c173648b3 100644 --- a/server/tests/api/activitypub/security.ts +++ b/server/tests/api/activitypub/security.ts @@ -7,10 +7,9 @@ import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-c import { buildAbsoluteFixturePath, cleanupTests, - flushAndRunMultipleServers, + createMultipleServers, killallServers, - reRunServer, - ServerInfo, + PeerTubeServer, wait } from '../../../../shared/extra-utils' import { makeFollowRequest, makePOSTAPRequest } from '../../../../shared/extra-utils/requests/activitypub' @@ -20,7 +19,7 @@ import { buildGlobalHeaders } from '../../../lib/job-queue/handlers/utils/activi const expect = chai.expect -function setKeysOfServer (onServer: ServerInfo, ofServer: ServerInfo, publicKey: string, privateKey: string) { +function setKeysOfServer (onServer: PeerTubeServer, ofServer: PeerTubeServer, publicKey: string, privateKey: string) { const url = 'http://localhost:' + ofServer.port + '/accounts/peertube' return Promise.all([ @@ -29,7 +28,7 @@ function setKeysOfServer (onServer: ServerInfo, ofServer: ServerInfo, publicKey: ]) } -function setUpdatedAtOfServer (onServer: ServerInfo, ofServer: ServerInfo, updatedAt: string) { +function setUpdatedAtOfServer (onServer: PeerTubeServer, ofServer: PeerTubeServer, updatedAt: string) { const url = 'http://localhost:' + ofServer.port + '/accounts/peertube' return Promise.all([ @@ -38,7 +37,7 @@ function setUpdatedAtOfServer (onServer: ServerInfo, ofServer: ServerInfo, updat ]) } -function getAnnounceWithoutContext (server: ServerInfo) { +function getAnnounceWithoutContext (server: PeerTubeServer) { const json = require(buildAbsoluteFixturePath('./ap-json/peertube/announce-without-context.json')) const result: typeof json = {} @@ -54,7 +53,7 @@ function getAnnounceWithoutContext (server: ServerInfo) { } describe('Test ActivityPub security', function () { - let servers: ServerInfo[] + let servers: PeerTubeServer[] let url: string const keys = require(buildAbsoluteFixturePath('./ap-json/peertube/keys.json')) @@ -72,7 +71,7 @@ describe('Test ActivityPub security', function () { before(async function () { this.timeout(60000) - servers = await flushAndRunMultipleServers(3) + servers = await createMultipleServers(3) url = servers[0].url + '/inbox' @@ -172,7 +171,7 @@ describe('Test ActivityPub security', function () { // Invalid peertube actor cache await killallServers([ servers[1] ]) - await reRunServer(servers[1]) + await servers[1].run() const body = activityPubContextify(getAnnounceWithoutContext(servers[1])) const headers = buildGlobalHeaders(body) diff --git a/server/tests/api/check-params/abuses.ts b/server/tests/api/check-params/abuses.ts index 7a6790ba8..62811f932 100644 --- a/server/tests/api/check-params/abuses.ts +++ b/server/tests/api/check-params/abuses.ts @@ -9,10 +9,10 @@ import { checkBadStartPagination, cleanupTests, doubleFollow, - flushAndRunServer, + createSingleServer, makeGetRequest, makePostBodyRequest, - ServerInfo, + PeerTubeServer, setAccessTokensToServers, waitJobs } from '@shared/extra-utils' @@ -21,7 +21,7 @@ import { AbuseCreate, AbuseState } from '@shared/models' describe('Test abuses API validators', function () { const basePath = '/api/v1/abuses/' - let server: ServerInfo + let server: PeerTubeServer let userToken = '' let userToken2 = '' @@ -35,7 +35,7 @@ describe('Test abuses API validators', function () { before(async function () { this.timeout(30000) - server = await flushAndRunServer(1) + server = await createSingleServer(1) await setAccessTokensToServers([ server ]) @@ -404,12 +404,12 @@ describe('Test abuses API validators', function () { describe('When trying to manage messages of a remote abuse', function () { let remoteAbuseId: number - let anotherServer: ServerInfo + let anotherServer: PeerTubeServer before(async function () { this.timeout(50000) - anotherServer = await flushAndRunServer(2) + anotherServer = await createSingleServer(2) await setAccessTokensToServers([ anotherServer ]) await doubleFollow(anotherServer, server) diff --git a/server/tests/api/check-params/accounts.ts b/server/tests/api/check-params/accounts.ts index 223322626..e866593db 100644 --- a/server/tests/api/check-params/accounts.ts +++ b/server/tests/api/check-params/accounts.ts @@ -7,20 +7,20 @@ import { checkBadSortPagination, checkBadStartPagination, cleanupTests, - flushAndRunServer, - ServerInfo + createSingleServer, + PeerTubeServer } from '@shared/extra-utils' describe('Test accounts API validators', function () { const path = '/api/v1/accounts/' - let server: ServerInfo + let server: PeerTubeServer // --------------------------------------------------------------- before(async function () { this.timeout(30000) - server = await flushAndRunServer(1) + server = await createSingleServer(1) }) describe('When listing accounts', function () { diff --git a/server/tests/api/check-params/blocklist.ts b/server/tests/api/check-params/blocklist.ts index 14e45e503..b2a1cc4e2 100644 --- a/server/tests/api/check-params/blocklist.ts +++ b/server/tests/api/check-params/blocklist.ts @@ -5,11 +5,11 @@ import 'mocha' import { cleanupTests, doubleFollow, - flushAndRunMultipleServers, + createMultipleServers, makeDeleteRequest, makeGetRequest, makePostBodyRequest, - ServerInfo, + PeerTubeServer, setAccessTokensToServers } from '../../../../shared/extra-utils' import { @@ -20,14 +20,14 @@ import { import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' describe('Test blocklist API validators', function () { - let servers: ServerInfo[] - let server: ServerInfo + let servers: PeerTubeServer[] + let server: PeerTubeServer let userAccessToken: string before(async function () { this.timeout(60000) - servers = await flushAndRunMultipleServers(2) + servers = await createMultipleServers(2) await setAccessTokensToServers(servers) server = servers[0] diff --git a/server/tests/api/check-params/bulk.ts b/server/tests/api/check-params/bulk.ts index 69ff7dd96..a660c3d80 100644 --- a/server/tests/api/check-params/bulk.ts +++ b/server/tests/api/check-params/bulk.ts @@ -3,15 +3,15 @@ import 'mocha' import { cleanupTests, - flushAndRunServer, - ServerInfo, + createSingleServer, + PeerTubeServer, setAccessTokensToServers } from '../../../../shared/extra-utils' import { makePostBodyRequest } from '../../../../shared/extra-utils/requests/requests' import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' describe('Test bulk API validators', function () { - let server: ServerInfo + let server: PeerTubeServer let userAccessToken: string // --------------------------------------------------------------- @@ -19,7 +19,7 @@ describe('Test bulk API validators', function () { before(async function () { this.timeout(120000) - server = await flushAndRunServer(1) + server = await createSingleServer(1) await setAccessTokensToServers([ server ]) const user = { username: 'user1', password: 'password' } diff --git a/server/tests/api/check-params/config.ts b/server/tests/api/check-params/config.ts index 6fd26864e..1756d58ee 100644 --- a/server/tests/api/check-params/config.ts +++ b/server/tests/api/check-params/config.ts @@ -5,18 +5,18 @@ import { omit } from 'lodash' import { HttpStatusCode } from '@shared/core-utils' import { cleanupTests, - flushAndRunServer, + createSingleServer, makeDeleteRequest, makeGetRequest, makePutBodyRequest, - ServerInfo, + PeerTubeServer, setAccessTokensToServers } from '@shared/extra-utils' import { CustomConfig } from '@shared/models' describe('Test config API validators', function () { const path = '/api/v1/config/custom' - let server: ServerInfo + let server: PeerTubeServer let userAccessToken: string const updateParams: CustomConfig = { instance: { @@ -197,7 +197,7 @@ describe('Test config API validators', function () { before(async function () { this.timeout(30000) - server = await flushAndRunServer(1) + server = await createSingleServer(1) await setAccessTokensToServers([ server ]) diff --git a/server/tests/api/check-params/contact-form.ts b/server/tests/api/check-params/contact-form.ts index d2541777f..8c2b2a84b 100644 --- a/server/tests/api/check-params/contact-form.ts +++ b/server/tests/api/check-params/contact-form.ts @@ -2,11 +2,11 @@ import 'mocha' import { HttpStatusCode } from '@shared/core-utils' -import { cleanupTests, flushAndRunServer, killallServers, MockSmtpServer, reRunServer, ServerInfo } from '@shared/extra-utils' +import { cleanupTests, createSingleServer, killallServers, MockSmtpServer, PeerTubeServer } from '@shared/extra-utils' import { ContactFormCommand } from '@shared/extra-utils/server' describe('Test contact form API validators', function () { - let server: ServerInfo + let server: PeerTubeServer const emails: object[] = [] const defaultBody = { fromName: 'super name', @@ -25,7 +25,7 @@ describe('Test contact form API validators', function () { emailPort = await MockSmtpServer.Instance.collectEmails(emails) // Email is disabled - server = await flushAndRunServer(1) + server = await createSingleServer(1) command = server.contactForm }) @@ -39,7 +39,7 @@ describe('Test contact form API validators', function () { await killallServers([ server ]) // Contact form is disabled - await reRunServer(server, { smtp: { hostname: 'localhost', port: emailPort }, contact_form: { enabled: false } }) + await server.run({ smtp: { hostname: 'localhost', port: emailPort }, contact_form: { enabled: false } }) await command.send({ ...defaultBody, expectedStatus: HttpStatusCode.CONFLICT_409 }) }) @@ -49,7 +49,7 @@ describe('Test contact form API validators', function () { await killallServers([ server ]) // Email & contact form enabled - await reRunServer(server, { smtp: { hostname: 'localhost', port: emailPort } }) + await server.run({ smtp: { hostname: 'localhost', port: emailPort } }) await command.send({ ...defaultBody, fromEmail: 'badEmail', expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) await command.send({ ...defaultBody, fromEmail: 'badEmail@', expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) diff --git a/server/tests/api/check-params/custom-pages.ts b/server/tests/api/check-params/custom-pages.ts index 3d84fb3e6..043505e32 100644 --- a/server/tests/api/check-params/custom-pages.ts +++ b/server/tests/api/check-params/custom-pages.ts @@ -4,8 +4,8 @@ import 'mocha' import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' import { cleanupTests, - flushAndRunServer, - ServerInfo, + createSingleServer, + PeerTubeServer, setAccessTokensToServers } from '../../../../shared/extra-utils' import { makeGetRequest, makePutBodyRequest } from '../../../../shared/extra-utils/requests/requests' @@ -13,7 +13,7 @@ import { makeGetRequest, makePutBodyRequest } from '../../../../shared/extra-uti describe('Test custom pages validators', function () { const path = '/api/v1/custom-pages/homepage/instance' - let server: ServerInfo + let server: PeerTubeServer let userAccessToken: string // --------------------------------------------------------------- @@ -21,7 +21,7 @@ describe('Test custom pages validators', function () { before(async function () { this.timeout(120000) - server = await flushAndRunServer(1) + server = await createSingleServer(1) await setAccessTokensToServers([ server ]) const user = { username: 'user1', password: 'password' } diff --git a/server/tests/api/check-params/debug.ts b/server/tests/api/check-params/debug.ts index 609f9566e..9c13e9daf 100644 --- a/server/tests/api/check-params/debug.ts +++ b/server/tests/api/check-params/debug.ts @@ -4,8 +4,8 @@ import 'mocha' import { cleanupTests, - flushAndRunServer, - ServerInfo, + createSingleServer, + PeerTubeServer, setAccessTokensToServers } from '../../../../shared/extra-utils' import { makeGetRequest } from '../../../../shared/extra-utils/requests/requests' @@ -13,7 +13,7 @@ import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-c describe('Test debug API validators', function () { const path = '/api/v1/server/debug' - let server: ServerInfo + let server: PeerTubeServer let userAccessToken = '' // --------------------------------------------------------------- @@ -21,7 +21,7 @@ describe('Test debug API validators', function () { before(async function () { this.timeout(120000) - server = await flushAndRunServer(1) + server = await createSingleServer(1) await setAccessTokensToServers([ server ]) diff --git a/server/tests/api/check-params/follows.ts b/server/tests/api/check-params/follows.ts index fae3712ce..0fd2b4925 100644 --- a/server/tests/api/check-params/follows.ts +++ b/server/tests/api/check-params/follows.ts @@ -4,10 +4,10 @@ import 'mocha' import { cleanupTests, - flushAndRunServer, + createSingleServer, makeDeleteRequest, makeGetRequest, makePostBodyRequest, - ServerInfo, + PeerTubeServer, setAccessTokensToServers } from '../../../../shared/extra-utils' import { @@ -18,14 +18,14 @@ import { import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' describe('Test server follows API validators', function () { - let server: ServerInfo + let server: PeerTubeServer // --------------------------------------------------------------- before(async function () { this.timeout(30000) - server = await flushAndRunServer(1) + server = await createSingleServer(1) await setAccessTokensToServers([ server ]) }) diff --git a/server/tests/api/check-params/jobs.ts b/server/tests/api/check-params/jobs.ts index 3786e8612..a370ec2d3 100644 --- a/server/tests/api/check-params/jobs.ts +++ b/server/tests/api/check-params/jobs.ts @@ -4,8 +4,8 @@ import 'mocha' import { cleanupTests, - flushAndRunServer, - ServerInfo, + createSingleServer, + PeerTubeServer, setAccessTokensToServers } from '../../../../shared/extra-utils' import { @@ -18,7 +18,7 @@ import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-c describe('Test jobs API validators', function () { const path = '/api/v1/jobs/failed' - let server: ServerInfo + let server: PeerTubeServer let userAccessToken = '' // --------------------------------------------------------------- @@ -26,7 +26,7 @@ describe('Test jobs API validators', function () { before(async function () { this.timeout(120000) - server = await flushAndRunServer(1) + server = await createSingleServer(1) await setAccessTokensToServers([ server ]) diff --git a/server/tests/api/check-params/live.ts b/server/tests/api/check-params/live.ts index 20f27dd1d..eb5cdd1d8 100644 --- a/server/tests/api/check-params/live.ts +++ b/server/tests/api/check-params/live.ts @@ -6,12 +6,12 @@ import { HttpStatusCode } from '@shared/core-utils' import { buildAbsoluteFixturePath, cleanupTests, - flushAndRunServer, + createSingleServer, LiveCommand, makePostBodyRequest, makeUploadRequest, sendRTMPStream, - ServerInfo, + PeerTubeServer, setAccessTokensToServers, stopFfmpeg } from '@shared/extra-utils' @@ -19,7 +19,7 @@ import { VideoCreateResult, VideoPrivacy } from '@shared/models' describe('Test video lives API validator', function () { const path = '/api/v1/videos/live' - let server: ServerInfo + let server: PeerTubeServer let userAccessToken = '' let channelId: number let video: VideoCreateResult @@ -31,7 +31,7 @@ describe('Test video lives API validator', function () { before(async function () { this.timeout(30000) - server = await flushAndRunServer(1) + server = await createSingleServer(1) await setAccessTokensToServers([ server ]) diff --git a/server/tests/api/check-params/logs.ts b/server/tests/api/check-params/logs.ts index cf8f77959..2eb074007 100644 --- a/server/tests/api/check-params/logs.ts +++ b/server/tests/api/check-params/logs.ts @@ -4,8 +4,8 @@ import 'mocha' import { cleanupTests, - flushAndRunServer, - ServerInfo, + createSingleServer, + PeerTubeServer, setAccessTokensToServers } from '../../../../shared/extra-utils' import { makeGetRequest } from '../../../../shared/extra-utils/requests/requests' @@ -13,7 +13,7 @@ import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-c describe('Test logs API validators', function () { const path = '/api/v1/server/logs' - let server: ServerInfo + let server: PeerTubeServer let userAccessToken = '' // --------------------------------------------------------------- @@ -21,7 +21,7 @@ describe('Test logs API validators', function () { before(async function () { this.timeout(120000) - server = await flushAndRunServer(1) + server = await createSingleServer(1) await setAccessTokensToServers([ server ]) diff --git a/server/tests/api/check-params/plugins.ts b/server/tests/api/check-params/plugins.ts index d4b72c0f4..2b471ee7d 100644 --- a/server/tests/api/check-params/plugins.ts +++ b/server/tests/api/check-params/plugins.ts @@ -7,17 +7,17 @@ import { checkBadSortPagination, checkBadStartPagination, cleanupTests, - flushAndRunServer, + createSingleServer, makeGetRequest, makePostBodyRequest, makePutBodyRequest, - ServerInfo, + PeerTubeServer, setAccessTokensToServers } from '@shared/extra-utils' import { PeerTubePlugin, PluginType } from '@shared/models' describe('Test server plugins API validators', function () { - let server: ServerInfo + let server: PeerTubeServer let userAccessToken = null const npmPlugin = 'peertube-plugin-hello-world' @@ -33,7 +33,7 @@ describe('Test server plugins API validators', function () { before(async function () { this.timeout(30000) - server = await flushAndRunServer(1) + server = await createSingleServer(1) await setAccessTokensToServers([ server ]) diff --git a/server/tests/api/check-params/redundancy.ts b/server/tests/api/check-params/redundancy.ts index fca92fde4..18b98a0f9 100644 --- a/server/tests/api/check-params/redundancy.ts +++ b/server/tests/api/check-params/redundancy.ts @@ -9,18 +9,18 @@ import { checkBadStartPagination, cleanupTests, doubleFollow, - flushAndRunMultipleServers, + createMultipleServers, makeDeleteRequest, makeGetRequest, makePostBodyRequest, makePutBodyRequest, - ServerInfo, + PeerTubeServer, setAccessTokensToServers, waitJobs } from '../../../../shared/extra-utils' describe('Test server redundancy API validators', function () { - let servers: ServerInfo[] + let servers: PeerTubeServer[] let userAccessToken = null let videoIdLocal: number let videoRemote: VideoCreateResult @@ -30,7 +30,7 @@ describe('Test server redundancy API validators', function () { before(async function () { this.timeout(80000) - servers = await flushAndRunMultipleServers(2) + servers = await createMultipleServers(2) await setAccessTokensToServers(servers) await doubleFollow(servers[0], servers[1]) diff --git a/server/tests/api/check-params/search.ts b/server/tests/api/check-params/search.ts index 1acfa0922..43cd81af9 100644 --- a/server/tests/api/check-params/search.ts +++ b/server/tests/api/check-params/search.ts @@ -7,13 +7,13 @@ import { checkBadSortPagination, checkBadStartPagination, cleanupTests, - flushAndRunServer, + createSingleServer, makeGetRequest, - ServerInfo, + PeerTubeServer, setAccessTokensToServers } from '@shared/extra-utils' -function updateSearchIndex (server: ServerInfo, enabled: boolean, disableLocalSearch = false) { +function updateSearchIndex (server: PeerTubeServer, enabled: boolean, disableLocalSearch = false) { return server.config.updateCustomSubConfig({ newConfig: { search: { @@ -27,14 +27,14 @@ function updateSearchIndex (server: ServerInfo, enabled: boolean, disableLocalSe } describe('Test videos API validator', function () { - let server: ServerInfo + let server: PeerTubeServer // --------------------------------------------------------------- before(async function () { this.timeout(30000) - server = await flushAndRunServer(1) + server = await createSingleServer(1) await setAccessTokensToServers([ server ]) }) diff --git a/server/tests/api/check-params/services.ts b/server/tests/api/check-params/services.ts index 83435c24a..c623240b7 100644 --- a/server/tests/api/check-params/services.ts +++ b/server/tests/api/check-params/services.ts @@ -4,16 +4,16 @@ import 'mocha' import { HttpStatusCode } from '@shared/core-utils' import { cleanupTests, - flushAndRunServer, + createSingleServer, makeGetRequest, - ServerInfo, + PeerTubeServer, setAccessTokensToServers, setDefaultVideoChannel } from '@shared/extra-utils' import { VideoPlaylistPrivacy } from '@shared/models' describe('Test services API validators', function () { - let server: ServerInfo + let server: PeerTubeServer let playlistUUID: string // --------------------------------------------------------------- @@ -21,7 +21,7 @@ describe('Test services API validators', function () { before(async function () { this.timeout(60000) - server = await flushAndRunServer(1) + server = await createSingleServer(1) await setAccessTokensToServers([ server ]) await setDefaultVideoChannel([ server ]) @@ -120,7 +120,7 @@ describe('Test services API validators', function () { }) }) -function checkParamEmbed (server: ServerInfo, embedUrl: string, statusCodeExpected = HttpStatusCode.BAD_REQUEST_400, query = {}) { +function checkParamEmbed (server: PeerTubeServer, embedUrl: string, statusCodeExpected = HttpStatusCode.BAD_REQUEST_400, query = {}) { const path = '/services/oembed' return makeGetRequest({ diff --git a/server/tests/api/check-params/upload-quota.ts b/server/tests/api/check-params/upload-quota.ts index 4ca544790..2c73e6a19 100644 --- a/server/tests/api/check-params/upload-quota.ts +++ b/server/tests/api/check-params/upload-quota.ts @@ -5,9 +5,9 @@ import { expect } from 'chai' import { HttpStatusCode, randomInt } from '@shared/core-utils' import { cleanupTests, - flushAndRunServer, + createSingleServer, ImportsCommand, - ServerInfo, + PeerTubeServer, setAccessTokensToServers, setDefaultVideoChannel, VideosCommand, @@ -16,7 +16,7 @@ import { import { VideoImportState, VideoPrivacy } from '@shared/models' describe('Test upload quota', function () { - let server: ServerInfo + let server: PeerTubeServer let rootId: number let command: VideosCommand @@ -25,7 +25,7 @@ describe('Test upload quota', function () { before(async function () { this.timeout(30000) - server = await flushAndRunServer(1) + server = await createSingleServer(1) await setAccessTokensToServers([ server ]) await setDefaultVideoChannel([ server ]) diff --git a/server/tests/api/check-params/user-notifications.ts b/server/tests/api/check-params/user-notifications.ts index 913eca366..038c444b3 100644 --- a/server/tests/api/check-params/user-notifications.ts +++ b/server/tests/api/check-params/user-notifications.ts @@ -8,25 +8,25 @@ import { checkBadSortPagination, checkBadStartPagination, cleanupTests, - flushAndRunServer, + createSingleServer, makeGetRequest, makePostBodyRequest, makePutBodyRequest, - ServerInfo, + PeerTubeServer, setAccessTokensToServers, wait } from '@shared/extra-utils' import { UserNotificationSetting, UserNotificationSettingValue } from '@shared/models' describe('Test user notifications API validators', function () { - let server: ServerInfo + let server: PeerTubeServer // --------------------------------------------------------------- before(async function () { this.timeout(30000) - server = await flushAndRunServer(1) + server = await createSingleServer(1) await setAccessTokensToServers([ server ]) }) diff --git a/server/tests/api/check-params/user-subscriptions.ts b/server/tests/api/check-params/user-subscriptions.ts index 885ad68e4..22cf130c2 100644 --- a/server/tests/api/check-params/user-subscriptions.ts +++ b/server/tests/api/check-params/user-subscriptions.ts @@ -4,11 +4,11 @@ import 'mocha' import { cleanupTests, - flushAndRunServer, + createSingleServer, makeDeleteRequest, makeGetRequest, makePostBodyRequest, - ServerInfo, + PeerTubeServer, setAccessTokensToServers } from '../../../../shared/extra-utils' @@ -22,7 +22,7 @@ import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-c describe('Test user subscriptions API validators', function () { const path = '/api/v1/users/me/subscriptions' - let server: ServerInfo + let server: PeerTubeServer let userAccessToken = '' // --------------------------------------------------------------- @@ -30,7 +30,7 @@ describe('Test user subscriptions API validators', function () { before(async function () { this.timeout(30000) - server = await flushAndRunServer(1) + server = await createSingleServer(1) await setAccessTokensToServers([ server ]) diff --git a/server/tests/api/check-params/users.ts b/server/tests/api/check-params/users.ts index bce3f0774..c2c98f429 100644 --- a/server/tests/api/check-params/users.ts +++ b/server/tests/api/check-params/users.ts @@ -9,15 +9,14 @@ import { checkBadSortPagination, checkBadStartPagination, cleanupTests, - flushAndRunServer, + createSingleServer, killallServers, makeGetRequest, makePostBodyRequest, makePutBodyRequest, makeUploadRequest, MockSmtpServer, - reRunServer, - ServerInfo, + PeerTubeServer, setAccessTokensToServers, UsersCommand } from '@shared/extra-utils' @@ -29,8 +28,8 @@ describe('Test users API validators', function () { let rootId: number let moderatorId: number let video: VideoCreateResult - let server: ServerInfo - let serverWithRegistrationDisabled: ServerInfo + let server: PeerTubeServer + let serverWithRegistrationDisabled: PeerTubeServer let userToken = '' let moderatorToken = '' let emailPort: number @@ -48,8 +47,8 @@ describe('Test users API validators', function () { { const res = await Promise.all([ - flushAndRunServer(1, overrideConfig), - flushAndRunServer(2) + createSingleServer(1, overrideConfig), + createSingleServer(2) ]) server = res[0] @@ -196,7 +195,7 @@ describe('Test users API validators', function () { port: emailPort } } - await reRunServer(server, config) + await server.run(config) const fields = { ...baseCorrectParams, diff --git a/server/tests/api/check-params/video-blacklist.ts b/server/tests/api/check-params/video-blacklist.ts index 51609b982..b5d0e0778 100644 --- a/server/tests/api/check-params/video-blacklist.ts +++ b/server/tests/api/check-params/video-blacklist.ts @@ -10,17 +10,17 @@ import { checkBadStartPagination, cleanupTests, doubleFollow, - flushAndRunMultipleServers, + createMultipleServers, makePostBodyRequest, makePutBodyRequest, - ServerInfo, + PeerTubeServer, setAccessTokensToServers, waitJobs } from '@shared/extra-utils' import { VideoBlacklistType } from '@shared/models' describe('Test video blacklist API validators', function () { - let servers: ServerInfo[] + let servers: PeerTubeServer[] let notBlacklistedVideoId: string let remoteVideoUUID: string let userAccessToken1 = '' @@ -32,7 +32,7 @@ describe('Test video blacklist API validators', function () { before(async function () { this.timeout(120000) - servers = await flushAndRunMultipleServers(2) + servers = await createMultipleServers(2) await setAccessTokensToServers(servers) await doubleFollow(servers[0], servers[1]) diff --git a/server/tests/api/check-params/video-captions.ts b/server/tests/api/check-params/video-captions.ts index 913f894b9..26aab79e7 100644 --- a/server/tests/api/check-params/video-captions.ts +++ b/server/tests/api/check-params/video-captions.ts @@ -5,11 +5,11 @@ import { HttpStatusCode } from '@shared/core-utils' import { buildAbsoluteFixturePath, cleanupTests, - flushAndRunServer, + createSingleServer, makeDeleteRequest, makeGetRequest, makeUploadRequest, - ServerInfo, + PeerTubeServer, setAccessTokensToServers } from '@shared/extra-utils' import { VideoCreateResult } from '@shared/models' @@ -17,7 +17,7 @@ import { VideoCreateResult } from '@shared/models' describe('Test video captions API validator', function () { const path = '/api/v1/videos/' - let server: ServerInfo + let server: PeerTubeServer let userAccessToken: string let video: VideoCreateResult @@ -26,7 +26,7 @@ describe('Test video captions API validator', function () { before(async function () { this.timeout(30000) - server = await flushAndRunServer(1) + server = await createSingleServer(1) await setAccessTokensToServers([ server ]) diff --git a/server/tests/api/check-params/video-channels.ts b/server/tests/api/check-params/video-channels.ts index 8e6e32f20..62b8fa4f6 100644 --- a/server/tests/api/check-params/video-channels.ts +++ b/server/tests/api/check-params/video-channels.ts @@ -11,12 +11,12 @@ import { checkBadSortPagination, checkBadStartPagination, cleanupTests, - flushAndRunServer, + createSingleServer, makeGetRequest, makePostBodyRequest, makePutBodyRequest, makeUploadRequest, - ServerInfo, + PeerTubeServer, setAccessTokensToServers } from '@shared/extra-utils' import { VideoChannelUpdate } from '@shared/models' @@ -25,7 +25,7 @@ const expect = chai.expect describe('Test video channels API validator', function () { const videoChannelPath = '/api/v1/video-channels' - let server: ServerInfo + let server: PeerTubeServer let accessTokenUser: string let command: ChannelsCommand @@ -34,7 +34,7 @@ describe('Test video channels API validator', function () { before(async function () { this.timeout(30000) - server = await flushAndRunServer(1) + server = await createSingleServer(1) await setAccessTokensToServers([ server ]) diff --git a/server/tests/api/check-params/video-comments.ts b/server/tests/api/check-params/video-comments.ts index 44af9d7e3..ea5340b40 100644 --- a/server/tests/api/check-params/video-comments.ts +++ b/server/tests/api/check-params/video-comments.ts @@ -8,11 +8,11 @@ import { checkBadSortPagination, checkBadStartPagination, cleanupTests, - flushAndRunServer, + createSingleServer, makeDeleteRequest, makeGetRequest, makePostBodyRequest, - ServerInfo, + PeerTubeServer, setAccessTokensToServers } from '@shared/extra-utils' import { VideoCreateResult } from '@shared/models' @@ -22,7 +22,7 @@ const expect = chai.expect describe('Test video comments API validator', function () { let pathThread: string let pathComment: string - let server: ServerInfo + let server: PeerTubeServer let video: VideoCreateResult let userAccessToken: string let userAccessToken2: string @@ -33,7 +33,7 @@ describe('Test video comments API validator', function () { before(async function () { this.timeout(30000) - server = await flushAndRunServer(1) + server = await createSingleServer(1) await setAccessTokensToServers([ server ]) diff --git a/server/tests/api/check-params/video-imports.ts b/server/tests/api/check-params/video-imports.ts index 1a6b6075f..627f0c7ad 100644 --- a/server/tests/api/check-params/video-imports.ts +++ b/server/tests/api/check-params/video-imports.ts @@ -9,19 +9,19 @@ import { checkBadSortPagination, checkBadStartPagination, cleanupTests, - flushAndRunServer, + createSingleServer, ImportsCommand, makeGetRequest, makePostBodyRequest, makeUploadRequest, - ServerInfo, + PeerTubeServer, setAccessTokensToServers } from '@shared/extra-utils' import { VideoPrivacy } from '@shared/models' describe('Test video imports API validator', function () { const path = '/api/v1/videos/imports' - let server: ServerInfo + let server: PeerTubeServer let userAccessToken = '' let channelId: number @@ -30,7 +30,7 @@ describe('Test video imports API validator', function () { before(async function () { this.timeout(30000) - server = await flushAndRunServer(1) + server = await createSingleServer(1) await setAccessTokensToServers([ server ]) diff --git a/server/tests/api/check-params/video-playlists.ts b/server/tests/api/check-params/video-playlists.ts index e0e42ebb0..9d054b176 100644 --- a/server/tests/api/check-params/video-playlists.ts +++ b/server/tests/api/check-params/video-playlists.ts @@ -7,10 +7,10 @@ import { checkBadSortPagination, checkBadStartPagination, cleanupTests, - flushAndRunServer, + createSingleServer, makeGetRequest, PlaylistsCommand, - ServerInfo, + PeerTubeServer, setAccessTokensToServers, setDefaultVideoChannel } from '@shared/extra-utils' @@ -25,7 +25,7 @@ import { } from '@shared/models' describe('Test video playlists API validator', function () { - let server: ServerInfo + let server: PeerTubeServer let userAccessToken: string let playlist: VideoPlaylistCreateResult @@ -42,7 +42,7 @@ describe('Test video playlists API validator', function () { before(async function () { this.timeout(30000) - server = await flushAndRunServer(1) + server = await createSingleServer(1) await setAccessTokensToServers([ server ]) await setDefaultVideoChannel([ server ]) diff --git a/server/tests/api/check-params/videos-filter.ts b/server/tests/api/check-params/videos-filter.ts index cbfdef1db..e4e799cc7 100644 --- a/server/tests/api/check-params/videos-filter.ts +++ b/server/tests/api/check-params/videos-filter.ts @@ -3,16 +3,16 @@ import 'mocha' import { cleanupTests, - flushAndRunServer, + createSingleServer, makeGetRequest, - ServerInfo, + PeerTubeServer, setAccessTokensToServers, setDefaultVideoChannel } from '../../../../shared/extra-utils' import { UserRole } from '../../../../shared/models/users' import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' -async function testEndpoints (server: ServerInfo, token: string, filter: string, statusCodeExpected: HttpStatusCode) { +async function testEndpoints (server: PeerTubeServer, token: string, filter: string, statusCodeExpected: HttpStatusCode) { const paths = [ '/api/v1/video-channels/root_channel/videos', '/api/v1/accounts/root/videos', @@ -34,7 +34,7 @@ async function testEndpoints (server: ServerInfo, token: string, filter: string, } describe('Test video filters validators', function () { - let server: ServerInfo + let server: PeerTubeServer let userAccessToken: string let moderatorAccessToken: string @@ -43,7 +43,7 @@ describe('Test video filters validators', function () { before(async function () { this.timeout(30000) - server = await flushAndRunServer(1) + server = await createSingleServer(1) await setAccessTokensToServers([ server ]) await setDefaultVideoChannel([ server ]) diff --git a/server/tests/api/check-params/videos-history.ts b/server/tests/api/check-params/videos-history.ts index 549c9fa1f..3c1f479e4 100644 --- a/server/tests/api/check-params/videos-history.ts +++ b/server/tests/api/check-params/videos-history.ts @@ -6,11 +6,11 @@ import { checkBadCountPagination, checkBadStartPagination, cleanupTests, - flushAndRunServer, + createSingleServer, makeGetRequest, makePostBodyRequest, makePutBodyRequest, - ServerInfo, + PeerTubeServer, setAccessTokensToServers } from '@shared/extra-utils' @@ -18,14 +18,14 @@ describe('Test videos history API validator', function () { const myHistoryPath = '/api/v1/users/me/history/videos' const myHistoryRemove = myHistoryPath + '/remove' let watchingPath: string - let server: ServerInfo + let server: PeerTubeServer // --------------------------------------------------------------- before(async function () { this.timeout(30000) - server = await flushAndRunServer(1) + server = await createSingleServer(1) await setAccessTokensToServers([ server ]) diff --git a/server/tests/api/check-params/videos-overviews.ts b/server/tests/api/check-params/videos-overviews.ts index 3597c81d3..c2139d74b 100644 --- a/server/tests/api/check-params/videos-overviews.ts +++ b/server/tests/api/check-params/videos-overviews.ts @@ -1,17 +1,17 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ import 'mocha' -import { cleanupTests, flushAndRunServer, ServerInfo } from '@shared/extra-utils' +import { cleanupTests, createSingleServer, PeerTubeServer } from '@shared/extra-utils' describe('Test videos overview', function () { - let server: ServerInfo + let server: PeerTubeServer // --------------------------------------------------------------- before(async function () { this.timeout(30000) - server = await flushAndRunServer(1) + server = await createSingleServer(1) }) describe('When getting videos overview', function () { diff --git a/server/tests/api/check-params/videos.ts b/server/tests/api/check-params/videos.ts index 69bdae7cf..c60de2640 100644 --- a/server/tests/api/check-params/videos.ts +++ b/server/tests/api/check-params/videos.ts @@ -11,13 +11,13 @@ import { checkBadStartPagination, checkUploadVideoParam, cleanupTests, - flushAndRunServer, + createSingleServer, makeDeleteRequest, makeGetRequest, makePutBodyRequest, makeUploadRequest, root, - ServerInfo, + PeerTubeServer, setAccessTokensToServers } from '@shared/extra-utils' import { PeerTubeProblemDocument, VideoCreateResult, VideoPrivacy } from '@shared/models' @@ -26,7 +26,7 @@ const expect = chai.expect describe('Test videos API validator', function () { const path = '/api/v1/videos/' - let server: ServerInfo + let server: PeerTubeServer let userAccessToken = '' let accountName: string let channelId: number @@ -38,7 +38,7 @@ describe('Test videos API validator', function () { before(async function () { this.timeout(30000) - server = await flushAndRunServer(1) + server = await createSingleServer(1) await setAccessTokensToServers([ server ]) diff --git a/server/tests/api/live/live-constraints.ts b/server/tests/api/live/live-constraints.ts index 1c380883c..a00833569 100644 --- a/server/tests/api/live/live-constraints.ts +++ b/server/tests/api/live/live-constraints.ts @@ -8,8 +8,8 @@ import { cleanupTests, ConfigCommand, doubleFollow, - flushAndRunMultipleServers, - ServerInfo, + createMultipleServers, + PeerTubeServer, setAccessTokensToServers, setDefaultVideoChannel, wait, @@ -19,7 +19,7 @@ import { const expect = chai.expect describe('Test live constraints', function () { - let servers: ServerInfo[] = [] + let servers: PeerTubeServer[] = [] let userId: number let userAccessToken: string let userChannelId: number @@ -63,7 +63,7 @@ describe('Test live constraints', function () { before(async function () { this.timeout(120000) - servers = await flushAndRunMultipleServers(2) + servers = await createMultipleServers(2) // Get the access tokens await setAccessTokensToServers(servers) diff --git a/server/tests/api/live/live-permanent.ts b/server/tests/api/live/live-permanent.ts index 900bd6f5c..30d499e20 100644 --- a/server/tests/api/live/live-permanent.ts +++ b/server/tests/api/live/live-permanent.ts @@ -7,8 +7,8 @@ import { cleanupTests, ConfigCommand, doubleFollow, - flushAndRunMultipleServers, - ServerInfo, + createMultipleServers, + PeerTubeServer, setAccessTokensToServers, setDefaultVideoChannel, stopFfmpeg, @@ -19,7 +19,7 @@ import { const expect = chai.expect describe('Permanent live', function () { - let servers: ServerInfo[] = [] + let servers: PeerTubeServer[] = [] let videoUUID: string async function createLiveWrapper (permanentLive: boolean) { @@ -45,7 +45,7 @@ describe('Permanent live', function () { before(async function () { this.timeout(120000) - servers = await flushAndRunMultipleServers(2) + servers = await createMultipleServers(2) // Get the access tokens await setAccessTokensToServers(servers) diff --git a/server/tests/api/live/live-save-replay.ts b/server/tests/api/live/live-save-replay.ts index 7a33df90a..d403f27bf 100644 --- a/server/tests/api/live/live-save-replay.ts +++ b/server/tests/api/live/live-save-replay.ts @@ -9,8 +9,8 @@ import { cleanupTests, ConfigCommand, doubleFollow, - flushAndRunMultipleServers, - ServerInfo, + createMultipleServers, + PeerTubeServer, setAccessTokensToServers, setDefaultVideoChannel, stopFfmpeg, @@ -23,7 +23,7 @@ import { LiveVideoCreate, VideoPrivacy, VideoState } from '@shared/models' const expect = chai.expect describe('Save replay setting', function () { - let servers: ServerInfo[] = [] + let servers: PeerTubeServer[] = [] let liveVideoUUID: string let ffmpegCommand: FfmpegCommand @@ -82,7 +82,7 @@ describe('Save replay setting', function () { before(async function () { this.timeout(120000) - servers = await flushAndRunMultipleServers(2) + servers = await createMultipleServers(2) // Get the access tokens await setAccessTokensToServers(servers) diff --git a/server/tests/api/live/live-socket-messages.ts b/server/tests/api/live/live-socket-messages.ts index ad67d6285..3808964d1 100644 --- a/server/tests/api/live/live-socket-messages.ts +++ b/server/tests/api/live/live-socket-messages.ts @@ -6,8 +6,8 @@ import { VideoPrivacy, VideoState } from '@shared/models' import { cleanupTests, doubleFollow, - flushAndRunMultipleServers, - ServerInfo, + createMultipleServers, + PeerTubeServer, setAccessTokensToServers, setDefaultVideoChannel, stopFfmpeg, @@ -19,12 +19,12 @@ import { const expect = chai.expect describe('Test live', function () { - let servers: ServerInfo[] = [] + let servers: PeerTubeServer[] = [] before(async function () { this.timeout(120000) - servers = await flushAndRunMultipleServers(2) + servers = await createMultipleServers(2) // Get the access tokens await setAccessTokensToServers(servers) diff --git a/server/tests/api/live/live-views.ts b/server/tests/api/live/live-views.ts index 43222f9c9..4a137b185 100644 --- a/server/tests/api/live/live-views.ts +++ b/server/tests/api/live/live-views.ts @@ -7,8 +7,8 @@ import { VideoPrivacy } from '@shared/models' import { cleanupTests, doubleFollow, - flushAndRunMultipleServers, - ServerInfo, + createMultipleServers, + PeerTubeServer, setAccessTokensToServers, setDefaultVideoChannel, stopFfmpeg, @@ -20,12 +20,12 @@ import { const expect = chai.expect describe('Test live', function () { - let servers: ServerInfo[] = [] + let servers: PeerTubeServer[] = [] before(async function () { this.timeout(120000) - servers = await flushAndRunMultipleServers(2) + servers = await createMultipleServers(2) // Get the access tokens await setAccessTokensToServers(servers) diff --git a/server/tests/api/live/live.ts b/server/tests/api/live/live.ts index 2cce1f448..7cfac522c 100644 --- a/server/tests/api/live/live.ts +++ b/server/tests/api/live/live.ts @@ -11,13 +11,12 @@ import { checkResolutionsInMasterPlaylist, cleanupTests, doubleFollow, - flushAndRunMultipleServers, + createMultipleServers, killallServers, LiveCommand, makeRawRequest, - reRunServer, sendRTMPStream, - ServerInfo, + PeerTubeServer, setAccessTokensToServers, setDefaultVideoChannel, stopFfmpeg, @@ -32,13 +31,13 @@ import { LiveVideo, LiveVideoCreate, VideoDetails, VideoPrivacy, VideoState, Vid const expect = chai.expect describe('Test live', function () { - let servers: ServerInfo[] = [] + let servers: PeerTubeServer[] = [] let commands: LiveCommand[] before(async function () { this.timeout(120000) - servers = await flushAndRunMultipleServers(2) + servers = await createMultipleServers(2) // Get the access tokens await setAccessTokensToServers(servers) @@ -571,7 +570,7 @@ describe('Test live', function () { await commands[0].waitUntilSegmentGeneration({ videoUUID: liveVideoReplayId, resolution: 0, segment: 2 }) await killallServers([ servers[0] ]) - await reRunServer(servers[0]) + await servers[0].run() await wait(5000) }) diff --git a/server/tests/api/moderation/abuses.ts b/server/tests/api/moderation/abuses.ts index 97a0d95c4..360b9de35 100644 --- a/server/tests/api/moderation/abuses.ts +++ b/server/tests/api/moderation/abuses.ts @@ -6,8 +6,8 @@ import { AbusesCommand, cleanupTests, doubleFollow, - flushAndRunMultipleServers, - ServerInfo, + createMultipleServers, + PeerTubeServer, setAccessTokensToServers, waitJobs } from '@shared/extra-utils' @@ -16,7 +16,7 @@ import { AbuseMessage, AbusePredefinedReasonsString, AbuseState, AdminAbuse, Use const expect = chai.expect describe('Test abuses', function () { - let servers: ServerInfo[] = [] + let servers: PeerTubeServer[] = [] let abuseServer1: AdminAbuse let abuseServer2: AdminAbuse let commands: AbusesCommand[] @@ -25,7 +25,7 @@ describe('Test abuses', function () { this.timeout(50000) // Run servers - servers = await flushAndRunMultipleServers(2) + servers = await createMultipleServers(2) // Get the access tokens await setAccessTokensToServers(servers) @@ -389,7 +389,7 @@ describe('Test abuses', function () { describe('Comment abuses', function () { - async function getComment (server: ServerInfo, videoIdArg: number | string) { + async function getComment (server: PeerTubeServer, videoIdArg: number | string) { const videoId = typeof videoIdArg === 'string' ? await server.videos.getId({ uuid: videoIdArg }) : videoIdArg @@ -591,7 +591,7 @@ describe('Test abuses', function () { describe('Account abuses', function () { - function getAccountFromServer (server: ServerInfo, targetName: string, targetServer: ServerInfo) { + function getAccountFromServer (server: PeerTubeServer, targetName: string, targetServer: PeerTubeServer) { return server.accounts.get({ accountName: targetName + '@' + targetServer.host }) } diff --git a/server/tests/api/moderation/blocklist-notification.ts b/server/tests/api/moderation/blocklist-notification.ts index 6b56fdd65..fdfbcbced 100644 --- a/server/tests/api/moderation/blocklist-notification.ts +++ b/server/tests/api/moderation/blocklist-notification.ts @@ -2,12 +2,12 @@ import 'mocha' import * as chai from 'chai' -import { cleanupTests, doubleFollow, flushAndRunMultipleServers, ServerInfo, setAccessTokensToServers, waitJobs } from '@shared/extra-utils' +import { cleanupTests, doubleFollow, createMultipleServers, PeerTubeServer, setAccessTokensToServers, waitJobs } from '@shared/extra-utils' import { UserNotificationType } from '@shared/models' const expect = chai.expect -async function checkNotifications (server: ServerInfo, token: string, expected: UserNotificationType[]) { +async function checkNotifications (server: PeerTubeServer, token: string, expected: UserNotificationType[]) { const { data } = await server.notifications.list({ token, start: 0, count: 10, unread: true }) expect(data).to.have.lengthOf(expected.length) @@ -17,7 +17,7 @@ async function checkNotifications (server: ServerInfo, token: string, expected: } describe('Test blocklist', function () { - let servers: ServerInfo[] + let servers: PeerTubeServer[] let videoUUID: string let userToken1: string @@ -62,7 +62,7 @@ describe('Test blocklist', function () { before(async function () { this.timeout(60000) - servers = await flushAndRunMultipleServers(2) + servers = await createMultipleServers(2) await setAccessTokensToServers(servers) { diff --git a/server/tests/api/moderation/blocklist.ts b/server/tests/api/moderation/blocklist.ts index 9a4a3b3b9..593291e87 100644 --- a/server/tests/api/moderation/blocklist.ts +++ b/server/tests/api/moderation/blocklist.ts @@ -7,8 +7,8 @@ import { cleanupTests, CommentsCommand, doubleFollow, - flushAndRunMultipleServers, - ServerInfo, + createMultipleServers, + PeerTubeServer, setAccessTokensToServers, waitJobs } from '@shared/extra-utils' @@ -16,7 +16,7 @@ import { UserNotificationType } from '@shared/models' const expect = chai.expect -async function checkAllVideos (server: ServerInfo, token: string) { +async function checkAllVideos (server: PeerTubeServer, token: string) { { const { data } = await server.videos.listWithToken({ token }) expect(data).to.have.lengthOf(5) @@ -28,7 +28,7 @@ async function checkAllVideos (server: ServerInfo, token: string) { } } -async function checkAllComments (server: ServerInfo, token: string, videoUUID: string) { +async function checkAllComments (server: PeerTubeServer, token: string, videoUUID: string) { const { data } = await server.comments.listThreads({ videoId: videoUUID, start: 0, count: 25, sort: '-createdAt', token }) const threads = data.filter(t => t.isDeleted === false) @@ -41,8 +41,8 @@ async function checkAllComments (server: ServerInfo, token: string, videoUUID: s } async function checkCommentNotification ( - mainServer: ServerInfo, - comment: { server: ServerInfo, token: string, videoUUID: string, text: string }, + mainServer: PeerTubeServer, + comment: { server: PeerTubeServer, token: string, videoUUID: string, text: string }, check: 'presence' | 'absence' ) { const command = comment.server.comments @@ -63,7 +63,7 @@ async function checkCommentNotification ( } describe('Test blocklist', function () { - let servers: ServerInfo[] + let servers: PeerTubeServer[] let videoUUID1: string let videoUUID2: string let videoUUID3: string @@ -77,7 +77,7 @@ describe('Test blocklist', function () { before(async function () { this.timeout(120000) - servers = await flushAndRunMultipleServers(3) + servers = await createMultipleServers(3) await setAccessTokensToServers(servers) command = servers[0].blocklist diff --git a/server/tests/api/moderation/video-blacklist.ts b/server/tests/api/moderation/video-blacklist.ts index d23d23bcb..62cbf2e07 100644 --- a/server/tests/api/moderation/video-blacklist.ts +++ b/server/tests/api/moderation/video-blacklist.ts @@ -7,11 +7,10 @@ import { BlacklistCommand, cleanupTests, doubleFollow, - flushAndRunMultipleServers, + createMultipleServers, ImportsCommand, killallServers, - reRunServer, - ServerInfo, + PeerTubeServer, setAccessTokensToServers, waitJobs } from '@shared/extra-utils' @@ -20,11 +19,11 @@ import { UserAdminFlag, UserRole, VideoBlacklist, VideoBlacklistType } from '@sh const expect = chai.expect describe('Test video blacklist', function () { - let servers: ServerInfo[] = [] + let servers: PeerTubeServer[] = [] let videoId: number let command: BlacklistCommand - async function blacklistVideosOnServer (server: ServerInfo) { + async function blacklistVideosOnServer (server: PeerTubeServer) { const { data } = await server.videos.list() for (const video of data) { @@ -36,7 +35,7 @@ describe('Test video blacklist', function () { this.timeout(50000) // Run servers - servers = await flushAndRunMultipleServers(2) + servers = await createMultipleServers(2) // Get the access tokens await setAccessTokensToServers(servers) @@ -344,7 +343,7 @@ describe('Test video blacklist', function () { } } } - await reRunServer(servers[0], config) + await servers[0].run(config) { const user = { username: 'user_without_flag', password: 'password' } diff --git a/server/tests/api/notifications/admin-notifications.ts b/server/tests/api/notifications/admin-notifications.ts index 5a5bdb0c8..d65551f0a 100644 --- a/server/tests/api/notifications/admin-notifications.ts +++ b/server/tests/api/notifications/admin-notifications.ts @@ -10,13 +10,13 @@ import { MockJoinPeerTubeVersions, MockSmtpServer, prepareNotificationsTest, - ServerInfo, + PeerTubeServer, wait } from '@shared/extra-utils' import { PluginType, UserNotification, UserNotificationType } from '@shared/models' describe('Test admin notifications', function () { - let server: ServerInfo + let server: PeerTubeServer let userNotifications: UserNotification[] = [] let adminNotifications: UserNotification[] = [] let emails: object[] = [] diff --git a/server/tests/api/notifications/comments-notifications.ts b/server/tests/api/notifications/comments-notifications.ts index 133b6340f..d54819aaa 100644 --- a/server/tests/api/notifications/comments-notifications.ts +++ b/server/tests/api/notifications/comments-notifications.ts @@ -9,7 +9,7 @@ import { cleanupTests, MockSmtpServer, prepareNotificationsTest, - ServerInfo, + PeerTubeServer, waitJobs } from '@shared/extra-utils' import { UserNotification } from '@shared/models' @@ -17,7 +17,7 @@ import { UserNotification } from '@shared/models' const expect = chai.expect describe('Test comments notifications', function () { - let servers: ServerInfo[] = [] + let servers: PeerTubeServer[] = [] let userToken: string let userNotifications: UserNotification[] = [] let emails: object[] = [] diff --git a/server/tests/api/notifications/moderation-notifications.ts b/server/tests/api/notifications/moderation-notifications.ts index e7c5badd2..3a294192b 100644 --- a/server/tests/api/notifications/moderation-notifications.ts +++ b/server/tests/api/notifications/moderation-notifications.ts @@ -20,14 +20,14 @@ import { MockInstancesIndex, MockSmtpServer, prepareNotificationsTest, - ServerInfo, + PeerTubeServer, wait, waitJobs } from '@shared/extra-utils' import { AbuseState, CustomConfig, UserNotification, VideoPrivacy } from '@shared/models' describe('Test moderation notifications', function () { - let servers: ServerInfo[] = [] + let servers: PeerTubeServer[] = [] let userAccessToken: string let userNotifications: UserNotification[] = [] let adminNotifications: UserNotification[] = [] diff --git a/server/tests/api/notifications/notifications-api.ts b/server/tests/api/notifications/notifications-api.ts index 647d783b5..178b20687 100644 --- a/server/tests/api/notifications/notifications-api.ts +++ b/server/tests/api/notifications/notifications-api.ts @@ -9,7 +9,7 @@ import { getAllNotificationsSettings, MockSmtpServer, prepareNotificationsTest, - ServerInfo, + PeerTubeServer, waitJobs } from '@shared/extra-utils' import { UserNotification, UserNotificationSettingValue } from '@shared/models' @@ -17,7 +17,7 @@ import { UserNotification, UserNotificationSettingValue } from '@shared/models' const expect = chai.expect describe('Test notifications API', function () { - let server: ServerInfo + let server: PeerTubeServer let userNotifications: UserNotification[] = [] let userToken: string let emails: object[] = [] diff --git a/server/tests/api/notifications/user-notifications.ts b/server/tests/api/notifications/user-notifications.ts index 53f8c7594..b7c22d118 100644 --- a/server/tests/api/notifications/user-notifications.ts +++ b/server/tests/api/notifications/user-notifications.ts @@ -13,7 +13,7 @@ import { ImportsCommand, MockSmtpServer, prepareNotificationsTest, - ServerInfo, + PeerTubeServer, uploadRandomVideoOnServers, wait, waitJobs @@ -23,7 +23,7 @@ import { UserNotification, UserNotificationType, VideoPrivacy } from '@shared/mo const expect = chai.expect describe('Test user notifications', function () { - let servers: ServerInfo[] = [] + let servers: PeerTubeServer[] = [] let userAccessToken: string let userNotifications: UserNotification[] = [] let adminNotifications: UserNotification[] = [] diff --git a/server/tests/api/redundancy/manage-redundancy.ts b/server/tests/api/redundancy/manage-redundancy.ts index e193b968e..aff64e2eb 100644 --- a/server/tests/api/redundancy/manage-redundancy.ts +++ b/server/tests/api/redundancy/manage-redundancy.ts @@ -5,9 +5,9 @@ import * as chai from 'chai' import { cleanupTests, doubleFollow, - flushAndRunMultipleServers, + createMultipleServers, RedundancyCommand, - ServerInfo, + PeerTubeServer, setAccessTokensToServers, waitJobs } from '@shared/extra-utils' @@ -18,7 +18,7 @@ const expect = chai.expect describe('Test manage videos redundancy', function () { const targets: VideoRedundanciesTarget[] = [ 'my-videos', 'remote-videos' ] - let servers: ServerInfo[] + let servers: PeerTubeServer[] let video1Server2UUID: string let video2Server2UUID: string let redundanciesToRemove: number[] = [] @@ -48,7 +48,7 @@ describe('Test manage videos redundancy', function () { } } } - servers = await flushAndRunMultipleServers(3, config) + servers = await createMultipleServers(3, config) // Get the access tokens await setAccessTokensToServers(servers) diff --git a/server/tests/api/redundancy/redundancy-constraints.ts b/server/tests/api/redundancy/redundancy-constraints.ts index 0378cc122..217691fb6 100644 --- a/server/tests/api/redundancy/redundancy-constraints.ts +++ b/server/tests/api/redundancy/redundancy-constraints.ts @@ -4,19 +4,18 @@ import 'mocha' import { expect } from 'chai' import { cleanupTests, - flushAndRunServer, + createSingleServer, killallServers, - reRunServer, - ServerInfo, + PeerTubeServer, setAccessTokensToServers, waitJobs } from '@shared/extra-utils' import { VideoPrivacy } from '@shared/models' describe('Test redundancy constraints', function () { - let remoteServer: ServerInfo - let localServer: ServerInfo - let servers: ServerInfo[] + let remoteServer: PeerTubeServer + let localServer: PeerTubeServer + let servers: PeerTubeServer[] const remoteServerConfig = { redundancy: { @@ -59,7 +58,7 @@ describe('Test redundancy constraints', function () { this.timeout(120000) { - remoteServer = await flushAndRunServer(1, remoteServerConfig) + remoteServer = await createSingleServer(1, remoteServerConfig) } { @@ -70,7 +69,7 @@ describe('Test redundancy constraints', function () { } } } - localServer = await flushAndRunServer(2, config) + localServer = await createSingleServer(2, config) } servers = [ remoteServer, localServer ] @@ -119,7 +118,7 @@ describe('Test redundancy constraints', function () { } } await await killallServers([ localServer ]) - await reRunServer(localServer, config) + await localServer.run(config) await uploadWrapper('video 2 server 2') @@ -148,7 +147,7 @@ describe('Test redundancy constraints', function () { } } await killallServers([ localServer ]) - await reRunServer(localServer, config) + await localServer.run(config) await uploadWrapper('video 3 server 2') diff --git a/server/tests/api/redundancy/redundancy.ts b/server/tests/api/redundancy/redundancy.ts index 77ea2278e..9d5d96efd 100644 --- a/server/tests/api/redundancy/redundancy.ts +++ b/server/tests/api/redundancy/redundancy.ts @@ -11,12 +11,11 @@ import { checkVideoFilesWereRemoved, cleanupTests, doubleFollow, - flushAndRunMultipleServers, + createMultipleServers, killallServers, makeGetRequest, - reRunServer, root, - ServerInfo, + PeerTubeServer, setAccessTokensToServers, wait, waitJobs @@ -25,11 +24,11 @@ import { VideoPrivacy, VideoRedundancyStrategy, VideoRedundancyStrategyWithManua const expect = chai.expect -let servers: ServerInfo[] = [] +let servers: PeerTubeServer[] = [] let video1Server2UUID: string let video1Server2Id: number -function checkMagnetWebseeds (file: { magnetUri: string, resolution: { id: number } }, baseWebseeds: string[], server: ServerInfo) { +function checkMagnetWebseeds (file: { magnetUri: string, resolution: { id: number } }, baseWebseeds: string[], server: PeerTubeServer) { const parsed = magnetUtil.decode(file.magnetUri) for (const ws of baseWebseeds) { @@ -40,7 +39,7 @@ function checkMagnetWebseeds (file: { magnetUri: string, resolution: { id: numbe expect(parsed.urlList).to.have.lengthOf(baseWebseeds.length) } -async function flushAndRunServers (strategy: VideoRedundancyStrategy | null, additionalParams: any = {}, withWebtorrent = true) { +async function createSingleServers (strategy: VideoRedundancyStrategy | null, additionalParams: any = {}, withWebtorrent = true) { const strategies: any[] = [] if (strategy !== null) { @@ -72,7 +71,7 @@ async function flushAndRunServers (strategy: VideoRedundancyStrategy | null, add } } - servers = await flushAndRunMultipleServers(3, config) + servers = await createMultipleServers(3, config) // Get the access tokens await setAccessTokensToServers(servers) @@ -288,7 +287,7 @@ describe('Test videos redundancy', function () { before(function () { this.timeout(120000) - return flushAndRunServers(strategy) + return createSingleServers(strategy) }) it('Should have 1 webseed on the first video', async function () { @@ -338,7 +337,7 @@ describe('Test videos redundancy', function () { before(function () { this.timeout(120000) - return flushAndRunServers(strategy) + return createSingleServers(strategy) }) it('Should have 1 webseed on the first video', async function () { @@ -388,7 +387,7 @@ describe('Test videos redundancy', function () { before(function () { this.timeout(120000) - return flushAndRunServers(strategy, { min_views: 3 }) + return createSingleServers(strategy, { min_views: 3 }) }) it('Should have 1 webseed on the first video', async function () { @@ -458,7 +457,7 @@ describe('Test videos redundancy', function () { before(async function () { this.timeout(120000) - await flushAndRunServers(strategy, { min_views: 3 }, false) + await createSingleServers(strategy, { min_views: 3 }, false) }) it('Should have 0 playlist redundancy on the first video', async function () { @@ -519,7 +518,7 @@ describe('Test videos redundancy', function () { before(function () { this.timeout(120000) - return flushAndRunServers(null) + return createSingleServers(null) }) it('Should have 1 webseed on the first video', async function () { @@ -575,7 +574,7 @@ describe('Test videos redundancy', function () { describe('Test expiration', function () { const strategy = 'recently-added' - async function checkContains (servers: ServerInfo[], str: string) { + async function checkContains (servers: PeerTubeServer[], str: string) { for (const server of servers) { const video = await server.videos.get({ id: video1Server2UUID }) @@ -585,7 +584,7 @@ describe('Test videos redundancy', function () { } } - async function checkNotContains (servers: ServerInfo[], str: string) { + async function checkNotContains (servers: PeerTubeServer[], str: string) { for (const server of servers) { const video = await server.videos.get({ id: video1Server2UUID }) @@ -598,7 +597,7 @@ describe('Test videos redundancy', function () { before(async function () { this.timeout(120000) - await flushAndRunServers(strategy, { min_lifetime: '7 seconds', min_views: 0 }) + await createSingleServers(strategy, { min_lifetime: '7 seconds', min_views: 0 }) await enableRedundancyOnServer1() }) @@ -640,7 +639,7 @@ describe('Test videos redundancy', function () { before(async function () { this.timeout(120000) - await flushAndRunServers(strategy, { min_lifetime: '7 seconds', min_views: 0 }) + await createSingleServers(strategy, { min_lifetime: '7 seconds', min_views: 0 }) await enableRedundancyOnServer1() @@ -691,7 +690,7 @@ describe('Test videos redundancy', function () { await waitJobs(servers) await killallServers([ servers[0] ]) - await reRunServer(servers[0], { + await servers[0].run({ redundancy: { videos: { check_interval: '1 second', diff --git a/server/tests/api/search/search-activitypub-video-channels.ts b/server/tests/api/search/search-activitypub-video-channels.ts index 71e9367e5..f5896ec25 100644 --- a/server/tests/api/search/search-activitypub-video-channels.ts +++ b/server/tests/api/search/search-activitypub-video-channels.ts @@ -4,9 +4,9 @@ import 'mocha' import * as chai from 'chai' import { cleanupTests, - flushAndRunMultipleServers, + createMultipleServers, SearchCommand, - ServerInfo, + PeerTubeServer, setAccessTokensToServers, wait, waitJobs @@ -16,7 +16,7 @@ import { VideoChannel } from '@shared/models' const expect = chai.expect describe('Test ActivityPub video channels search', function () { - let servers: ServerInfo[] + let servers: PeerTubeServer[] let userServer2Token: string let videoServer2UUID: string let channelIdServer2: number @@ -25,7 +25,7 @@ describe('Test ActivityPub video channels search', function () { before(async function () { this.timeout(120000) - servers = await flushAndRunMultipleServers(2) + servers = await createMultipleServers(2) await setAccessTokensToServers(servers) diff --git a/server/tests/api/search/search-activitypub-video-playlists.ts b/server/tests/api/search/search-activitypub-video-playlists.ts index 7c99b954b..ada2d3d6c 100644 --- a/server/tests/api/search/search-activitypub-video-playlists.ts +++ b/server/tests/api/search/search-activitypub-video-playlists.ts @@ -4,9 +4,9 @@ import 'mocha' import * as chai from 'chai' import { cleanupTests, - flushAndRunMultipleServers, + createMultipleServers, SearchCommand, - ServerInfo, + PeerTubeServer, setAccessTokensToServers, setDefaultVideoChannel, wait, @@ -17,7 +17,7 @@ import { VideoPlaylistPrivacy } from '@shared/models' const expect = chai.expect describe('Test ActivityPub playlists search', function () { - let servers: ServerInfo[] + let servers: PeerTubeServer[] let playlistServer1UUID: string let playlistServer2UUID: string let video2Server2: string @@ -27,7 +27,7 @@ describe('Test ActivityPub playlists search', function () { before(async function () { this.timeout(120000) - servers = await flushAndRunMultipleServers(2) + servers = await createMultipleServers(2) await setAccessTokensToServers(servers) await setDefaultVideoChannel(servers) diff --git a/server/tests/api/search/search-activitypub-videos.ts b/server/tests/api/search/search-activitypub-videos.ts index 0dfc63446..a015b72a7 100644 --- a/server/tests/api/search/search-activitypub-videos.ts +++ b/server/tests/api/search/search-activitypub-videos.ts @@ -4,9 +4,9 @@ import 'mocha' import * as chai from 'chai' import { cleanupTests, - flushAndRunMultipleServers, + createMultipleServers, SearchCommand, - ServerInfo, + PeerTubeServer, setAccessTokensToServers, wait, waitJobs @@ -16,7 +16,7 @@ import { VideoPrivacy } from '@shared/models' const expect = chai.expect describe('Test ActivityPub videos search', function () { - let servers: ServerInfo[] + let servers: PeerTubeServer[] let videoServer1UUID: string let videoServer2UUID: string @@ -25,7 +25,7 @@ describe('Test ActivityPub videos search', function () { before(async function () { this.timeout(120000) - servers = await flushAndRunMultipleServers(2) + servers = await createMultipleServers(2) await setAccessTokensToServers(servers) diff --git a/server/tests/api/search/search-channels.ts b/server/tests/api/search/search-channels.ts index 7035fbd62..07e00a214 100644 --- a/server/tests/api/search/search-channels.ts +++ b/server/tests/api/search/search-channels.ts @@ -2,19 +2,19 @@ import 'mocha' import * as chai from 'chai' -import { cleanupTests, flushAndRunServer, SearchCommand, ServerInfo, setAccessTokensToServers } from '@shared/extra-utils' +import { cleanupTests, createSingleServer, SearchCommand, PeerTubeServer, setAccessTokensToServers } from '@shared/extra-utils' import { VideoChannel } from '@shared/models' const expect = chai.expect describe('Test channels search', function () { - let server: ServerInfo = null + let server: PeerTubeServer = null let command: SearchCommand before(async function () { this.timeout(30000) - server = await flushAndRunServer(1) + server = await createSingleServer(1) await setAccessTokensToServers([ server ]) diff --git a/server/tests/api/search/search-index.ts b/server/tests/api/search/search-index.ts index b54c0da22..38edcf7c6 100644 --- a/server/tests/api/search/search-index.ts +++ b/server/tests/api/search/search-index.ts @@ -2,7 +2,7 @@ import 'mocha' import * as chai from 'chai' -import { cleanupTests, flushAndRunServer, SearchCommand, ServerInfo, setAccessTokensToServers } from '@shared/extra-utils' +import { cleanupTests, createSingleServer, SearchCommand, PeerTubeServer, setAccessTokensToServers } from '@shared/extra-utils' import { BooleanBothQuery, VideoPlaylistPrivacy, VideoPlaylistType, VideosSearchQuery } from '@shared/models' const expect = chai.expect @@ -10,13 +10,13 @@ const expect = chai.expect describe('Test videos search', function () { const localVideoName = 'local video' + new Date().toISOString() - let server: ServerInfo = null + let server: PeerTubeServer = null let command: SearchCommand before(async function () { this.timeout(30000) - server = await flushAndRunServer(1) + server = await createSingleServer(1) await setAccessTokensToServers([ server ]) diff --git a/server/tests/api/search/search-playlists.ts b/server/tests/api/search/search-playlists.ts index e15128c8e..b29c2d127 100644 --- a/server/tests/api/search/search-playlists.ts +++ b/server/tests/api/search/search-playlists.ts @@ -4,9 +4,9 @@ import 'mocha' import * as chai from 'chai' import { cleanupTests, - flushAndRunServer, + createSingleServer, SearchCommand, - ServerInfo, + PeerTubeServer, setAccessTokensToServers, setDefaultVideoChannel } from '@shared/extra-utils' @@ -15,13 +15,13 @@ import { VideoPlaylistPrivacy } from '@shared/models' const expect = chai.expect describe('Test playlists search', function () { - let server: ServerInfo = null + let server: PeerTubeServer = null let command: SearchCommand before(async function () { this.timeout(30000) - server = await flushAndRunServer(1) + server = await createSingleServer(1) await setAccessTokensToServers([ server ]) await setDefaultVideoChannel([ server ]) diff --git a/server/tests/api/search/search-videos.ts b/server/tests/api/search/search-videos.ts index 478ebafc9..a9b0a4fcd 100644 --- a/server/tests/api/search/search-videos.ts +++ b/server/tests/api/search/search-videos.ts @@ -4,9 +4,9 @@ import 'mocha' import * as chai from 'chai' import { cleanupTests, - flushAndRunServer, + createSingleServer, SearchCommand, - ServerInfo, + PeerTubeServer, setAccessTokensToServers, setDefaultVideoChannel, stopFfmpeg, @@ -17,7 +17,7 @@ import { VideoPrivacy } from '@shared/models' const expect = chai.expect describe('Test videos search', function () { - let server: ServerInfo = null + let server: PeerTubeServer = null let startDate: string let videoUUID: string @@ -26,7 +26,7 @@ describe('Test videos search', function () { before(async function () { this.timeout(60000) - server = await flushAndRunServer(1) + server = await createSingleServer(1) await setAccessTokensToServers([ server ]) await setDefaultVideoChannel([ server ]) diff --git a/server/tests/api/server/auto-follows.ts b/server/tests/api/server/auto-follows.ts index e9fb5b4b1..8dca2e5e5 100644 --- a/server/tests/api/server/auto-follows.ts +++ b/server/tests/api/server/auto-follows.ts @@ -4,9 +4,9 @@ import 'mocha' import * as chai from 'chai' import { cleanupTests, - flushAndRunMultipleServers, + createMultipleServers, MockInstancesIndex, - ServerInfo, + PeerTubeServer, setAccessTokensToServers, wait, waitJobs @@ -14,7 +14,7 @@ import { const expect = chai.expect -async function checkFollow (follower: ServerInfo, following: ServerInfo, exists: boolean) { +async function checkFollow (follower: PeerTubeServer, following: PeerTubeServer, exists: boolean) { { const body = await following.follows.getFollowers({ start: 0, count: 5, sort: '-createdAt' }) const follow = body.data.find(f => f.follower.host === follower.host && f.state === 'accepted') @@ -32,13 +32,13 @@ async function checkFollow (follower: ServerInfo, following: ServerInfo, exists: } } -async function server1Follows2 (servers: ServerInfo[]) { +async function server1Follows2 (servers: PeerTubeServer[]) { await servers[0].follows.follow({ targets: [ servers[1].host ] }) await waitJobs(servers) } -async function resetFollows (servers: ServerInfo[]) { +async function resetFollows (servers: PeerTubeServer[]) { try { await servers[0].follows.unfollow({ target: servers[1] }) await servers[1].follows.unfollow({ target: servers[0] }) @@ -52,12 +52,12 @@ async function resetFollows (servers: ServerInfo[]) { } describe('Test auto follows', function () { - let servers: ServerInfo[] = [] + let servers: PeerTubeServer[] = [] before(async function () { this.timeout(30000) - servers = await flushAndRunMultipleServers(3) + servers = await createMultipleServers(3) // Get the access tokens await setAccessTokensToServers(servers) diff --git a/server/tests/api/server/bulk.ts b/server/tests/api/server/bulk.ts index acc17092d..5d8c87983 100644 --- a/server/tests/api/server/bulk.ts +++ b/server/tests/api/server/bulk.ts @@ -6,8 +6,8 @@ import { BulkCommand, cleanupTests, doubleFollow, - flushAndRunMultipleServers, - ServerInfo, + createMultipleServers, + PeerTubeServer, setAccessTokensToServers, waitJobs } from '@shared/extra-utils' @@ -17,7 +17,7 @@ const expect = chai.expect describe('Test bulk actions', function () { const commentsUser3: { videoId: number, commentId: number }[] = [] - let servers: ServerInfo[] = [] + let servers: PeerTubeServer[] = [] let user1Token: string let user2Token: string let user3Token: string @@ -27,7 +27,7 @@ describe('Test bulk actions', function () { before(async function () { this.timeout(30000) - servers = await flushAndRunMultipleServers(2) + servers = await createMultipleServers(2) // Get the access tokens await setAccessTokensToServers(servers) diff --git a/server/tests/api/server/config.ts b/server/tests/api/server/config.ts index 479e177a8..a7191c5ef 100644 --- a/server/tests/api/server/config.ts +++ b/server/tests/api/server/config.ts @@ -5,19 +5,18 @@ import * as chai from 'chai' import { HttpStatusCode } from '@shared/core-utils' import { cleanupTests, - flushAndRunServer, + createSingleServer, killallServers, makeGetRequest, parallelTests, - reRunServer, - ServerInfo, + PeerTubeServer, setAccessTokensToServers } from '@shared/extra-utils' import { CustomConfig } from '@shared/models' const expect = chai.expect -function checkInitialConfig (server: ServerInfo, data: CustomConfig) { +function checkInitialConfig (server: PeerTubeServer, data: CustomConfig) { expect(data.instance.name).to.equal('PeerTube') expect(data.instance.shortDescription).to.equal( 'PeerTube, an ActivityPub-federated video streaming platform using P2P directly in your web browser.' @@ -204,12 +203,12 @@ function checkUpdatedConfig (data: CustomConfig) { } describe('Test config', function () { - let server: ServerInfo = null + let server: PeerTubeServer = null before(async function () { this.timeout(30000) - server = await flushAndRunServer(1) + server = await createSingleServer(1) await setAccessTokensToServers([ server ]) }) @@ -456,7 +455,7 @@ describe('Test config', function () { await killallServers([ server ]) - await reRunServer(server) + await server.run() const data = await server.config.getCustomConfig() @@ -512,7 +511,7 @@ describe('Test config', function () { frameguard: { enabled: false } } } - server = await reRunServer(server, config) + await server.run(config) { const res = await makeGetRequest({ diff --git a/server/tests/api/server/contact-form.ts b/server/tests/api/server/contact-form.ts index 353fed80a..f0905bb3b 100644 --- a/server/tests/api/server/contact-form.ts +++ b/server/tests/api/server/contact-form.ts @@ -3,13 +3,21 @@ import 'mocha' import * as chai from 'chai' import { HttpStatusCode } from '@shared/core-utils' -import { cleanupTests, flushAndRunServer, MockSmtpServer, ServerInfo, setAccessTokensToServers, wait, waitJobs } from '@shared/extra-utils' -import { ContactFormCommand } from '@shared/extra-utils/server' +import { + cleanupTests, + ContactFormCommand, + createSingleServer, + MockSmtpServer, + PeerTubeServer, + setAccessTokensToServers, + wait, + waitJobs +} from '@shared/extra-utils' const expect = chai.expect describe('Test contact form', function () { - let server: ServerInfo + let server: PeerTubeServer const emails: object[] = [] let command: ContactFormCommand @@ -24,7 +32,7 @@ describe('Test contact form', function () { port } } - server = await flushAndRunServer(1, overrideConfig) + server = await createSingleServer(1, overrideConfig) await setAccessTokensToServers([ server ]) command = server.contactForm diff --git a/server/tests/api/server/email.ts b/server/tests/api/server/email.ts index 258e835e7..b202cf8a7 100644 --- a/server/tests/api/server/email.ts +++ b/server/tests/api/server/email.ts @@ -3,12 +3,12 @@ import 'mocha' import * as chai from 'chai' import { HttpStatusCode } from '@shared/core-utils' -import { cleanupTests, flushAndRunServer, MockSmtpServer, ServerInfo, setAccessTokensToServers, waitJobs } from '@shared/extra-utils' +import { cleanupTests, createSingleServer, MockSmtpServer, PeerTubeServer, setAccessTokensToServers, waitJobs } from '@shared/extra-utils' const expect = chai.expect describe('Test emails', function () { - let server: ServerInfo + let server: PeerTubeServer let userId: number let userId2: number let userAccessToken: string @@ -39,7 +39,7 @@ describe('Test emails', function () { port: emailPort } } - server = await flushAndRunServer(1, overrideConfig) + server = await createSingleServer(1, overrideConfig) await setAccessTokensToServers([ server ]) { diff --git a/server/tests/api/server/follow-constraints.ts b/server/tests/api/server/follow-constraints.ts index 887e400e9..4ed593b76 100644 --- a/server/tests/api/server/follow-constraints.ts +++ b/server/tests/api/server/follow-constraints.ts @@ -3,13 +3,13 @@ import 'mocha' import * as chai from 'chai' import { HttpStatusCode } from '@shared/core-utils' -import { cleanupTests, doubleFollow, flushAndRunMultipleServers, ServerInfo, setAccessTokensToServers } from '@shared/extra-utils' +import { cleanupTests, doubleFollow, createMultipleServers, PeerTubeServer, setAccessTokensToServers } from '@shared/extra-utils' import { PeerTubeProblemDocument, ServerErrorCode } from '@shared/models' const expect = chai.expect describe('Test follow constraints', function () { - let servers: ServerInfo[] = [] + let servers: PeerTubeServer[] = [] let video1UUID: string let video2UUID: string let userToken: string @@ -17,7 +17,7 @@ describe('Test follow constraints', function () { before(async function () { this.timeout(90000) - servers = await flushAndRunMultipleServers(2) + servers = await createMultipleServers(2) // Get the access tokens await setAccessTokensToServers(servers) diff --git a/server/tests/api/server/follows-moderation.ts b/server/tests/api/server/follows-moderation.ts index 045024544..0aa328c5a 100644 --- a/server/tests/api/server/follows-moderation.ts +++ b/server/tests/api/server/follows-moderation.ts @@ -4,16 +4,16 @@ import 'mocha' import * as chai from 'chai' import { cleanupTests, - flushAndRunMultipleServers, + createMultipleServers, FollowsCommand, - ServerInfo, + PeerTubeServer, setAccessTokensToServers, waitJobs } from '@shared/extra-utils' const expect = chai.expect -async function checkServer1And2HasFollowers (servers: ServerInfo[], state = 'accepted') { +async function checkServer1And2HasFollowers (servers: PeerTubeServer[], state = 'accepted') { const fns = [ servers[0].follows.getFollowings.bind(servers[0].follows), servers[1].follows.getFollowers.bind(servers[1].follows) @@ -30,7 +30,7 @@ async function checkServer1And2HasFollowers (servers: ServerInfo[], state = 'acc } } -async function checkNoFollowers (servers: ServerInfo[]) { +async function checkNoFollowers (servers: PeerTubeServer[]) { const fns = [ servers[0].follows.getFollowings.bind(servers[0].follows), servers[1].follows.getFollowers.bind(servers[1].follows) @@ -43,13 +43,13 @@ async function checkNoFollowers (servers: ServerInfo[]) { } describe('Test follows moderation', function () { - let servers: ServerInfo[] = [] + let servers: PeerTubeServer[] = [] let commands: FollowsCommand[] before(async function () { this.timeout(30000) - servers = await flushAndRunMultipleServers(3) + servers = await createMultipleServers(3) // Get the access tokens await setAccessTokensToServers(servers) diff --git a/server/tests/api/server/follows.ts b/server/tests/api/server/follows.ts index d43064689..8856177b8 100644 --- a/server/tests/api/server/follows.ts +++ b/server/tests/api/server/follows.ts @@ -7,9 +7,9 @@ import { completeVideoCheck, dateIsValid, expectAccountFollows, - flushAndRunMultipleServers, + createMultipleServers, FollowsCommand, - ServerInfo, + PeerTubeServer, setAccessTokensToServers, testCaptionFile, waitJobs @@ -19,13 +19,13 @@ import { Video, VideoPrivacy } from '@shared/models' const expect = chai.expect describe('Test follows', function () { - let servers: ServerInfo[] = [] + let servers: PeerTubeServer[] = [] let followsCommands: FollowsCommand[] before(async function () { this.timeout(30000) - servers = await flushAndRunMultipleServers(3) + servers = await createMultipleServers(3) followsCommands = servers.map(s => s.follows) // Get the access tokens diff --git a/server/tests/api/server/handle-down.ts b/server/tests/api/server/handle-down.ts index de3dee826..5f20b0093 100644 --- a/server/tests/api/server/handle-down.ts +++ b/server/tests/api/server/handle-down.ts @@ -7,10 +7,9 @@ import { cleanupTests, CommentsCommand, completeVideoCheck, - flushAndRunMultipleServers, + createMultipleServers, killallServers, - reRunServer, - ServerInfo, + PeerTubeServer, setAccessTokensToServers, wait, waitJobs @@ -20,7 +19,7 @@ import { JobState, VideoCreateResult, VideoPrivacy } from '@shared/models' const expect = chai.expect describe('Test handle downs', function () { - let servers: ServerInfo[] = [] + let servers: PeerTubeServer[] = [] let threadIdServer1: number let threadIdServer2: number let commentIdServer1: number @@ -54,7 +53,7 @@ describe('Test handle downs', function () { before(async function () { this.timeout(30000) - servers = await flushAndRunMultipleServers(3) + servers = await createMultipleServers(3) commentCommands = servers.map(s => s.comments) checkAttributes = { @@ -176,8 +175,8 @@ describe('Test handle downs', function () { it('Should re-follow server 1', async function () { this.timeout(35000) - await reRunServer(servers[1]) - await reRunServer(servers[2]) + await servers[1].run() + await servers[2].run() await servers[1].follows.unfollow({ target: servers[0] }) await waitJobs(servers) diff --git a/server/tests/api/server/homepage.ts b/server/tests/api/server/homepage.ts index aac075321..c291037f2 100644 --- a/server/tests/api/server/homepage.ts +++ b/server/tests/api/server/homepage.ts @@ -6,29 +6,28 @@ import { HttpStatusCode } from '@shared/core-utils' import { cleanupTests, CustomPagesCommand, - flushAndRunServer, + createSingleServer, killallServers, - reRunServer, - ServerInfo, + PeerTubeServer, setAccessTokensToServers } from '../../../../shared/extra-utils/index' const expect = chai.expect -async function getHomepageState (server: ServerInfo) { +async function getHomepageState (server: PeerTubeServer) { const config = await server.config.getConfig() return config.homepage.enabled } describe('Test instance homepage actions', function () { - let server: ServerInfo + let server: PeerTubeServer let command: CustomPagesCommand before(async function () { this.timeout(30000) - server = await flushAndRunServer(1) + server = await createSingleServer(1) await setAccessTokensToServers([ server ]) command = server.customPage @@ -56,7 +55,7 @@ describe('Test instance homepage actions', function () { await killallServers([ server ]) - await reRunServer(server) + await server.run() const page = await command.getInstanceHomepage() expect(page.content).to.equal('') diff --git a/server/tests/api/server/jobs.ts b/server/tests/api/server/jobs.ts index 0c44e4dad..376cd10d0 100644 --- a/server/tests/api/server/jobs.ts +++ b/server/tests/api/server/jobs.ts @@ -6,8 +6,8 @@ import { cleanupTests, dateIsValid, doubleFollow, - flushAndRunMultipleServers, - ServerInfo, + createMultipleServers, + PeerTubeServer, setAccessTokensToServers, waitJobs } from '@shared/extra-utils' @@ -15,12 +15,12 @@ import { const expect = chai.expect describe('Test jobs', function () { - let servers: ServerInfo[] + let servers: PeerTubeServer[] before(async function () { this.timeout(30000) - servers = await flushAndRunMultipleServers(2) + servers = await createMultipleServers(2) await setAccessTokensToServers(servers) diff --git a/server/tests/api/server/logs.ts b/server/tests/api/server/logs.ts index 2d141fd8c..bcd94dda3 100644 --- a/server/tests/api/server/logs.ts +++ b/server/tests/api/server/logs.ts @@ -4,11 +4,10 @@ import 'mocha' import * as chai from 'chai' import { cleanupTests, - flushAndRunServer, + createSingleServer, killallServers, LogsCommand, - reRunServer, - ServerInfo, + PeerTubeServer, setAccessTokensToServers, waitJobs } from '@shared/extra-utils' @@ -16,13 +15,13 @@ import { const expect = chai.expect describe('Test logs', function () { - let server: ServerInfo + let server: PeerTubeServer let logsCommand: LogsCommand before(async function () { this.timeout(30000) - server = await flushAndRunServer(1) + server = await createSingleServer(1) await setAccessTokensToServers([ server ]) logsCommand = server.logs @@ -113,7 +112,7 @@ describe('Test logs', function () { await killallServers([ server ]) - await reRunServer(server, { log: { log_ping_requests: false } }) + await server.run({ log: { log_ping_requests: false } }) const now = new Date() diff --git a/server/tests/api/server/no-client.ts b/server/tests/api/server/no-client.ts index d589f51f3..f45222f2f 100644 --- a/server/tests/api/server/no-client.ts +++ b/server/tests/api/server/no-client.ts @@ -1,16 +1,16 @@ import 'mocha' import * as request from 'supertest' -import { ServerInfo } from '../../../../shared/extra-utils' -import { cleanupTests, flushAndRunServer } from '../../../../shared/extra-utils/server/servers' +import { PeerTubeServer } from '../../../../shared/extra-utils' +import { cleanupTests, createSingleServer } from '../../../../shared/extra-utils/server/servers' import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' describe('Start and stop server without web client routes', function () { - let server: ServerInfo + let server: PeerTubeServer before(async function () { this.timeout(30000) - server = await flushAndRunServer(1, {}, [ '--no-client' ]) + server = await createSingleServer(1, {}, [ '--no-client' ]) }) it('Should fail getting the client', function () { diff --git a/server/tests/api/server/plugins.ts b/server/tests/api/server/plugins.ts index 45a22e48d..db03d026a 100644 --- a/server/tests/api/server/plugins.ts +++ b/server/tests/api/server/plugins.ts @@ -5,11 +5,10 @@ import * as chai from 'chai' import { HttpStatusCode } from '@shared/core-utils' import { cleanupTests, - flushAndRunServer, + createSingleServer, killallServers, PluginsCommand, - reRunServer, - ServerInfo, + PeerTubeServer, setAccessTokensToServers, testHelloWorldRegisteredSettings, wait @@ -19,7 +18,7 @@ import { PluginType } from '@shared/models' const expect = chai.expect describe('Test plugins', function () { - let server: ServerInfo = null + let server: PeerTubeServer = null let command: PluginsCommand before(async function () { @@ -30,7 +29,7 @@ describe('Test plugins', function () { index: { check_latest_versions_interval: '5 seconds' } } } - server = await flushAndRunServer(1, configOverride) + server = await createSingleServer(1, configOverride) await setAccessTokensToServers([ server ]) command = server.plugins @@ -245,7 +244,7 @@ describe('Test plugins', function () { // Restart the server to take into account this change await killallServers([ server ]) - await reRunServer(server) + await server.run() { const body = await command.list({ pluginType: PluginType.PLUGIN }) @@ -326,7 +325,7 @@ describe('Test plugins', function () { await check() await killallServers([ server ]) - await reRunServer(server) + await server.run() await check() }) diff --git a/server/tests/api/server/reverse-proxy.ts b/server/tests/api/server/reverse-proxy.ts index de3cf02f2..c20b7a5f0 100644 --- a/server/tests/api/server/reverse-proxy.ts +++ b/server/tests/api/server/reverse-proxy.ts @@ -2,10 +2,10 @@ import { expect } from 'chai' import { HttpStatusCode } from '@shared/core-utils' -import { cleanupTests, flushAndRunServer, ServerInfo, setAccessTokensToServers, wait } from '@shared/extra-utils' +import { cleanupTests, createSingleServer, PeerTubeServer, setAccessTokensToServers, wait } from '@shared/extra-utils' describe('Test application behind a reverse proxy', function () { - let server: ServerInfo + let server: PeerTubeServer let videoId: string before(async function () { @@ -30,7 +30,7 @@ describe('Test application behind a reverse proxy', function () { } } - server = await flushAndRunServer(1, config) + server = await createSingleServer(1, config) await setAccessTokensToServers([ server ]) const { uuid } = await server.videos.upload() diff --git a/server/tests/api/server/services.ts b/server/tests/api/server/services.ts index 28f9ae3b6..69d030dbb 100644 --- a/server/tests/api/server/services.ts +++ b/server/tests/api/server/services.ts @@ -2,13 +2,13 @@ import 'mocha' import * as chai from 'chai' -import { cleanupTests, flushAndRunServer, ServerInfo, setAccessTokensToServers, setDefaultVideoChannel } from '@shared/extra-utils' +import { cleanupTests, createSingleServer, PeerTubeServer, setAccessTokensToServers, setDefaultVideoChannel } from '@shared/extra-utils' import { Video, VideoPlaylistPrivacy } from '@shared/models' const expect = chai.expect describe('Test services', function () { - let server: ServerInfo = null + let server: PeerTubeServer = null let playlistUUID: string let playlistDisplayName: string let video: Video @@ -16,7 +16,7 @@ describe('Test services', function () { before(async function () { this.timeout(30000) - server = await flushAndRunServer(1) + server = await createSingleServer(1) await setAccessTokensToServers([ server ]) await setDefaultVideoChannel([ server ]) diff --git a/server/tests/api/server/stats.ts b/server/tests/api/server/stats.ts index be5abad52..f07d0fd39 100644 --- a/server/tests/api/server/stats.ts +++ b/server/tests/api/server/stats.ts @@ -5,8 +5,8 @@ import * as chai from 'chai' import { cleanupTests, doubleFollow, - flushAndRunMultipleServers, - ServerInfo, + createMultipleServers, + PeerTubeServer, setAccessTokensToServers, wait, waitJobs @@ -16,7 +16,7 @@ import { ActivityType, VideoPlaylistPrivacy } from '@shared/models' const expect = chai.expect describe('Test stats (excluding redundancy)', function () { - let servers: ServerInfo[] = [] + let servers: PeerTubeServer[] = [] let channelId const user = { username: 'user1', @@ -26,7 +26,7 @@ describe('Test stats (excluding redundancy)', function () { before(async function () { this.timeout(60000) - servers = await flushAndRunMultipleServers(3) + servers = await createMultipleServers(3) await setAccessTokensToServers(servers) diff --git a/server/tests/api/server/tracker.ts b/server/tests/api/server/tracker.ts index d80362fee..f597ac60c 100644 --- a/server/tests/api/server/tracker.ts +++ b/server/tests/api/server/tracker.ts @@ -3,16 +3,16 @@ import 'mocha' import * as magnetUtil from 'magnet-uri' import * as WebTorrent from 'webtorrent' -import { cleanupTests, flushAndRunServer, killallServers, reRunServer, ServerInfo, setAccessTokensToServers } from '@shared/extra-utils' +import { cleanupTests, createSingleServer, killallServers, PeerTubeServer, setAccessTokensToServers } from '@shared/extra-utils' describe('Test tracker', function () { - let server: ServerInfo + let server: PeerTubeServer let badMagnet: string let goodMagnet: string before(async function () { this.timeout(60000) - server = await flushAndRunServer(1) + server = await createSingleServer(1) await setAccessTokensToServers([ server ]) { @@ -48,7 +48,7 @@ describe('Test tracker', function () { const errCb = () => done(new Error('Tracker is enabled')) killallServers([ server ]) - .then(() => reRunServer(server, { tracker: { enabled: false } })) + .then(() => server.run({ tracker: { enabled: false } })) .then(() => { const webtorrent = new WebTorrent() @@ -72,7 +72,7 @@ describe('Test tracker', function () { this.timeout(20000) killallServers([ server ]) - .then(() => reRunServer(server)) + .then(() => server.run()) .then(() => { const webtorrent = new WebTorrent() diff --git a/server/tests/api/users/user-subscriptions.ts b/server/tests/api/users/user-subscriptions.ts index 1b15a98dc..d2bb9c387 100644 --- a/server/tests/api/users/user-subscriptions.ts +++ b/server/tests/api/users/user-subscriptions.ts @@ -5,8 +5,8 @@ import * as chai from 'chai' import { cleanupTests, doubleFollow, - flushAndRunMultipleServers, - ServerInfo, + createMultipleServers, + PeerTubeServer, setAccessTokensToServers, SubscriptionsCommand, waitJobs @@ -15,7 +15,7 @@ import { const expect = chai.expect describe('Test users subscriptions', function () { - let servers: ServerInfo[] = [] + let servers: PeerTubeServer[] = [] const users: { accessToken: string }[] = [] let video3UUID: string @@ -24,7 +24,7 @@ describe('Test users subscriptions', function () { before(async function () { this.timeout(120000) - servers = await flushAndRunMultipleServers(3) + servers = await createMultipleServers(3) // Get the access tokens await setAccessTokensToServers(servers) diff --git a/server/tests/api/users/users-multiple-servers.ts b/server/tests/api/users/users-multiple-servers.ts index f8d7ae88e..e629966bb 100644 --- a/server/tests/api/users/users-multiple-servers.ts +++ b/server/tests/api/users/users-multiple-servers.ts @@ -8,8 +8,8 @@ import { checkVideoFilesWereRemoved, cleanupTests, doubleFollow, - flushAndRunMultipleServers, - ServerInfo, + createMultipleServers, + PeerTubeServer, setAccessTokensToServers, testImage, waitJobs @@ -19,7 +19,7 @@ import { User } from '@shared/models' const expect = chai.expect describe('Test users with multiple servers', function () { - let servers: ServerInfo[] = [] + let servers: PeerTubeServer[] = [] let user: User let userId: number let videoUUID: string @@ -29,7 +29,7 @@ describe('Test users with multiple servers', function () { before(async function () { this.timeout(120_000) - servers = await flushAndRunMultipleServers(3) + servers = await createMultipleServers(3) // Get the access tokens await setAccessTokensToServers(servers) diff --git a/server/tests/api/users/users-verification.ts b/server/tests/api/users/users-verification.ts index c8c226fa8..5dbe2af59 100644 --- a/server/tests/api/users/users-verification.ts +++ b/server/tests/api/users/users-verification.ts @@ -3,12 +3,12 @@ import 'mocha' import * as chai from 'chai' import { HttpStatusCode } from '@shared/core-utils' -import { cleanupTests, flushAndRunServer, MockSmtpServer, ServerInfo, setAccessTokensToServers, waitJobs } from '@shared/extra-utils' +import { cleanupTests, createSingleServer, MockSmtpServer, PeerTubeServer, setAccessTokensToServers, waitJobs } from '@shared/extra-utils' const expect = chai.expect describe('Test users account verification', function () { - let server: ServerInfo + let server: PeerTubeServer let userId: number let userAccessToken: string let verificationString: string @@ -34,7 +34,7 @@ describe('Test users account verification', function () { port } } - server = await flushAndRunServer(1, overrideConfig) + server = await createSingleServer(1, overrideConfig) await setAccessTokensToServers([ server ]) }) diff --git a/server/tests/api/users/users.ts b/server/tests/api/users/users.ts index 310136a37..6ae5410b3 100644 --- a/server/tests/api/users/users.ts +++ b/server/tests/api/users/users.ts @@ -5,11 +5,10 @@ import * as chai from 'chai' import { HttpStatusCode } from '@shared/core-utils' import { cleanupTests, - flushAndRunServer, + createSingleServer, killallServers, makePutBodyRequest, - reRunServer, - ServerInfo, + PeerTubeServer, setAccessTokensToServers, testImage, waitJobs @@ -19,7 +18,7 @@ import { AbuseState, OAuth2ErrorCode, UserAdminFlag, UserRole, Video, VideoPlayl const expect = chai.expect describe('Test users', function () { - let server: ServerInfo + let server: PeerTubeServer let token: string let userToken: string let videoId: number @@ -32,7 +31,7 @@ describe('Test users', function () { before(async function () { this.timeout(30000) - server = await flushAndRunServer(1, { + server = await createSingleServer(1, { rates_limit: { login: { max: 30 @@ -238,7 +237,7 @@ describe('Test users', function () { await server.sql.setTokenField(server.accessToken, 'refreshTokenExpiresAt', new Date().toISOString()) await killallServers([ server ]) - await reRunServer(server) + await server.run() await server.users.getMyInfo({ expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -254,7 +253,7 @@ describe('Test users', function () { await server.sql.setTokenField(server.accessToken, 'refreshTokenExpiresAt', futureDate) await killallServers([ server ]) - await reRunServer(server) + await server.run() const res = await server.login.refreshToken({ refreshToken: server.refreshToken }) server.accessToken = res.body.access_token diff --git a/server/tests/api/videos/audio-only.ts b/server/tests/api/videos/audio-only.ts index b2952e38b..b9bf96650 100644 --- a/server/tests/api/videos/audio-only.ts +++ b/server/tests/api/videos/audio-only.ts @@ -4,12 +4,12 @@ import 'mocha' import * as chai from 'chai' import { join } from 'path' import { getAudioStream, getVideoStreamSize } from '@server/helpers/ffprobe-utils' -import { cleanupTests, doubleFollow, flushAndRunMultipleServers, ServerInfo, setAccessTokensToServers, waitJobs } from '@shared/extra-utils' +import { cleanupTests, doubleFollow, createMultipleServers, PeerTubeServer, setAccessTokensToServers, waitJobs } from '@shared/extra-utils' const expect = chai.expect describe('Test audio only video transcoding', function () { - let servers: ServerInfo[] = [] + let servers: PeerTubeServer[] = [] let videoUUID: string before(async function () { @@ -36,7 +36,7 @@ describe('Test audio only video transcoding', function () { } } } - servers = await flushAndRunMultipleServers(2, configOverride) + servers = await createMultipleServers(2, configOverride) // Get the access tokens await setAccessTokensToServers(servers) diff --git a/server/tests/api/videos/multiple-servers.ts b/server/tests/api/videos/multiple-servers.ts index 89d842307..562079a15 100644 --- a/server/tests/api/videos/multiple-servers.ts +++ b/server/tests/api/videos/multiple-servers.ts @@ -12,8 +12,8 @@ import { completeVideoCheck, dateIsValid, doubleFollow, - flushAndRunMultipleServers, - ServerInfo, + createMultipleServers, + PeerTubeServer, setAccessTokensToServers, testImage, wait, @@ -25,7 +25,7 @@ import { VideoCommentThreadTree, VideoPrivacy } from '@shared/models' const expect = chai.expect describe('Test multiple servers', function () { - let servers: ServerInfo[] = [] + let servers: PeerTubeServer[] = [] const toRemove = [] let videoUUID = '' let videoChannelId: number @@ -33,7 +33,7 @@ describe('Test multiple servers', function () { before(async function () { this.timeout(120000) - servers = await flushAndRunMultipleServers(3) + servers = await createMultipleServers(3) // Get the access tokens await setAccessTokensToServers(servers) diff --git a/server/tests/api/videos/resumable-upload.ts b/server/tests/api/videos/resumable-upload.ts index 2f1cf8a55..b4fc5ee09 100644 --- a/server/tests/api/videos/resumable-upload.ts +++ b/server/tests/api/videos/resumable-upload.ts @@ -8,8 +8,8 @@ import { HttpStatusCode } from '@shared/core-utils' import { buildAbsoluteFixturePath, cleanupTests, - flushAndRunServer, - ServerInfo, + createSingleServer, + PeerTubeServer, setAccessTokensToServers, setDefaultVideoChannel } from '@shared/extra-utils' @@ -21,7 +21,7 @@ const expect = chai.expect describe('Test resumable upload', function () { const defaultFixture = 'video_short.mp4' - let server: ServerInfo + let server: PeerTubeServer let rootId: number async function buildSize (fixture: string, size?: number) { @@ -99,7 +99,7 @@ describe('Test resumable upload', function () { before(async function () { this.timeout(30000) - server = await flushAndRunServer(1) + server = await createSingleServer(1) await setAccessTokensToServers([ server ]) await setDefaultVideoChannel([ server ]) diff --git a/server/tests/api/videos/single-server.ts b/server/tests/api/videos/single-server.ts index 12c1f7b2f..c0535be09 100644 --- a/server/tests/api/videos/single-server.ts +++ b/server/tests/api/videos/single-server.ts @@ -6,8 +6,8 @@ import { checkVideoFilesWereRemoved, cleanupTests, completeVideoCheck, - flushAndRunServer, - ServerInfo, + createSingleServer, + PeerTubeServer, setAccessTokensToServers, testImage, wait @@ -19,7 +19,7 @@ const expect = chai.expect describe('Test a single server', function () { function runSuite (mode: 'legacy' | 'resumable') { - let server: ServerInfo = null + let server: PeerTubeServer = null let videoId: number | string let videoId2: string let videoUUID = '' @@ -94,7 +94,7 @@ describe('Test a single server', function () { before(async function () { this.timeout(30000) - server = await flushAndRunServer(1) + server = await createSingleServer(1) await setAccessTokensToServers([ server ]) }) diff --git a/server/tests/api/videos/video-captions.ts b/server/tests/api/videos/video-captions.ts index abc07194d..6caba6aa6 100644 --- a/server/tests/api/videos/video-captions.ts +++ b/server/tests/api/videos/video-captions.ts @@ -6,8 +6,8 @@ import { checkVideoFilesWereRemoved, cleanupTests, doubleFollow, - flushAndRunMultipleServers, - ServerInfo, + createMultipleServers, + PeerTubeServer, setAccessTokensToServers, testCaptionFile, wait, @@ -19,13 +19,13 @@ const expect = chai.expect describe('Test video captions', function () { const uuidRegex = '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}' - let servers: ServerInfo[] + let servers: PeerTubeServer[] let videoUUID: string before(async function () { this.timeout(60000) - servers = await flushAndRunMultipleServers(2) + servers = await createMultipleServers(2) await setAccessTokensToServers(servers) await doubleFollow(servers[0], servers[1]) diff --git a/server/tests/api/videos/video-change-ownership.ts b/server/tests/api/videos/video-change-ownership.ts index 352eb5ea3..cefddb68e 100644 --- a/server/tests/api/videos/video-change-ownership.ts +++ b/server/tests/api/videos/video-change-ownership.ts @@ -7,9 +7,9 @@ import { ChangeOwnershipCommand, cleanupTests, doubleFollow, - flushAndRunMultipleServers, - flushAndRunServer, - ServerInfo, + createMultipleServers, + createSingleServer, + PeerTubeServer, setAccessTokensToServers, setDefaultVideoChannel, waitJobs @@ -19,7 +19,7 @@ import { VideoPrivacy } from '@shared/models' const expect = chai.expect describe('Test video change ownership - nominal', function () { - let servers: ServerInfo[] = [] + let servers: PeerTubeServer[] = [] const firstUser = 'first' const secondUser = 'second' @@ -39,7 +39,7 @@ describe('Test video change ownership - nominal', function () { before(async function () { this.timeout(50000) - servers = await flushAndRunMultipleServers(2) + servers = await createMultipleServers(2) await setAccessTokensToServers(servers) await setDefaultVideoChannel(servers) @@ -251,7 +251,7 @@ describe('Test video change ownership - nominal', function () { }) describe('Test video change ownership - quota too small', function () { - let server: ServerInfo + let server: PeerTubeServer const firstUser = 'first' const secondUser = 'second' @@ -263,7 +263,7 @@ describe('Test video change ownership - quota too small', function () { this.timeout(50000) // Run one server - server = await flushAndRunServer(1) + server = await createSingleServer(1) await setAccessTokensToServers([ server ]) await server.users.create({ username: secondUser, videoQuota: 10 }) diff --git a/server/tests/api/videos/video-channels.ts b/server/tests/api/videos/video-channels.ts index 1efef932c..140fee7fe 100644 --- a/server/tests/api/videos/video-channels.ts +++ b/server/tests/api/videos/video-channels.ts @@ -7,8 +7,8 @@ import { ACTOR_IMAGES_SIZE } from '@server/initializers/constants' import { cleanupTests, doubleFollow, - flushAndRunMultipleServers, - ServerInfo, + createMultipleServers, + PeerTubeServer, setAccessTokensToServers, setDefaultVideoChannel, testFileExistsOrNot, @@ -20,14 +20,14 @@ import { User, VideoChannel } from '@shared/models' const expect = chai.expect -async function findChannel (server: ServerInfo, channelId: number) { +async function findChannel (server: PeerTubeServer, channelId: number) { const body = await server.channels.list({ sort: '-name' }) return body.data.find(c => c.id === channelId) } describe('Test video channels', function () { - let servers: ServerInfo[] + let servers: PeerTubeServer[] let userInfo: User let secondVideoChannelId: number let totoChannel: number @@ -40,7 +40,7 @@ describe('Test video channels', function () { before(async function () { this.timeout(60000) - servers = await flushAndRunMultipleServers(2) + servers = await createMultipleServers(2) await setAccessTokensToServers(servers) await setDefaultVideoChannel(servers) diff --git a/server/tests/api/videos/video-comments.ts b/server/tests/api/videos/video-comments.ts index adb59bd74..9709e0628 100644 --- a/server/tests/api/videos/video-comments.ts +++ b/server/tests/api/videos/video-comments.ts @@ -6,8 +6,8 @@ import { cleanupTests, CommentsCommand, dateIsValid, - flushAndRunServer, - ServerInfo, + createSingleServer, + PeerTubeServer, setAccessTokensToServers, testImage } from '@shared/extra-utils' @@ -15,7 +15,7 @@ import { const expect = chai.expect describe('Test video comments', function () { - let server: ServerInfo + let server: PeerTubeServer let videoId: number let videoUUID: string let threadId: number @@ -28,7 +28,7 @@ describe('Test video comments', function () { before(async function () { this.timeout(30000) - server = await flushAndRunServer(1) + server = await createSingleServer(1) await setAccessTokensToServers([ server ]) diff --git a/server/tests/api/videos/video-description.ts b/server/tests/api/videos/video-description.ts index b89247288..ce45eac80 100644 --- a/server/tests/api/videos/video-description.ts +++ b/server/tests/api/videos/video-description.ts @@ -2,12 +2,12 @@ import 'mocha' import * as chai from 'chai' -import { cleanupTests, doubleFollow, flushAndRunMultipleServers, ServerInfo, setAccessTokensToServers, waitJobs } from '@shared/extra-utils' +import { cleanupTests, doubleFollow, createMultipleServers, PeerTubeServer, setAccessTokensToServers, waitJobs } from '@shared/extra-utils' const expect = chai.expect describe('Test video description', function () { - let servers: ServerInfo[] = [] + let servers: PeerTubeServer[] = [] let videoUUID = '' let videoId: number const longDescription = 'my super description for server 1'.repeat(50) @@ -16,7 +16,7 @@ describe('Test video description', function () { this.timeout(40000) // Run servers - servers = await flushAndRunMultipleServers(2) + servers = await createMultipleServers(2) // Get the access tokens await setAccessTokensToServers(servers) diff --git a/server/tests/api/videos/video-hls.ts b/server/tests/api/videos/video-hls.ts index 9d79f2683..4c4b18887 100644 --- a/server/tests/api/videos/video-hls.ts +++ b/server/tests/api/videos/video-hls.ts @@ -11,9 +11,9 @@ import { checkTmpIsEmpty, cleanupTests, doubleFollow, - flushAndRunMultipleServers, + createMultipleServers, makeRawRequest, - ServerInfo, + PeerTubeServer, setAccessTokensToServers, waitJobs, webtorrentAdd @@ -23,7 +23,7 @@ import { DEFAULT_AUDIO_RESOLUTION } from '../../../initializers/constants' const expect = chai.expect -async function checkHlsPlaylist (servers: ServerInfo[], videoUUID: string, hlsOnly: boolean, resolutions = [ 240, 360, 480, 720 ]) { +async function checkHlsPlaylist (servers: PeerTubeServer[], videoUUID: string, hlsOnly: boolean, resolutions = [ 240, 360, 480, 720 ]) { for (const server of servers) { const videoDetails = await server.videos.get({ id: videoUUID }) const baseUrl = `http://${videoDetails.account.host}` @@ -98,7 +98,7 @@ async function checkHlsPlaylist (servers: ServerInfo[], videoUUID: string, hlsOn } describe('Test HLS videos', function () { - let servers: ServerInfo[] = [] + let servers: PeerTubeServer[] = [] let videoUUID = '' let videoAudioUUID = '' @@ -176,7 +176,7 @@ describe('Test HLS videos', function () { } } } - servers = await flushAndRunMultipleServers(2, configOverride) + servers = await createMultipleServers(2, configOverride) // Get the access tokens await setAccessTokensToServers(servers) diff --git a/server/tests/api/videos/video-imports.ts b/server/tests/api/videos/video-imports.ts index 8b6542aa4..4ef55c3af 100644 --- a/server/tests/api/videos/video-imports.ts +++ b/server/tests/api/videos/video-imports.ts @@ -6,9 +6,9 @@ import { areHttpImportTestsDisabled, cleanupTests, doubleFollow, - flushAndRunMultipleServers, + createMultipleServers, ImportsCommand, - ServerInfo, + PeerTubeServer, setAccessTokensToServers, testCaptionFile, testImage, @@ -19,13 +19,13 @@ import { VideoPrivacy, VideoResolution } from '@shared/models' const expect = chai.expect describe('Test video imports', function () { - let servers: ServerInfo[] = [] + let servers: PeerTubeServer[] = [] let channelIdServer1: number let channelIdServer2: number if (areHttpImportTestsDisabled()) return - async function checkVideosServer1 (server: ServerInfo, idHttp: string, idMagnet: string, idTorrent: string) { + async function checkVideosServer1 (server: PeerTubeServer, idHttp: string, idMagnet: string, idTorrent: string) { const videoHttp = await server.videos.get({ id: idHttp }) expect(videoHttp.name).to.equal('small video - youtube') @@ -63,7 +63,7 @@ describe('Test video imports', function () { expect(bodyCaptions.total).to.equal(2) } - async function checkVideoServer2 (server: ServerInfo, id: number | string) { + async function checkVideoServer2 (server: PeerTubeServer, id: number | string) { const video = await server.videos.get({ id }) expect(video.name).to.equal('my super name') @@ -84,7 +84,7 @@ describe('Test video imports', function () { this.timeout(30_000) // Run servers - servers = await flushAndRunMultipleServers(2) + servers = await createMultipleServers(2) await setAccessTokensToServers(servers) diff --git a/server/tests/api/videos/video-nsfw.ts b/server/tests/api/videos/video-nsfw.ts index 95395a582..b25dcda20 100644 --- a/server/tests/api/videos/video-nsfw.ts +++ b/server/tests/api/videos/video-nsfw.ts @@ -2,7 +2,7 @@ import 'mocha' import * as chai from 'chai' -import { cleanupTests, flushAndRunServer, ServerInfo, setAccessTokensToServers } from '@shared/extra-utils' +import { cleanupTests, createSingleServer, PeerTubeServer, setAccessTokensToServers } from '@shared/extra-utils' import { BooleanBothQuery, CustomConfig, ResultList, Video, VideosOverview } from '@shared/models' const expect = chai.expect @@ -13,7 +13,7 @@ function createOverviewRes (overview: VideosOverview) { } describe('Test video NSFW policy', function () { - let server: ServerInfo + let server: PeerTubeServer let userAccessToken: string let customConfig: CustomConfig @@ -61,7 +61,7 @@ describe('Test video NSFW policy', function () { before(async function () { this.timeout(50000) - server = await flushAndRunServer(1) + server = await createSingleServer(1) // Get the access tokens await setAccessTokensToServers([ server ]) diff --git a/server/tests/api/videos/video-playlist-thumbnails.ts b/server/tests/api/videos/video-playlist-thumbnails.ts index 709f64c4d..9a682c12b 100644 --- a/server/tests/api/videos/video-playlist-thumbnails.ts +++ b/server/tests/api/videos/video-playlist-thumbnails.ts @@ -5,8 +5,8 @@ import * as chai from 'chai' import { cleanupTests, doubleFollow, - flushAndRunMultipleServers, - ServerInfo, + createMultipleServers, + PeerTubeServer, setAccessTokensToServers, setDefaultVideoChannel, testImage, @@ -17,7 +17,7 @@ import { VideoPlaylistPrivacy } from '../../../../shared/models/videos/playlist/ const expect = chai.expect describe('Playlist thumbnail', function () { - let servers: ServerInfo[] = [] + let servers: PeerTubeServer[] = [] let playlistWithoutThumbnailId: number let playlistWithThumbnailId: number @@ -30,13 +30,13 @@ describe('Playlist thumbnail', function () { let video1: number let video2: number - async function getPlaylistWithoutThumbnail (server: ServerInfo) { + async function getPlaylistWithoutThumbnail (server: PeerTubeServer) { const body = await server.playlists.list({ start: 0, count: 10 }) return body.data.find(p => p.displayName === 'playlist without thumbnail') } - async function getPlaylistWithThumbnail (server: ServerInfo) { + async function getPlaylistWithThumbnail (server: PeerTubeServer) { const body = await server.playlists.list({ start: 0, count: 10 }) return body.data.find(p => p.displayName === 'playlist with thumbnail') @@ -45,7 +45,7 @@ describe('Playlist thumbnail', function () { before(async function () { this.timeout(120000) - servers = await flushAndRunMultipleServers(2, { transcoding: { enabled: false } }) + servers = await createMultipleServers(2, { transcoding: { enabled: false } }) // Get the access tokens await setAccessTokensToServers(servers) diff --git a/server/tests/api/videos/video-playlists.ts b/server/tests/api/videos/video-playlists.ts index 0dc53d4c0..71ca3e63a 100644 --- a/server/tests/api/videos/video-playlists.ts +++ b/server/tests/api/videos/video-playlists.ts @@ -7,9 +7,9 @@ import { checkPlaylistFilesWereRemoved, cleanupTests, doubleFollow, - flushAndRunMultipleServers, + createMultipleServers, PlaylistsCommand, - ServerInfo, + PeerTubeServer, setAccessTokensToServers, setDefaultVideoChannel, testImage, @@ -28,7 +28,7 @@ import { const expect = chai.expect async function checkPlaylistElementType ( - servers: ServerInfo[], + servers: PeerTubeServer[], playlistId: string, type: VideoPlaylistElementType, position: number, @@ -52,7 +52,7 @@ async function checkPlaylistElementType ( } describe('Test video playlists', function () { - let servers: ServerInfo[] = [] + let servers: PeerTubeServer[] = [] let playlistServer2Id1: number let playlistServer2Id2: number @@ -75,7 +75,7 @@ describe('Test video playlists', function () { before(async function () { this.timeout(120000) - servers = await flushAndRunMultipleServers(3, { transcoding: { enabled: false } }) + servers = await createMultipleServers(3, { transcoding: { enabled: false } }) // Get the access tokens await setAccessTokensToServers(servers) @@ -584,10 +584,10 @@ describe('Test video playlists', function () { }) describe('Element type', function () { - let groupUser1: ServerInfo[] - let groupWithoutToken1: ServerInfo[] - let group1: ServerInfo[] - let group2: ServerInfo[] + let groupUser1: PeerTubeServer[] + let groupWithoutToken1: PeerTubeServer[] + let group1: PeerTubeServer[] + let group2: PeerTubeServer[] let video1: string let video2: string diff --git a/server/tests/api/videos/video-privacy.ts b/server/tests/api/videos/video-privacy.ts index de08a9e7b..5ec626155 100644 --- a/server/tests/api/videos/video-privacy.ts +++ b/server/tests/api/videos/video-privacy.ts @@ -3,13 +3,13 @@ import 'mocha' import * as chai from 'chai' import { HttpStatusCode } from '@shared/core-utils' -import { cleanupTests, doubleFollow, flushAndRunServer, ServerInfo, setAccessTokensToServers, waitJobs } from '@shared/extra-utils' +import { cleanupTests, doubleFollow, createSingleServer, PeerTubeServer, setAccessTokensToServers, waitJobs } from '@shared/extra-utils' import { VideoCreateResult, VideoPrivacy } from '@shared/models' const expect = chai.expect describe('Test video privacy', function () { - const servers: ServerInfo[] = [] + const servers: PeerTubeServer[] = [] let anotherUserToken: string let privateVideoId: number @@ -35,8 +35,8 @@ describe('Test video privacy', function () { this.timeout(50000) // Run servers - servers.push(await flushAndRunServer(1, dontFederateUnlistedConfig)) - servers.push(await flushAndRunServer(2)) + servers.push(await createSingleServer(1, dontFederateUnlistedConfig)) + servers.push(await createSingleServer(2)) // Get the access tokens await setAccessTokensToServers(servers) diff --git a/server/tests/api/videos/video-schedule-update.ts b/server/tests/api/videos/video-schedule-update.ts index 3938b47c8..22b5cf1c2 100644 --- a/server/tests/api/videos/video-schedule-update.ts +++ b/server/tests/api/videos/video-schedule-update.ts @@ -5,8 +5,8 @@ import * as chai from 'chai' import { cleanupTests, doubleFollow, - flushAndRunMultipleServers, - ServerInfo, + createMultipleServers, + PeerTubeServer, setAccessTokensToServers, wait, waitJobs @@ -23,14 +23,14 @@ function in10Seconds () { } describe('Test video update scheduler', function () { - let servers: ServerInfo[] = [] + let servers: PeerTubeServer[] = [] let video2UUID: string before(async function () { this.timeout(30000) // Run servers - servers = await flushAndRunMultipleServers(2) + servers = await createMultipleServers(2) await setAccessTokensToServers(servers) diff --git a/server/tests/api/videos/video-transcoder.ts b/server/tests/api/videos/video-transcoder.ts index 37450eeeb..2465d2d89 100644 --- a/server/tests/api/videos/video-transcoder.ts +++ b/server/tests/api/videos/video-transcoder.ts @@ -9,11 +9,11 @@ import { buildAbsoluteFixturePath, cleanupTests, doubleFollow, - flushAndRunMultipleServers, + createMultipleServers, generateHighBitrateVideo, generateVideoWithFramerate, makeGetRequest, - ServerInfo, + PeerTubeServer, setAccessTokensToServers, waitJobs, webtorrentAdd @@ -31,7 +31,7 @@ import { const expect = chai.expect -function updateConfigForTranscoding (server: ServerInfo) { +function updateConfigForTranscoding (server: PeerTubeServer) { return server.config.updateCustomSubConfig({ newConfig: { transcoding: { @@ -56,14 +56,14 @@ function updateConfigForTranscoding (server: ServerInfo) { } describe('Test video transcoding', function () { - let servers: ServerInfo[] = [] + let servers: PeerTubeServer[] = [] let video4k: string before(async function () { this.timeout(30_000) // Run servers - servers = await flushAndRunMultipleServers(2) + servers = await createMultipleServers(2) await setAccessTokensToServers(servers) diff --git a/server/tests/api/videos/videos-filter.ts b/server/tests/api/videos/videos-filter.ts index af1541dbd..db9150655 100644 --- a/server/tests/api/videos/videos-filter.ts +++ b/server/tests/api/videos/videos-filter.ts @@ -6,14 +6,14 @@ import { HttpStatusCode } from '@shared/core-utils' import { cleanupTests, doubleFollow, - flushAndRunMultipleServers, + createMultipleServers, makeGetRequest, - ServerInfo, + PeerTubeServer, setAccessTokensToServers } from '@shared/extra-utils' import { UserRole, Video, VideoPrivacy } from '@shared/models' -async function getVideosNames (server: ServerInfo, token: string, filter: string, statusCodeExpected = HttpStatusCode.OK_200) { +async function getVideosNames (server: PeerTubeServer, token: string, filter: string, statusCodeExpected = HttpStatusCode.OK_200) { const paths = [ '/api/v1/video-channels/root_channel/videos', '/api/v1/accounts/root/videos', @@ -42,14 +42,14 @@ async function getVideosNames (server: ServerInfo, token: string, filter: string } describe('Test videos filter', function () { - let servers: ServerInfo[] + let servers: PeerTubeServer[] // --------------------------------------------------------------- before(async function () { this.timeout(160000) - servers = await flushAndRunMultipleServers(2) + servers = await createMultipleServers(2) await setAccessTokensToServers(servers) diff --git a/server/tests/api/videos/videos-history.ts b/server/tests/api/videos/videos-history.ts index 4b5e581d1..55e53cb94 100644 --- a/server/tests/api/videos/videos-history.ts +++ b/server/tests/api/videos/videos-history.ts @@ -5,11 +5,10 @@ import * as chai from 'chai' import { HttpStatusCode } from '@shared/core-utils' import { cleanupTests, - flushAndRunServer, + createSingleServer, HistoryCommand, killallServers, - reRunServer, - ServerInfo, + PeerTubeServer, setAccessTokensToServers, wait } from '@shared/extra-utils' @@ -18,7 +17,7 @@ import { Video } from '@shared/models' const expect = chai.expect describe('Test videos history', function () { - let server: ServerInfo = null + let server: PeerTubeServer = null let video1UUID: string let video2UUID: string let video3UUID: string @@ -29,7 +28,7 @@ describe('Test videos history', function () { before(async function () { this.timeout(30000) - server = await flushAndRunServer(1) + server = await createSingleServer(1) await setAccessTokensToServers([ server ]) @@ -191,7 +190,7 @@ describe('Test videos history', function () { await killallServers([ server ]) - await reRunServer(server, { history: { videos: { max_age: '10 days' } } }) + await server.run({ history: { videos: { max_age: '10 days' } } }) await wait(6000) @@ -206,7 +205,7 @@ describe('Test videos history', function () { await killallServers([ server ]) - await reRunServer(server, { history: { videos: { max_age: '5 seconds' } } }) + await server.run({ history: { videos: { max_age: '5 seconds' } } }) await wait(6000) diff --git a/server/tests/api/videos/videos-overview.ts b/server/tests/api/videos/videos-overview.ts index f0657b334..70aa66549 100644 --- a/server/tests/api/videos/videos-overview.ts +++ b/server/tests/api/videos/videos-overview.ts @@ -2,13 +2,13 @@ import 'mocha' import * as chai from 'chai' -import { cleanupTests, flushAndRunServer, ServerInfo, setAccessTokensToServers, wait } from '@shared/extra-utils' +import { cleanupTests, createSingleServer, PeerTubeServer, setAccessTokensToServers, wait } from '@shared/extra-utils' import { VideosOverview } from '@shared/models' const expect = chai.expect describe('Test a videos overview', function () { - let server: ServerInfo = null + let server: PeerTubeServer = null function testOverviewCount (overview: VideosOverview, expected: number) { expect(overview.tags).to.have.lengthOf(expected) @@ -19,7 +19,7 @@ describe('Test a videos overview', function () { before(async function () { this.timeout(30000) - server = await flushAndRunServer(1) + server = await createSingleServer(1) await setAccessTokensToServers([ server ]) }) diff --git a/server/tests/api/videos/videos-views-cleaner.ts b/server/tests/api/videos/videos-views-cleaner.ts index 238662cf3..0be03ddd2 100644 --- a/server/tests/api/videos/videos-views-cleaner.ts +++ b/server/tests/api/videos/videos-views-cleaner.ts @@ -5,10 +5,9 @@ import * as chai from 'chai' import { cleanupTests, doubleFollow, - flushAndRunMultipleServers, + createMultipleServers, killallServers, - reRunServer, - ServerInfo, + PeerTubeServer, setAccessTokensToServers, wait, waitJobs @@ -17,7 +16,7 @@ import { const expect = chai.expect describe('Test video views cleaner', function () { - let servers: ServerInfo[] + let servers: PeerTubeServer[] let videoIdServer1: string let videoIdServer2: string @@ -25,7 +24,7 @@ describe('Test video views cleaner', function () { before(async function () { this.timeout(120000) - servers = await flushAndRunMultipleServers(2) + servers = await createMultipleServers(2) await setAccessTokensToServers(servers) await doubleFollow(servers[0], servers[1]) @@ -48,7 +47,7 @@ describe('Test video views cleaner', function () { await killallServers([ servers[0] ]) - await reRunServer(servers[0], { views: { videos: { remote: { max_age: '10 days' } } } }) + await servers[0].run({ views: { videos: { remote: { max_age: '10 days' } } } }) await wait(6000) @@ -74,7 +73,7 @@ describe('Test video views cleaner', function () { await killallServers([ servers[0] ]) - await reRunServer(servers[0], { views: { videos: { remote: { max_age: '5 seconds' } } } }) + await servers[0].run({ views: { videos: { remote: { max_age: '5 seconds' } } } }) await wait(6000) diff --git a/server/tests/cli/create-import-video-file-job.ts b/server/tests/cli/create-import-video-file-job.ts index 26f4bdc8d..e8cd71e09 100644 --- a/server/tests/cli/create-import-video-file-job.ts +++ b/server/tests/cli/create-import-video-file-job.ts @@ -2,7 +2,7 @@ import 'mocha' import * as chai from 'chai' -import { cleanupTests, doubleFollow, flushAndRunMultipleServers, ServerInfo, setAccessTokensToServers, waitJobs } from '@shared/extra-utils' +import { cleanupTests, doubleFollow, createMultipleServers, PeerTubeServer, setAccessTokensToServers, waitJobs } from '@shared/extra-utils' import { VideoFile } from '@shared/models' const expect = chai.expect @@ -20,7 +20,7 @@ function assertVideoProperties (video: VideoFile, resolution: number, extname: s describe('Test create import video jobs', function () { this.timeout(60000) - let servers: ServerInfo[] = [] + let servers: PeerTubeServer[] = [] let video1UUID: string let video2UUID: string @@ -28,7 +28,7 @@ describe('Test create import video jobs', function () { this.timeout(90000) // Run server 2 to have transcoding enabled - servers = await flushAndRunMultipleServers(2) + servers = await createMultipleServers(2) await setAccessTokensToServers(servers) await doubleFollow(servers[0], servers[1]) diff --git a/server/tests/cli/create-transcoding-job.ts b/server/tests/cli/create-transcoding-job.ts index c9bbab802..53f187f90 100644 --- a/server/tests/cli/create-transcoding-job.ts +++ b/server/tests/cli/create-transcoding-job.ts @@ -5,8 +5,8 @@ import * as chai from 'chai' import { cleanupTests, doubleFollow, - flushAndRunMultipleServers, - ServerInfo, + createMultipleServers, + PeerTubeServer, setAccessTokensToServers, waitJobs } from '../../../shared/extra-utils' @@ -14,7 +14,7 @@ import { const expect = chai.expect describe('Test create transcoding jobs', function () { - let servers: ServerInfo[] = [] + let servers: PeerTubeServer[] = [] const videosUUID: string[] = [] const config = { @@ -39,7 +39,7 @@ describe('Test create transcoding jobs', function () { this.timeout(60000) // Run server 2 to have transcoding enabled - servers = await flushAndRunMultipleServers(2) + servers = await createMultipleServers(2) await setAccessTokensToServers(servers) await servers[0].config.updateCustomSubConfig({ newConfig: config }) diff --git a/server/tests/cli/optimize-old-videos.ts b/server/tests/cli/optimize-old-videos.ts index eefc95a6d..53f47a85e 100644 --- a/server/tests/cli/optimize-old-videos.ts +++ b/server/tests/cli/optimize-old-videos.ts @@ -6,9 +6,9 @@ import { join } from 'path' import { cleanupTests, doubleFollow, - flushAndRunMultipleServers, + createMultipleServers, generateHighBitrateVideo, - ServerInfo, + PeerTubeServer, setAccessTokensToServers, wait, waitJobs @@ -20,13 +20,13 @@ import { VIDEO_TRANSCODING_FPS } from '../../initializers/constants' const expect = chai.expect describe('Test optimize old videos', function () { - let servers: ServerInfo[] = [] + let servers: PeerTubeServer[] = [] before(async function () { this.timeout(200000) // Run server 2 to have transcoding enabled - servers = await flushAndRunMultipleServers(2) + servers = await createMultipleServers(2) await setAccessTokensToServers(servers) await doubleFollow(servers[0], servers[1]) diff --git a/server/tests/cli/peertube.ts b/server/tests/cli/peertube.ts index a83aa7724..f19b6ae22 100644 --- a/server/tests/cli/peertube.ts +++ b/server/tests/cli/peertube.ts @@ -8,16 +8,16 @@ import { cleanupTests, CLICommand, doubleFollow, - flushAndRunServer, + createSingleServer, ImportsCommand, - ServerInfo, + PeerTubeServer, setAccessTokensToServers, testHelloWorldRegisteredSettings, waitJobs } from '../../../shared/extra-utils' describe('Test CLI wrapper', function () { - let server: ServerInfo + let server: PeerTubeServer let userAccessToken: string let cliCommand: CLICommand @@ -27,7 +27,7 @@ describe('Test CLI wrapper', function () { before(async function () { this.timeout(30000) - server = await flushAndRunServer(1) + server = await createSingleServer(1) await setAccessTokensToServers([ server ]) await server.users.create({ username: 'user_1', password: 'super_password' }) @@ -210,14 +210,14 @@ describe('Test CLI wrapper', function () { }) describe('Manage video redundancies', function () { - let anotherServer: ServerInfo + let anotherServer: PeerTubeServer let video1Server2: number - let servers: ServerInfo[] + let servers: PeerTubeServer[] before(async function () { this.timeout(120000) - anotherServer = await flushAndRunServer(2) + anotherServer = await createSingleServer(2) await setAccessTokensToServers([ anotherServer ]) await doubleFollow(server, anotherServer) diff --git a/server/tests/cli/plugins.ts b/server/tests/cli/plugins.ts index 178a7a2d9..42651d79c 100644 --- a/server/tests/cli/plugins.ts +++ b/server/tests/cli/plugins.ts @@ -4,21 +4,20 @@ import 'mocha' import { expect } from 'chai' import { cleanupTests, - flushAndRunServer, + createSingleServer, killallServers, PluginsCommand, - reRunServer, - ServerInfo, + PeerTubeServer, setAccessTokensToServers } from '../../../shared/extra-utils' describe('Test plugin scripts', function () { - let server: ServerInfo + let server: PeerTubeServer before(async function () { this.timeout(30000) - server = await flushAndRunServer(1) + server = await createSingleServer(1) await setAccessTokensToServers([ server ]) }) @@ -40,7 +39,7 @@ describe('Test plugin scripts', function () { this.timeout(30000) await killallServers([ server ]) - await reRunServer(server) + await server.run() const config = await server.config.getConfig() @@ -63,7 +62,7 @@ describe('Test plugin scripts', function () { this.timeout(30000) await killallServers([ server ]) - await reRunServer(server) + await server.run() const config = await server.config.getConfig() diff --git a/server/tests/cli/prune-storage.ts b/server/tests/cli/prune-storage.ts index 9912a36e0..5bf86462b 100644 --- a/server/tests/cli/prune-storage.ts +++ b/server/tests/cli/prune-storage.ts @@ -10,10 +10,10 @@ import { cleanupTests, CLICommand, doubleFollow, - flushAndRunMultipleServers, + createMultipleServers, killallServers, makeGetRequest, - ServerInfo, + PeerTubeServer, setAccessTokensToServers, setDefaultVideoChannel, wait, @@ -23,13 +23,13 @@ import { VideoPlaylistPrivacy } from '@shared/models' const expect = chai.expect -async function countFiles (server: ServerInfo, directory: string) { +async function countFiles (server: PeerTubeServer, directory: string) { const files = await readdir(server.servers.buildDirectory(directory)) return files.length } -async function assertNotExists (server: ServerInfo, directory: string, substring: string) { +async function assertNotExists (server: PeerTubeServer, directory: string, substring: string) { const files = await readdir(server.servers.buildDirectory(directory)) for (const f of files) { @@ -37,7 +37,7 @@ async function assertNotExists (server: ServerInfo, directory: string, substring } } -async function assertCountAreOkay (servers: ServerInfo[]) { +async function assertCountAreOkay (servers: PeerTubeServer[]) { for (const server of servers) { const videosCount = await countFiles(server, 'videos') expect(videosCount).to.equal(8) @@ -57,13 +57,13 @@ async function assertCountAreOkay (servers: ServerInfo[]) { } describe('Test prune storage scripts', function () { - let servers: ServerInfo[] + let servers: PeerTubeServer[] const badNames: { [directory: string]: string[] } = {} before(async function () { this.timeout(120000) - servers = await flushAndRunMultipleServers(2, { transcoding: { enabled: true } }) + servers = await createMultipleServers(2, { transcoding: { enabled: true } }) await setAccessTokensToServers(servers) await setDefaultVideoChannel(servers) diff --git a/server/tests/cli/regenerate-thumbnails.ts b/server/tests/cli/regenerate-thumbnails.ts index 2df1a1157..d532a5c2b 100644 --- a/server/tests/cli/regenerate-thumbnails.ts +++ b/server/tests/cli/regenerate-thumbnails.ts @@ -7,14 +7,14 @@ import { Video } from '@shared/models' import { cleanupTests, doubleFollow, - flushAndRunMultipleServers, + createMultipleServers, makeRawRequest, - ServerInfo, + PeerTubeServer, setAccessTokensToServers, waitJobs } from '../../../shared/extra-utils' -async function testThumbnail (server: ServerInfo, videoId: number | string) { +async function testThumbnail (server: PeerTubeServer, videoId: number | string) { const video = await server.videos.get({ id: videoId }) const requests = [ @@ -29,7 +29,7 @@ async function testThumbnail (server: ServerInfo, videoId: number | string) { } describe('Test regenerate thumbnails script', function () { - let servers: ServerInfo[] + let servers: PeerTubeServer[] let video1: Video let video2: Video @@ -41,7 +41,7 @@ describe('Test regenerate thumbnails script', function () { before(async function () { this.timeout(60000) - servers = await flushAndRunMultipleServers(2) + servers = await createMultipleServers(2) await setAccessTokensToServers(servers) await doubleFollow(servers[0], servers[1]) diff --git a/server/tests/cli/reset-password.ts b/server/tests/cli/reset-password.ts index e0d6f220a..4a02db35d 100644 --- a/server/tests/cli/reset-password.ts +++ b/server/tests/cli/reset-password.ts @@ -1,12 +1,12 @@ import 'mocha' -import { cleanupTests, CLICommand, flushAndRunServer, ServerInfo, setAccessTokensToServers } from '../../../shared/extra-utils' +import { cleanupTests, CLICommand, createSingleServer, PeerTubeServer, setAccessTokensToServers } from '../../../shared/extra-utils' describe('Test reset password scripts', function () { - let server: ServerInfo + let server: PeerTubeServer before(async function () { this.timeout(30000) - server = await flushAndRunServer(1) + server = await createSingleServer(1) await setAccessTokensToServers([ server ]) await server.users.create({ username: 'user_1', password: 'super password' }) diff --git a/server/tests/cli/update-host.ts b/server/tests/cli/update-host.ts index d2d196456..fcbcb55ba 100644 --- a/server/tests/cli/update-host.ts +++ b/server/tests/cli/update-host.ts @@ -4,18 +4,17 @@ import 'mocha' import { expect } from 'chai' import { cleanupTests, - flushAndRunServer, + createSingleServer, killallServers, makeActivityPubGetRequest, parseTorrentVideo, - reRunServer, - ServerInfo, + PeerTubeServer, setAccessTokensToServers, waitJobs } from '@shared/extra-utils' describe('Test update host scripts', function () { - let server: ServerInfo + let server: PeerTubeServer before(async function () { this.timeout(60000) @@ -26,7 +25,7 @@ describe('Test update host scripts', function () { } } // Run server 2 to have transcoding enabled - server = await flushAndRunServer(2, overrideConfig) + server = await createSingleServer(2, overrideConfig) await setAccessTokensToServers([ server ]) // Upload two videos for our needs @@ -56,7 +55,7 @@ describe('Test update host scripts', function () { await killallServers([ server ]) // Run server with standard configuration - await reRunServer(server) + await server.run() await server.cli.execWithEnv(`npm run update-host`) }) diff --git a/server/tests/client.ts b/server/tests/client.ts index caf6fb00c..959b34653 100644 --- a/server/tests/client.ts +++ b/server/tests/client.ts @@ -8,10 +8,10 @@ import { Account, HTMLServerConfig, ServerConfig, VideoPlaylistCreateResult, Vid import { cleanupTests, doubleFollow, - flushAndRunMultipleServers, + createMultipleServers, makeGetRequest, makeHTMLRequest, - ServerInfo, + PeerTubeServer, setAccessTokensToServers, setDefaultVideoChannel, waitJobs @@ -29,7 +29,7 @@ function checkIndexTags (html: string, title: string, description: string, css: } describe('Test a client controllers', function () { - let servers: ServerInfo[] = [] + let servers: PeerTubeServer[] = [] let account: Account const videoName = 'my super name for server 1' @@ -51,7 +51,7 @@ describe('Test a client controllers', function () { before(async function () { this.timeout(120000) - servers = await flushAndRunMultipleServers(2) + servers = await createMultipleServers(2) await setAccessTokensToServers(servers) diff --git a/server/tests/external-plugins/auth-ldap.ts b/server/tests/external-plugins/auth-ldap.ts index ef624152e..aaaf23278 100644 --- a/server/tests/external-plugins/auth-ldap.ts +++ b/server/tests/external-plugins/auth-ldap.ts @@ -3,17 +3,17 @@ import 'mocha' import { expect } from 'chai' import { HttpStatusCode } from '@shared/core-utils' -import { cleanupTests, flushAndRunServer, ServerInfo, setAccessTokensToServers } from '@shared/extra-utils' +import { cleanupTests, createSingleServer, PeerTubeServer, setAccessTokensToServers } from '@shared/extra-utils' describe('Official plugin auth-ldap', function () { - let server: ServerInfo + let server: PeerTubeServer let accessToken: string let userId: number before(async function () { this.timeout(30000) - server = await flushAndRunServer(1) + server = await createSingleServer(1) await setAccessTokensToServers([ server ]) await server.plugins.install({ npmName: 'peertube-plugin-auth-ldap' }) diff --git a/server/tests/external-plugins/auto-block-videos.ts b/server/tests/external-plugins/auto-block-videos.ts index 3b4b48bf0..9cb86310b 100644 --- a/server/tests/external-plugins/auto-block-videos.ts +++ b/server/tests/external-plugins/auto-block-videos.ts @@ -5,17 +5,16 @@ import { expect } from 'chai' import { cleanupTests, doubleFollow, - flushAndRunMultipleServers, + createMultipleServers, killallServers, MockBlocklist, - reRunServer, - ServerInfo, + PeerTubeServer, setAccessTokensToServers, wait } from '@shared/extra-utils' import { Video } from '@shared/models' -async function check (server: ServerInfo, videoUUID: string, exists = true) { +async function check (server: PeerTubeServer, videoUUID: string, exists = true) { const { data } = await server.videos.list() const video = data.find(v => v.uuid === videoUUID) @@ -25,7 +24,7 @@ async function check (server: ServerInfo, videoUUID: string, exists = true) { } describe('Official plugin auto-block videos', function () { - let servers: ServerInfo[] + let servers: PeerTubeServer[] let blocklistServer: MockBlocklist let server1Videos: Video[] = [] let server2Videos: Video[] = [] @@ -34,7 +33,7 @@ describe('Official plugin auto-block videos', function () { before(async function () { this.timeout(60000) - servers = await flushAndRunMultipleServers(2) + servers = await createMultipleServers(2) await setAccessTokensToServers(servers) for (const server of servers) { @@ -161,7 +160,7 @@ describe('Official plugin auto-block videos', function () { await check(servers[0], video.uuid, true) await killallServers([ servers[0] ]) - await reRunServer(servers[0]) + await servers[0].run() await wait(2000) await check(servers[0], video.uuid, true) diff --git a/server/tests/external-plugins/auto-mute.ts b/server/tests/external-plugins/auto-mute.ts index 25b56a546..771201505 100644 --- a/server/tests/external-plugins/auto-mute.ts +++ b/server/tests/external-plugins/auto-mute.ts @@ -6,26 +6,25 @@ import { HttpStatusCode } from '@shared/core-utils' import { cleanupTests, doubleFollow, - flushAndRunMultipleServers, + createMultipleServers, killallServers, makeGetRequest, MockBlocklist, - reRunServer, - ServerInfo, + PeerTubeServer, setAccessTokensToServers, wait } from '@shared/extra-utils' describe('Official plugin auto-mute', function () { const autoMuteListPath = '/plugins/auto-mute/router/api/v1/mute-list' - let servers: ServerInfo[] + let servers: PeerTubeServer[] let blocklistServer: MockBlocklist let port: number before(async function () { this.timeout(30000) - servers = await flushAndRunMultipleServers(2) + servers = await createMultipleServers(2) await setAccessTokensToServers(servers) for (const server of servers) { @@ -150,7 +149,7 @@ describe('Official plugin auto-mute', function () { } await killallServers([ servers[0] ]) - await reRunServer(servers[0]) + await servers[0].run() await wait(2000) { diff --git a/server/tests/feeds/feeds.ts b/server/tests/feeds/feeds.ts index 8bdafc644..7735299d3 100644 --- a/server/tests/feeds/feeds.ts +++ b/server/tests/feeds/feeds.ts @@ -7,9 +7,9 @@ import { HttpStatusCode } from '@shared/core-utils' import { cleanupTests, doubleFollow, - flushAndRunMultipleServers, - flushAndRunServer, - ServerInfo, + createMultipleServers, + createSingleServer, + PeerTubeServer, setAccessTokensToServers, waitJobs } from '@shared/extra-utils' @@ -21,8 +21,8 @@ chai.config.includeStack = true const expect = chai.expect describe('Test syndication feeds', () => { - let servers: ServerInfo[] = [] - let serverHLSOnly: ServerInfo + let servers: PeerTubeServer[] = [] + let serverHLSOnly: PeerTubeServer let userAccessToken: string let rootAccountId: number let rootChannelId: number @@ -34,8 +34,8 @@ describe('Test syndication feeds', () => { this.timeout(120000) // Run servers - servers = await flushAndRunMultipleServers(2) - serverHLSOnly = await flushAndRunServer(3, { + servers = await createMultipleServers(2) + serverHLSOnly = await createSingleServer(3, { transcoding: { enabled: true, webtorrent: { enabled: false }, diff --git a/server/tests/misc-endpoints.ts b/server/tests/misc-endpoints.ts index f7c9e6c26..a4f344fcc 100644 --- a/server/tests/misc-endpoints.ts +++ b/server/tests/misc-endpoints.ts @@ -3,18 +3,18 @@ import 'mocha' import * as chai from 'chai' import { HttpStatusCode } from '@shared/core-utils' -import { cleanupTests, flushAndRunServer, makeGetRequest, ServerInfo, setAccessTokensToServers } from '@shared/extra-utils' +import { cleanupTests, createSingleServer, makeGetRequest, PeerTubeServer, setAccessTokensToServers } from '@shared/extra-utils' import { VideoPrivacy } from '@shared/models' const expect = chai.expect describe('Test misc endpoints', function () { - let server: ServerInfo + let server: PeerTubeServer before(async function () { this.timeout(120000) - server = await flushAndRunServer(1) + server = await createSingleServer(1) await setAccessTokensToServers([ server ]) }) diff --git a/server/tests/plugins/action-hooks.ts b/server/tests/plugins/action-hooks.ts index 12d5c23c5..b96de4e90 100644 --- a/server/tests/plugins/action-hooks.ts +++ b/server/tests/plugins/action-hooks.ts @@ -3,18 +3,17 @@ import 'mocha' import { cleanupTests, - flushAndRunMultipleServers, + createMultipleServers, killallServers, + PeerTubeServer, PluginsCommand, - reRunServer, - ServerInfo, setAccessTokensToServers, setDefaultVideoChannel } from '@shared/extra-utils' import { ServerHookName, VideoPlaylistPrivacy, VideoPrivacy } from '@shared/models' describe('Test plugin action hooks', function () { - let servers: ServerInfo[] + let servers: PeerTubeServer[] let videoUUID: string let threadId: number @@ -25,7 +24,7 @@ describe('Test plugin action hooks', function () { before(async function () { this.timeout(30000) - servers = await flushAndRunMultipleServers(2) + servers = await createMultipleServers(2) await setAccessTokensToServers(servers) await setDefaultVideoChannel(servers) @@ -33,7 +32,7 @@ describe('Test plugin action hooks', function () { await killallServers([ servers[0] ]) - await reRunServer(servers[0], { + await servers[0].run({ live: { enabled: true } diff --git a/server/tests/plugins/external-auth.ts b/server/tests/plugins/external-auth.ts index 48f942f7f..c0834a14c 100644 --- a/server/tests/plugins/external-auth.ts +++ b/server/tests/plugins/external-auth.ts @@ -6,16 +6,16 @@ import { HttpStatusCode } from '@shared/core-utils' import { cleanupTests, decodeQueryString, - flushAndRunServer, + createSingleServer, PluginsCommand, - ServerInfo, + PeerTubeServer, setAccessTokensToServers, wait } from '@shared/extra-utils' import { UserRole } from '@shared/models' async function loginExternal (options: { - server: ServerInfo + server: PeerTubeServer npmName: string authName: string username: string @@ -46,7 +46,7 @@ async function loginExternal (options: { } describe('Test external auth plugins', function () { - let server: ServerInfo + let server: PeerTubeServer let cyanAccessToken: string let cyanRefreshToken: string @@ -59,7 +59,7 @@ describe('Test external auth plugins', function () { before(async function () { this.timeout(30000) - server = await flushAndRunServer(1) + server = await createSingleServer(1) await setAccessTokensToServers([ server ]) for (const suffix of [ 'one', 'two', 'three' ]) { diff --git a/server/tests/plugins/filter-hooks.ts b/server/tests/plugins/filter-hooks.ts index 18479dcf5..5d94303a9 100644 --- a/server/tests/plugins/filter-hooks.ts +++ b/server/tests/plugins/filter-hooks.ts @@ -6,11 +6,11 @@ import { HttpStatusCode } from '@shared/core-utils' import { cleanupTests, doubleFollow, - flushAndRunMultipleServers, + createMultipleServers, ImportsCommand, makeRawRequest, PluginsCommand, - ServerInfo, + PeerTubeServer, setAccessTokensToServers, setDefaultVideoChannel, waitJobs @@ -20,14 +20,14 @@ import { VideoDetails, VideoImportState, VideoPlaylist, VideoPlaylistPrivacy, Vi const expect = chai.expect describe('Test plugin filter hooks', function () { - let servers: ServerInfo[] + let servers: PeerTubeServer[] let videoUUID: string let threadId: number before(async function () { this.timeout(60000) - servers = await flushAndRunMultipleServers(2) + servers = await createMultipleServers(2) await setAccessTokensToServers(servers) await setDefaultVideoChannel(servers) await doubleFollow(servers[0], servers[1]) diff --git a/server/tests/plugins/html-injection.ts b/server/tests/plugins/html-injection.ts index 0cb89f511..2902c39b7 100644 --- a/server/tests/plugins/html-injection.ts +++ b/server/tests/plugins/html-injection.ts @@ -4,23 +4,23 @@ import 'mocha' import * as chai from 'chai' import { cleanupTests, - flushAndRunServer, + createSingleServer, makeHTMLRequest, PluginsCommand, - ServerInfo, + PeerTubeServer, setAccessTokensToServers } from '../../../shared/extra-utils' const expect = chai.expect describe('Test plugins HTML injection', function () { - let server: ServerInfo = null + let server: PeerTubeServer = null let command: PluginsCommand before(async function () { this.timeout(30000) - server = await flushAndRunServer(1) + server = await createSingleServer(1) await setAccessTokensToServers([ server ]) command = server.plugins diff --git a/server/tests/plugins/id-and-pass-auth.ts b/server/tests/plugins/id-and-pass-auth.ts index 203996af8..981bcad91 100644 --- a/server/tests/plugins/id-and-pass-auth.ts +++ b/server/tests/plugins/id-and-pass-auth.ts @@ -3,11 +3,11 @@ import 'mocha' import { expect } from 'chai' import { HttpStatusCode } from '@shared/core-utils' -import { cleanupTests, flushAndRunServer, PluginsCommand, ServerInfo, setAccessTokensToServers, wait } from '@shared/extra-utils' +import { cleanupTests, createSingleServer, PluginsCommand, PeerTubeServer, setAccessTokensToServers, wait } from '@shared/extra-utils' import { UserRole } from '@shared/models' describe('Test id and pass auth plugins', function () { - let server: ServerInfo + let server: PeerTubeServer let crashAccessToken: string let crashRefreshToken: string @@ -18,7 +18,7 @@ describe('Test id and pass auth plugins', function () { before(async function () { this.timeout(30000) - server = await flushAndRunServer(1) + server = await createSingleServer(1) await setAccessTokensToServers([ server ]) for (const suffix of [ 'one', 'two', 'three' ]) { diff --git a/server/tests/plugins/plugin-helpers.ts b/server/tests/plugins/plugin-helpers.ts index cf16aaa9d..1d87b84ae 100644 --- a/server/tests/plugins/plugin-helpers.ts +++ b/server/tests/plugins/plugin-helpers.ts @@ -7,16 +7,16 @@ import { checkVideoFilesWereRemoved, cleanupTests, doubleFollow, - flushAndRunMultipleServers, + createMultipleServers, makeGetRequest, makePostBodyRequest, PluginsCommand, - ServerInfo, + PeerTubeServer, setAccessTokensToServers, waitJobs } from '@shared/extra-utils' -function postCommand (server: ServerInfo, command: string, bodyArg?: object) { +function postCommand (server: PeerTubeServer, command: string, bodyArg?: object) { const body = { command } if (bodyArg) Object.assign(body, bodyArg) @@ -29,12 +29,12 @@ function postCommand (server: ServerInfo, command: string, bodyArg?: object) { } describe('Test plugin helpers', function () { - let servers: ServerInfo[] + let servers: PeerTubeServer[] before(async function () { this.timeout(60000) - servers = await flushAndRunMultipleServers(2) + servers = await createMultipleServers(2) await setAccessTokensToServers(servers) await doubleFollow(servers[0], servers[1]) diff --git a/server/tests/plugins/plugin-router.ts b/server/tests/plugins/plugin-router.ts index 1c53dd80c..dec8ca4bb 100644 --- a/server/tests/plugins/plugin-router.ts +++ b/server/tests/plugins/plugin-router.ts @@ -5,16 +5,16 @@ import { expect } from 'chai' import { HttpStatusCode } from '@shared/core-utils' import { cleanupTests, - flushAndRunServer, + createSingleServer, makeGetRequest, makePostBodyRequest, PluginsCommand, - ServerInfo, + PeerTubeServer, setAccessTokensToServers } from '@shared/extra-utils' describe('Test plugin helpers', function () { - let server: ServerInfo + let server: PeerTubeServer const basePaths = [ '/plugins/test-five/router/', '/plugins/test-five/0.0.1/router/' @@ -23,7 +23,7 @@ describe('Test plugin helpers', function () { before(async function () { this.timeout(30000) - server = await flushAndRunServer(1) + server = await createSingleServer(1) await setAccessTokensToServers([ server ]) await server.plugins.install({ path: PluginsCommand.getPluginTestPath('-five') }) diff --git a/server/tests/plugins/plugin-storage.ts b/server/tests/plugins/plugin-storage.ts index 30e231439..5745914a5 100644 --- a/server/tests/plugins/plugin-storage.ts +++ b/server/tests/plugins/plugin-storage.ts @@ -5,15 +5,22 @@ import { expect } from 'chai' import { pathExists, readdir, readFile } from 'fs-extra' import { join } from 'path' import { HttpStatusCode } from '@shared/core-utils' -import { cleanupTests, flushAndRunServer, makeGetRequest, PluginsCommand, ServerInfo, setAccessTokensToServers } from '@shared/extra-utils' +import { + cleanupTests, + createSingleServer, + makeGetRequest, + PeerTubeServer, + PluginsCommand, + setAccessTokensToServers +} from '@shared/extra-utils' describe('Test plugin storage', function () { - let server: ServerInfo + let server: PeerTubeServer before(async function () { this.timeout(30000) - server = await flushAndRunServer(1) + server = await createSingleServer(1) await setAccessTokensToServers([ server ]) await server.plugins.install({ path: PluginsCommand.getPluginTestPath('-six') }) diff --git a/server/tests/plugins/plugin-transcoding.ts b/server/tests/plugins/plugin-transcoding.ts index 3a03065b0..3c54d3796 100644 --- a/server/tests/plugins/plugin-transcoding.ts +++ b/server/tests/plugins/plugin-transcoding.ts @@ -6,9 +6,9 @@ import { join } from 'path' import { getAudioStream, getVideoFileFPS, getVideoStreamFromFile } from '@server/helpers/ffprobe-utils' import { cleanupTests, - flushAndRunServer, + createSingleServer, PluginsCommand, - ServerInfo, + PeerTubeServer, setAccessTokensToServers, setDefaultVideoChannel, testFfmpegStreamError, @@ -16,7 +16,7 @@ import { } from '@shared/extra-utils' import { VideoPrivacy } from '@shared/models' -async function createLiveWrapper (server: ServerInfo) { +async function createLiveWrapper (server: PeerTubeServer) { const liveAttributes = { name: 'live video', channelId: server.store.channel.id, @@ -28,7 +28,7 @@ async function createLiveWrapper (server: ServerInfo) { return uuid } -function updateConf (server: ServerInfo, vodProfile: string, liveProfile: string) { +function updateConf (server: PeerTubeServer, vodProfile: string, liveProfile: string) { return server.config.updateCustomSubConfig({ newConfig: { transcoding: { @@ -64,12 +64,12 @@ function updateConf (server: ServerInfo, vodProfile: string, liveProfile: string } describe('Test transcoding plugins', function () { - let server: ServerInfo + let server: PeerTubeServer before(async function () { this.timeout(60000) - server = await flushAndRunServer(1) + server = await createSingleServer(1) await setAccessTokensToServers([ server ]) await setDefaultVideoChannel([ server ]) diff --git a/server/tests/plugins/plugin-unloading.ts b/server/tests/plugins/plugin-unloading.ts index 26a27abca..6c405b7f5 100644 --- a/server/tests/plugins/plugin-unloading.ts +++ b/server/tests/plugins/plugin-unloading.ts @@ -3,17 +3,24 @@ import 'mocha' import { expect } from 'chai' import { HttpStatusCode } from '@shared/core-utils' -import { cleanupTests, flushAndRunServer, makeGetRequest, PluginsCommand, ServerInfo, setAccessTokensToServers } from '@shared/extra-utils' +import { + cleanupTests, + createSingleServer, + makeGetRequest, + PeerTubeServer, + PluginsCommand, + setAccessTokensToServers +} from '@shared/extra-utils' describe('Test plugins module unloading', function () { - let server: ServerInfo = null + let server: PeerTubeServer = null const requestPath = '/plugins/test-unloading/router/get' let value: string = null before(async function () { this.timeout(30000) - server = await flushAndRunServer(1) + server = await createSingleServer(1) await setAccessTokensToServers([ server ]) await server.plugins.install({ path: PluginsCommand.getPluginTestPath('-unloading') }) diff --git a/server/tests/plugins/translations.ts b/server/tests/plugins/translations.ts index d8d878026..8b25c6b75 100644 --- a/server/tests/plugins/translations.ts +++ b/server/tests/plugins/translations.ts @@ -2,19 +2,18 @@ import 'mocha' import * as chai from 'chai' -import { PluginsCommand, setAccessTokensToServers } from '../../../shared/extra-utils' -import { cleanupTests, flushAndRunServer, ServerInfo } from '../../../shared/extra-utils/server/servers' +import { cleanupTests, createSingleServer, PeerTubeServer, PluginsCommand, setAccessTokensToServers } from '@shared/extra-utils' const expect = chai.expect describe('Test plugin translations', function () { - let server: ServerInfo + let server: PeerTubeServer let command: PluginsCommand before(async function () { this.timeout(30000) - server = await flushAndRunServer(1) + server = await createSingleServer(1) await setAccessTokensToServers([ server ]) command = server.plugins diff --git a/server/tests/plugins/video-constants.ts b/server/tests/plugins/video-constants.ts index facc6bbc1..953916e8e 100644 --- a/server/tests/plugins/video-constants.ts +++ b/server/tests/plugins/video-constants.ts @@ -3,18 +3,18 @@ import 'mocha' import * as chai from 'chai' import { HttpStatusCode } from '@shared/core-utils' -import { cleanupTests, flushAndRunServer, PluginsCommand, ServerInfo, setAccessTokensToServers } from '@shared/extra-utils' +import { cleanupTests, createSingleServer, PluginsCommand, PeerTubeServer, setAccessTokensToServers } from '@shared/extra-utils' import { VideoPlaylistPrivacy } from '@shared/models' const expect = chai.expect describe('Test plugin altering video constants', function () { - let server: ServerInfo + let server: PeerTubeServer before(async function () { this.timeout(30000) - server = await flushAndRunServer(1) + server = await createSingleServer(1) await setAccessTokensToServers([ server ]) await server.plugins.install({ path: PluginsCommand.getPluginTestPath('-video-constants') }) diff --git a/server/tools/cli.ts b/server/tools/cli.ts index 7d5eb72ed..52e6ea593 100644 --- a/server/tools/cli.ts +++ b/server/tools/cli.ts @@ -2,7 +2,7 @@ import { Command } from 'commander' import { Netrc } from 'netrc-parser' import { join } from 'path' import { createLogger, format, transports } from 'winston' -import { assignCommands, ServerInfo } from '@shared/extra-utils' +import { PeerTubeServer } from '@shared/extra-utils' import { UserRole } from '@shared/models' import { VideoPrivacy } from '../../shared/models/videos' import { getAppNumber, isTestInstance, root } from '../helpers/core-utils' @@ -14,7 +14,7 @@ const config = require('application-config')(configName) const version = require('../../../package.json').version -async function getAdminTokenOrDie (server: ServerInfo, username: string, password: string) { +async function getAdminTokenOrDie (server: PeerTubeServer, username: string, password: string) { const token = await server.login.getAccessToken(username, password) const me = await server.users.getMyInfo({ token }) @@ -124,7 +124,7 @@ function buildCommonVideoOptions (command: Command) { .option('-v, --verbose ', 'Verbosity, from 0/\'error\' to 4/\'debug\'', 'info') } -async function buildVideoAttributesFromCommander (server: ServerInfo, command: Command, defaultAttributes: any = {}) { +async function buildVideoAttributesFromCommander (server: PeerTubeServer, command: Command, defaultAttributes: any = {}) { const options = command.opts() const defaultBooleanAttributes = { @@ -179,14 +179,11 @@ function getServerCredentials (program: Command) { }) } -function buildServer (url: string): ServerInfo { - const server = { url, internalServerNumber: undefined } - assignCommands(server) - - return server +function buildServer (url: string) { + return new PeerTubeServer({ url }) } -async function assignToken (server: ServerInfo, username: string, password: string) { +async function assignToken (server: PeerTubeServer, username: string, password: string) { const bodyClient = await server.login.getClient() const client = { id: bodyClient.client_id, secret: bodyClient.client_secret } diff --git a/server/tools/peertube-import-videos.ts b/server/tools/peertube-import-videos.ts index caf1facc7..52aae3d2c 100644 --- a/server/tools/peertube-import-videos.ts +++ b/server/tools/peertube-import-videos.ts @@ -20,7 +20,7 @@ import { getLogger, getServerCredentials } from './cli' -import { ServerInfo } from '@shared/extra-utils' +import { PeerTubeServer } from '@shared/extra-utils' const processOptions = { maxBuffer: Infinity @@ -270,7 +270,7 @@ async function uploadVideoOnPeerTube (parameters: { /* ---------------------------------------------------------- */ -async function getCategory (server: ServerInfo, categories: string[]) { +async function getCategory (server: PeerTubeServer, categories: string[]) { if (!categories) return undefined const categoryString = categories[0] diff --git a/server/tools/test-live.ts b/server/tools/test-live.ts index bc31b6926..0cb0c3668 100644 --- a/server/tools/test-live.ts +++ b/server/tools/test-live.ts @@ -1,10 +1,10 @@ import { program } from 'commander' import { LiveVideoCreate, VideoPrivacy } from '@shared/models' import { - flushAndRunServer, + createSingleServer, killallServers, sendRTMPStream, - ServerInfo, + PeerTubeServer, setAccessTokensToServers, setDefaultVideoChannel } from '../../shared/extra-utils' @@ -36,7 +36,7 @@ async function run () { console.log('Starting server.') - const server = await flushAndRunServer(1, {}, [], { hideLogs: false, execArgv: [ '--inspect' ] }) + const server = await createSingleServer(1, {}, [], { hideLogs: false, execArgv: [ '--inspect' ] }) const cleanup = async () => { console.log('Killing server') @@ -81,7 +81,7 @@ async function run () { // ---------------------------------------------------------------------------- -async function buildConfig (server: ServerInfo, commandType: CommandType) { +async function buildConfig (server: PeerTubeServer, commandType: CommandType) { await server.config.updateCustomSubConfig({ newConfig: { instance: { diff --git a/shared/extra-utils/miscs/checks.ts b/shared/extra-utils/miscs/checks.ts index 8f7bdb9b5..c81460330 100644 --- a/shared/extra-utils/miscs/checks.ts +++ b/shared/extra-utils/miscs/checks.ts @@ -6,7 +6,7 @@ import { join } from 'path' import { root } from '@server/helpers/core-utils' import { HttpStatusCode } from '@shared/core-utils' import { makeGetRequest } from '../requests' -import { ServerInfo } from '../server' +import { PeerTubeServer } from '../server' // Default interval -> 5 minutes function dateIsValid (dateString: string, interval = 300000) { @@ -33,7 +33,7 @@ async function testImage (url: string, imageName: string, imagePath: string, ext expect(data.length).to.be.below(maxLength, 'the generated image is way larger than the recorded fixture') } -async function testFileExistsOrNot (server: ServerInfo, directory: string, filePath: string, exist: boolean) { +async function testFileExistsOrNot (server: PeerTubeServer, directory: string, filePath: string, exist: boolean) { const base = server.servers.buildDirectory(directory) expect(await pathExists(join(base, filePath))).to.equal(exist) diff --git a/shared/extra-utils/miscs/webtorrent.ts b/shared/extra-utils/miscs/webtorrent.ts index 84e390b2a..815ea3d56 100644 --- a/shared/extra-utils/miscs/webtorrent.ts +++ b/shared/extra-utils/miscs/webtorrent.ts @@ -2,7 +2,7 @@ import { readFile } from 'fs-extra' import * as parseTorrent from 'parse-torrent' import { join } from 'path' import * as WebTorrent from 'webtorrent' -import { ServerInfo } from '../server' +import { PeerTubeServer } from '../server' let webtorrent: WebTorrent.Instance @@ -15,7 +15,7 @@ function webtorrentAdd (torrent: string, refreshWebTorrent = false) { return new Promise(res => webtorrent.add(torrent, res)) } -async function parseTorrentVideo (server: ServerInfo, videoUUID: string, resolution: number) { +async function parseTorrentVideo (server: PeerTubeServer, videoUUID: string, resolution: number) { const torrentName = videoUUID + '-' + resolution + '.torrent' const torrentPath = server.servers.buildDirectory(join('torrents', torrentName)) diff --git a/shared/extra-utils/server/directories.ts b/shared/extra-utils/server/directories.ts index 3cd38a561..b6465cbf4 100644 --- a/shared/extra-utils/server/directories.ts +++ b/shared/extra-utils/server/directories.ts @@ -4,9 +4,9 @@ import { expect } from 'chai' import { pathExists, readdir } from 'fs-extra' import { join } from 'path' import { root } from '@server/helpers/core-utils' -import { ServerInfo } from './servers' +import { PeerTubeServer } from './server' -async function checkTmpIsEmpty (server: ServerInfo) { +async function checkTmpIsEmpty (server: PeerTubeServer) { await checkDirectoryIsEmpty(server, 'tmp', [ 'plugins-global.css', 'hls', 'resumable-uploads' ]) if (await pathExists(join('test' + server.internalServerNumber, 'tmp', 'hls'))) { @@ -14,7 +14,7 @@ async function checkTmpIsEmpty (server: ServerInfo) { } } -async function checkDirectoryIsEmpty (server: ServerInfo, directory: string, exceptions: string[] = []) { +async function checkDirectoryIsEmpty (server: PeerTubeServer, directory: string, exceptions: string[] = []) { const testDirectory = 'test' + server.internalServerNumber const directoryPath = join(root(), testDirectory, directory) diff --git a/shared/extra-utils/server/follows-command.ts b/shared/extra-utils/server/follows-command.ts index 4e1e56d7a..4e9ed9494 100644 --- a/shared/extra-utils/server/follows-command.ts +++ b/shared/extra-utils/server/follows-command.ts @@ -2,7 +2,7 @@ import { pick } from 'lodash' import { ActivityPubActorType, ActorFollow, FollowState, ResultList } from '@shared/models' import { HttpStatusCode } from '../../core-utils/miscs/http-error-codes' import { AbstractCommand, OverrideCommandOptions } from '../shared' -import { ServerInfo } from './servers' +import { PeerTubeServer } from './server' export class FollowsCommand extends AbstractCommand { @@ -70,7 +70,7 @@ export class FollowsCommand extends AbstractCommand { } async unfollow (options: OverrideCommandOptions & { - target: ServerInfo + target: PeerTubeServer }) { const path = '/api/v1/server/following/' + options.target.host @@ -112,7 +112,7 @@ export class FollowsCommand extends AbstractCommand { } removeFollower (options: OverrideCommandOptions & { - follower: ServerInfo + follower: PeerTubeServer }) { const path = '/api/v1/server/followers/peertube@' + options.follower.host diff --git a/shared/extra-utils/server/follows.ts b/shared/extra-utils/server/follows.ts index 50ae898cc..0188be1aa 100644 --- a/shared/extra-utils/server/follows.ts +++ b/shared/extra-utils/server/follows.ts @@ -1,7 +1,7 @@ import { waitJobs } from './jobs' -import { ServerInfo } from './servers' +import { PeerTubeServer } from './server' -async function doubleFollow (server1: ServerInfo, server2: ServerInfo) { +async function doubleFollow (server1: PeerTubeServer, server2: PeerTubeServer) { await Promise.all([ server1.follows.follow({ targets: [ server2.url ] }), server2.follows.follow({ targets: [ server1.url ] }) diff --git a/shared/extra-utils/server/index.ts b/shared/extra-utils/server/index.ts index 669b004cd..9055dfc57 100644 --- a/shared/extra-utils/server/index.ts +++ b/shared/extra-utils/server/index.ts @@ -9,6 +9,7 @@ export * from './jobs-command' export * from './plugins-command' export * from './plugins' export * from './redundancy-command' +export * from './server' export * from './servers-command' export * from './servers' export * from './stats-command' diff --git a/shared/extra-utils/server/jobs.ts b/shared/extra-utils/server/jobs.ts index 754530977..64a0353eb 100644 --- a/shared/extra-utils/server/jobs.ts +++ b/shared/extra-utils/server/jobs.ts @@ -1,17 +1,17 @@ import { JobState } from '../../models' import { wait } from '../miscs' -import { ServerInfo } from './servers' +import { PeerTubeServer } from './server' -async function waitJobs (serversArg: ServerInfo[] | ServerInfo) { +async function waitJobs (serversArg: PeerTubeServer[] | PeerTubeServer) { const pendingJobWait = process.env.NODE_PENDING_JOB_WAIT ? parseInt(process.env.NODE_PENDING_JOB_WAIT, 10) : 250 - let servers: ServerInfo[] + let servers: PeerTubeServer[] - if (Array.isArray(serversArg) === false) servers = [ serversArg as ServerInfo ] - else servers = serversArg as ServerInfo[] + if (Array.isArray(serversArg) === false) servers = [ serversArg as PeerTubeServer ] + else servers = serversArg as PeerTubeServer[] const states: JobState[] = [ 'waiting', 'active', 'delayed' ] const repeatableJobs = [ 'videos-views', 'activitypub-cleaner' ] diff --git a/shared/extra-utils/server/plugins.ts b/shared/extra-utils/server/plugins.ts index d1cc7e383..0f5fabd5a 100644 --- a/shared/extra-utils/server/plugins.ts +++ b/shared/extra-utils/server/plugins.ts @@ -1,9 +1,9 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ import { expect } from 'chai' -import { ServerInfo } from '../server/servers' +import { PeerTubeServer } from '../server/server' -async function testHelloWorldRegisteredSettings (server: ServerInfo) { +async function testHelloWorldRegisteredSettings (server: PeerTubeServer) { const body = await server.plugins.getRegisteredSettings({ npmName: 'peertube-plugin-hello-world' }) const registeredSettings = body.registeredSettings diff --git a/shared/extra-utils/server/server.ts b/shared/extra-utils/server/server.ts new file mode 100644 index 000000000..b1347661f --- /dev/null +++ b/shared/extra-utils/server/server.ts @@ -0,0 +1,376 @@ +import { ChildProcess, fork } from 'child_process' +import { copy } from 'fs-extra' +import { join } from 'path' +import { root } from '@server/helpers/core-utils' +import { randomInt } from '../../core-utils/miscs/miscs' +import { VideoChannel } from '../../models/videos' +import { BulkCommand } from '../bulk' +import { CLICommand } from '../cli' +import { CustomPagesCommand } from '../custom-pages' +import { FeedCommand } from '../feeds' +import { LogsCommand } from '../logs' +import { parallelTests, SQLCommand } from '../miscs' +import { AbusesCommand } from '../moderation' +import { OverviewsCommand } from '../overviews' +import { SearchCommand } from '../search' +import { SocketIOCommand } from '../socket' +import { AccountsCommand, BlocklistCommand, LoginCommand, NotificationsCommand, SubscriptionsCommand, UsersCommand } from '../users' +import { + BlacklistCommand, + CaptionsCommand, + ChangeOwnershipCommand, + ChannelsCommand, + HistoryCommand, + ImportsCommand, + LiveCommand, + PlaylistsCommand, + ServicesCommand, + StreamingPlaylistsCommand, + VideosCommand +} from '../videos' +import { CommentsCommand } from '../videos/comments-command' +import { ConfigCommand } from './config-command' +import { ContactFormCommand } from './contact-form-command' +import { DebugCommand } from './debug-command' +import { FollowsCommand } from './follows-command' +import { JobsCommand } from './jobs-command' +import { PluginsCommand } from './plugins-command' +import { RedundancyCommand } from './redundancy-command' +import { ServersCommand } from './servers-command' +import { StatsCommand } from './stats-command' + +export type RunServerOptions = { + hideLogs?: boolean + execArgv?: string[] +} + +export class PeerTubeServer { + app?: ChildProcess + + url: string + host?: string + hostname?: string + port?: number + + rtmpPort?: number + + parallel?: boolean + internalServerNumber: number + + serverNumber?: number + customConfigFile?: string + + store?: { + client?: { + id?: string + secret?: string + } + + user?: { + username: string + password: string + email?: string + } + + channel?: VideoChannel + + video?: { + id: number + uuid: string + shortUUID: string + name?: string + url?: string + + account?: { + name: string + } + + embedPath?: string + } + + videos?: { id: number, uuid: string }[] + } + + accessToken?: string + refreshToken?: string + + bulk?: BulkCommand + cli?: CLICommand + customPage?: CustomPagesCommand + feed?: FeedCommand + logs?: LogsCommand + abuses?: AbusesCommand + overviews?: OverviewsCommand + search?: SearchCommand + contactForm?: ContactFormCommand + debug?: DebugCommand + follows?: FollowsCommand + jobs?: JobsCommand + plugins?: PluginsCommand + redundancy?: RedundancyCommand + stats?: StatsCommand + config?: ConfigCommand + socketIO?: SocketIOCommand + accounts?: AccountsCommand + blocklist?: BlocklistCommand + subscriptions?: SubscriptionsCommand + live?: LiveCommand + services?: ServicesCommand + blacklist?: BlacklistCommand + captions?: CaptionsCommand + changeOwnership?: ChangeOwnershipCommand + playlists?: PlaylistsCommand + history?: HistoryCommand + imports?: ImportsCommand + streamingPlaylists?: StreamingPlaylistsCommand + channels?: ChannelsCommand + comments?: CommentsCommand + sql?: SQLCommand + notifications?: NotificationsCommand + servers?: ServersCommand + login?: LoginCommand + users?: UsersCommand + videos?: VideosCommand + + constructor (options: { serverNumber: number } | { url: string }) { + if ((options as any).url) { + this.setUrl((options as any).url) + } else { + this.setServerNumber((options as any).serverNumber) + } + + this.store = { + client: { + id: null, + secret: null + }, + user: { + username: null, + password: null + } + } + + this.assignCommands() + } + + setServerNumber (serverNumber: number) { + this.serverNumber = serverNumber + + this.parallel = parallelTests() + + this.internalServerNumber = this.parallel ? this.randomServer() : this.serverNumber + this.rtmpPort = this.parallel ? this.randomRTMP() : 1936 + this.port = 9000 + this.internalServerNumber + + this.url = `http://localhost:${this.port}` + this.host = `localhost:${this.port}` + this.hostname = 'localhost' + } + + setUrl (url: string) { + const parsed = new URL(url) + + this.url = url + this.host = parsed.host + this.hostname = parsed.hostname + this.port = parseInt(parsed.port) + } + + async flushAndRun (configOverride?: Object, args = [], options: RunServerOptions = {}) { + await ServersCommand.flushTests(this.internalServerNumber) + + return this.run(configOverride, args, options) + } + + async run (configOverrideArg?: any, args = [], options: RunServerOptions = {}) { + // These actions are async so we need to be sure that they have both been done + const serverRunString = { + 'HTTP server listening': false + } + const key = 'Database peertube_test' + this.internalServerNumber + ' is ready' + serverRunString[key] = false + + const regexps = { + client_id: 'Client id: (.+)', + client_secret: 'Client secret: (.+)', + user_username: 'Username: (.+)', + user_password: 'User password: (.+)' + } + + await this.assignCustomConfigFile() + + const configOverride = this.buildConfigOverride() + + if (configOverrideArg !== undefined) { + Object.assign(configOverride, configOverrideArg) + } + + // Share the environment + const env = Object.create(process.env) + env['NODE_ENV'] = 'test' + env['NODE_APP_INSTANCE'] = this.internalServerNumber.toString() + env['NODE_CONFIG'] = JSON.stringify(configOverride) + + const forkOptions = { + silent: true, + env, + detached: true, + execArgv: options.execArgv || [] + } + + return new Promise(res => { + this.app = fork(join(root(), 'dist', 'server.js'), args, forkOptions) + this.app.stdout.on('data', function onStdout (data) { + let dontContinue = false + + // Capture things if we want to + for (const key of Object.keys(regexps)) { + const regexp = regexps[key] + const matches = data.toString().match(regexp) + if (matches !== null) { + if (key === 'client_id') this.store.client.id = matches[1] + else if (key === 'client_secret') this.store.client.secret = matches[1] + else if (key === 'user_username') this.store.user.username = matches[1] + else if (key === 'user_password') this.store.user.password = matches[1] + } + } + + // Check if all required sentences are here + for (const key of Object.keys(serverRunString)) { + if (data.toString().indexOf(key) !== -1) serverRunString[key] = true + if (serverRunString[key] === false) dontContinue = true + } + + // If no, there is maybe one thing not already initialized (client/user credentials generation...) + if (dontContinue === true) return + + if (options.hideLogs === false) { + console.log(data.toString()) + } else { + this.app.stdout.removeListener('data', onStdout) + } + + process.on('exit', () => { + try { + process.kill(this.server.app.pid) + } catch { /* empty */ } + }) + + res() + }) + }) + } + + async kill () { + if (!this.app) return + + await this.sql.cleanup() + + process.kill(-this.app.pid) + + this.app = null + } + + private randomServer () { + const low = 10 + const high = 10000 + + return randomInt(low, high) + } + + private randomRTMP () { + const low = 1900 + const high = 2100 + + return randomInt(low, high) + } + + private async assignCustomConfigFile () { + if (this.internalServerNumber === this.serverNumber) return + + const basePath = join(root(), 'config') + + const tmpConfigFile = join(basePath, `test-${this.internalServerNumber}.yaml`) + await copy(join(basePath, `test-${this.serverNumber}.yaml`), tmpConfigFile) + + this.customConfigFile = tmpConfigFile + } + + private buildConfigOverride () { + if (!this.parallel) return {} + + return { + listen: { + port: this.port + }, + webserver: { + port: this.port + }, + database: { + suffix: '_test' + this.internalServerNumber + }, + storage: { + tmp: `test${this.internalServerNumber}/tmp/`, + avatars: `test${this.internalServerNumber}/avatars/`, + videos: `test${this.internalServerNumber}/videos/`, + streaming_playlists: `test${this.internalServerNumber}/streaming-playlists/`, + redundancy: `test${this.internalServerNumber}/redundancy/`, + logs: `test${this.internalServerNumber}/logs/`, + previews: `test${this.internalServerNumber}/previews/`, + thumbnails: `test${this.internalServerNumber}/thumbnails/`, + torrents: `test${this.internalServerNumber}/torrents/`, + captions: `test${this.internalServerNumber}/captions/`, + cache: `test${this.internalServerNumber}/cache/`, + plugins: `test${this.internalServerNumber}/plugins/` + }, + admin: { + email: `admin${this.internalServerNumber}@example.com` + }, + live: { + rtmp: { + port: this.rtmpPort + } + } + } + } + + private assignCommands () { + this.bulk = new BulkCommand(this) + this.cli = new CLICommand(this) + this.customPage = new CustomPagesCommand(this) + this.feed = new FeedCommand(this) + this.logs = new LogsCommand(this) + this.abuses = new AbusesCommand(this) + this.overviews = new OverviewsCommand(this) + this.search = new SearchCommand(this) + this.contactForm = new ContactFormCommand(this) + this.debug = new DebugCommand(this) + this.follows = new FollowsCommand(this) + this.jobs = new JobsCommand(this) + this.plugins = new PluginsCommand(this) + this.redundancy = new RedundancyCommand(this) + this.stats = new StatsCommand(this) + this.config = new ConfigCommand(this) + this.socketIO = new SocketIOCommand(this) + this.accounts = new AccountsCommand(this) + this.blocklist = new BlocklistCommand(this) + this.subscriptions = new SubscriptionsCommand(this) + this.live = new LiveCommand(this) + this.services = new ServicesCommand(this) + this.blacklist = new BlacklistCommand(this) + this.captions = new CaptionsCommand(this) + this.changeOwnership = new ChangeOwnershipCommand(this) + this.playlists = new PlaylistsCommand(this) + this.history = new HistoryCommand(this) + this.imports = new ImportsCommand(this) + this.streamingPlaylists = new StreamingPlaylistsCommand(this) + this.channels = new ChannelsCommand(this) + this.comments = new CommentsCommand(this) + this.sql = new SQLCommand(this) + this.notifications = new NotificationsCommand(this) + this.servers = new ServersCommand(this) + this.login = new LoginCommand(this) + this.users = new UsersCommand(this) + this.videos = new VideosCommand(this) + } +} diff --git a/shared/extra-utils/server/servers-command.ts b/shared/extra-utils/server/servers-command.ts index a7c5a868d..1a7b2aade 100644 --- a/shared/extra-utils/server/servers-command.ts +++ b/shared/extra-utils/server/servers-command.ts @@ -37,7 +37,7 @@ export class ServersCommand extends AbstractCommand { if (isGithubCI()) { await ensureDir('artifacts') - const origin = this.server.servers.buildDirectory('logs/peertube.log') + const origin = this.buildDirectory('logs/peertube.log') const destname = `peertube-${this.server.internalServerNumber}.log` console.log('Saving logs %s.', destname) diff --git a/shared/extra-utils/server/servers.ts b/shared/extra-utils/server/servers.ts index ea3f19a92..87d7e9449 100644 --- a/shared/extra-utils/server/servers.ts +++ b/shared/extra-utils/server/servers.ts @@ -1,391 +1,30 @@ -/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/no-floating-promises */ +import { ensureDir } from 'fs-extra' +import { isGithubCI } from '../miscs' +import { PeerTubeServer, RunServerOptions } from './server' -import { ChildProcess, fork } from 'child_process' -import { copy, ensureDir } from 'fs-extra' -import { join } from 'path' -import { root } from '@server/helpers/core-utils' -import { randomInt } from '../../core-utils/miscs/miscs' -import { VideoChannel } from '../../models/videos' -import { BulkCommand } from '../bulk' -import { CLICommand } from '../cli' -import { CustomPagesCommand } from '../custom-pages' -import { FeedCommand } from '../feeds' -import { LogsCommand } from '../logs' -import { isGithubCI, parallelTests, SQLCommand } from '../miscs' -import { AbusesCommand } from '../moderation' -import { OverviewsCommand } from '../overviews' -import { SearchCommand } from '../search' -import { SocketIOCommand } from '../socket' -import { AccountsCommand, BlocklistCommand, LoginCommand, NotificationsCommand, SubscriptionsCommand, UsersCommand } from '../users' -import { - BlacklistCommand, - CaptionsCommand, - ChangeOwnershipCommand, - ChannelsCommand, - HistoryCommand, - ImportsCommand, - LiveCommand, - PlaylistsCommand, - ServicesCommand, - StreamingPlaylistsCommand, - VideosCommand -} from '../videos' -import { CommentsCommand } from '../videos/comments-command' -import { ConfigCommand } from './config-command' -import { ContactFormCommand } from './contact-form-command' -import { DebugCommand } from './debug-command' -import { FollowsCommand } from './follows-command' -import { JobsCommand } from './jobs-command' -import { PluginsCommand } from './plugins-command' -import { RedundancyCommand } from './redundancy-command' -import { ServersCommand } from './servers-command' -import { StatsCommand } from './stats-command' +async function createSingleServer (serverNumber: number, configOverride?: Object, args = [], options: RunServerOptions = {}) { + const server = new PeerTubeServer({ serverNumber }) -interface ServerInfo { - app?: ChildProcess + await server.flushAndRun(configOverride, args, options) - url: string - host?: string - hostname?: string - port?: number - - rtmpPort?: number - - parallel?: boolean - internalServerNumber: number - - serverNumber?: number - customConfigFile?: string - - store?: { - client?: { - id?: string - secret?: string - } - - user?: { - username: string - password: string - email?: string - } - - channel?: VideoChannel - - video?: { - id: number - uuid: string - shortUUID: string - name?: string - url?: string - - account?: { - name: string - } - - embedPath?: string - } - - videos?: { id: number, uuid: string }[] - } - - accessToken?: string - refreshToken?: string - - bulk?: BulkCommand - cli?: CLICommand - customPage?: CustomPagesCommand - feed?: FeedCommand - logs?: LogsCommand - abuses?: AbusesCommand - overviews?: OverviewsCommand - search?: SearchCommand - contactForm?: ContactFormCommand - debug?: DebugCommand - follows?: FollowsCommand - jobs?: JobsCommand - plugins?: PluginsCommand - redundancy?: RedundancyCommand - stats?: StatsCommand - config?: ConfigCommand - socketIO?: SocketIOCommand - accounts?: AccountsCommand - blocklist?: BlocklistCommand - subscriptions?: SubscriptionsCommand - live?: LiveCommand - services?: ServicesCommand - blacklist?: BlacklistCommand - captions?: CaptionsCommand - changeOwnership?: ChangeOwnershipCommand - playlists?: PlaylistsCommand - history?: HistoryCommand - imports?: ImportsCommand - streamingPlaylists?: StreamingPlaylistsCommand - channels?: ChannelsCommand - comments?: CommentsCommand - sql?: SQLCommand - notifications?: NotificationsCommand - servers?: ServersCommand - login?: LoginCommand - users?: UsersCommand - videos?: VideosCommand -} - -function flushAndRunMultipleServers (totalServers: number, configOverride?: Object) { - const apps = [] - let i = 0 - - return new Promise(res => { - function anotherServerDone (serverNumber, app) { - apps[serverNumber - 1] = app - i++ - if (i === totalServers) { - return res(apps) - } - } - - for (let j = 1; j <= totalServers; j++) { - flushAndRunServer(j, configOverride).then(app => anotherServerDone(j, app)) - } - }) -} - -function randomServer () { - const low = 10 - const high = 10000 - - return randomInt(low, high) -} - -function randomRTMP () { - const low = 1900 - const high = 2100 - - return randomInt(low, high) -} - -type RunServerOptions = { - hideLogs?: boolean - execArgv?: string[] -} - -async function flushAndRunServer (serverNumber: number, configOverride?: Object, args = [], options: RunServerOptions = {}) { - const parallel = parallelTests() - - const internalServerNumber = parallel ? randomServer() : serverNumber - const rtmpPort = parallel ? randomRTMP() : 1936 - const port = 9000 + internalServerNumber - - await ServersCommand.flushTests(internalServerNumber) - - const server: ServerInfo = { - app: null, - port, - internalServerNumber, - rtmpPort, - parallel, - serverNumber, - url: `http://localhost:${port}`, - host: `localhost:${port}`, - hostname: 'localhost', - store: { - client: { - id: null, - secret: null - }, - user: { - username: null, - password: null - } - } - } - - return runServer(server, configOverride, args, options) + return server } -async function runServer (server: ServerInfo, configOverrideArg?: any, args = [], options: RunServerOptions = {}) { - // These actions are async so we need to be sure that they have both been done - const serverRunString = { - 'HTTP server listening': false - } - const key = 'Database peertube_test' + server.internalServerNumber + ' is ready' - serverRunString[key] = false - - const regexps = { - client_id: 'Client id: (.+)', - client_secret: 'Client secret: (.+)', - user_username: 'Username: (.+)', - user_password: 'User password: (.+)' - } - - if (server.internalServerNumber !== server.serverNumber) { - const basePath = join(root(), 'config') - - const tmpConfigFile = join(basePath, `test-${server.internalServerNumber}.yaml`) - await copy(join(basePath, `test-${server.serverNumber}.yaml`), tmpConfigFile) - - server.customConfigFile = tmpConfigFile - } - - const configOverride: any = {} - - if (server.parallel) { - Object.assign(configOverride, { - listen: { - port: server.port - }, - webserver: { - port: server.port - }, - database: { - suffix: '_test' + server.internalServerNumber - }, - storage: { - tmp: `test${server.internalServerNumber}/tmp/`, - avatars: `test${server.internalServerNumber}/avatars/`, - videos: `test${server.internalServerNumber}/videos/`, - streaming_playlists: `test${server.internalServerNumber}/streaming-playlists/`, - redundancy: `test${server.internalServerNumber}/redundancy/`, - logs: `test${server.internalServerNumber}/logs/`, - previews: `test${server.internalServerNumber}/previews/`, - thumbnails: `test${server.internalServerNumber}/thumbnails/`, - torrents: `test${server.internalServerNumber}/torrents/`, - captions: `test${server.internalServerNumber}/captions/`, - cache: `test${server.internalServerNumber}/cache/`, - plugins: `test${server.internalServerNumber}/plugins/` - }, - admin: { - email: `admin${server.internalServerNumber}@example.com` - }, - live: { - rtmp: { - port: server.rtmpPort - } - } - }) - } - - if (configOverrideArg !== undefined) { - Object.assign(configOverride, configOverrideArg) - } - - // Share the environment - const env = Object.create(process.env) - env['NODE_ENV'] = 'test' - env['NODE_APP_INSTANCE'] = server.internalServerNumber.toString() - env['NODE_CONFIG'] = JSON.stringify(configOverride) +function createMultipleServers (totalServers: number, configOverride?: Object) { + const serverPromises: Promise[] = [] - const forkOptions = { - silent: true, - env, - detached: true, - execArgv: options.execArgv || [] + for (let i = 1; i <= totalServers; i++) { + serverPromises.push(createSingleServer(i, configOverride)) } - return new Promise(res => { - server.app = fork(join(root(), 'dist', 'server.js'), args, forkOptions) - server.app.stdout.on('data', function onStdout (data) { - let dontContinue = false - - // Capture things if we want to - for (const key of Object.keys(regexps)) { - const regexp = regexps[key] - const matches = data.toString().match(regexp) - if (matches !== null) { - if (key === 'client_id') server.store.client.id = matches[1] - else if (key === 'client_secret') server.store.client.secret = matches[1] - else if (key === 'user_username') server.store.user.username = matches[1] - else if (key === 'user_password') server.store.user.password = matches[1] - } - } - - // Check if all required sentences are here - for (const key of Object.keys(serverRunString)) { - if (data.toString().indexOf(key) !== -1) serverRunString[key] = true - if (serverRunString[key] === false) dontContinue = true - } - - // If no, there is maybe one thing not already initialized (client/user credentials generation...) - if (dontContinue === true) return - - if (options.hideLogs === false) { - console.log(data.toString()) - } else { - server.app.stdout.removeListener('data', onStdout) - } - - process.on('exit', () => { - try { - process.kill(server.app.pid) - } catch { /* empty */ } - }) - - assignCommands(server) - - res(server) - }) - }) -} - -function assignCommands (server: ServerInfo) { - server.bulk = new BulkCommand(server) - server.cli = new CLICommand(server) - server.customPage = new CustomPagesCommand(server) - server.feed = new FeedCommand(server) - server.logs = new LogsCommand(server) - server.abuses = new AbusesCommand(server) - server.overviews = new OverviewsCommand(server) - server.search = new SearchCommand(server) - server.contactForm = new ContactFormCommand(server) - server.debug = new DebugCommand(server) - server.follows = new FollowsCommand(server) - server.jobs = new JobsCommand(server) - server.plugins = new PluginsCommand(server) - server.redundancy = new RedundancyCommand(server) - server.stats = new StatsCommand(server) - server.config = new ConfigCommand(server) - server.socketIO = new SocketIOCommand(server) - server.accounts = new AccountsCommand(server) - server.blocklist = new BlocklistCommand(server) - server.subscriptions = new SubscriptionsCommand(server) - server.live = new LiveCommand(server) - server.services = new ServicesCommand(server) - server.blacklist = new BlacklistCommand(server) - server.captions = new CaptionsCommand(server) - server.changeOwnership = new ChangeOwnershipCommand(server) - server.playlists = new PlaylistsCommand(server) - server.history = new HistoryCommand(server) - server.imports = new ImportsCommand(server) - server.streamingPlaylists = new StreamingPlaylistsCommand(server) - server.channels = new ChannelsCommand(server) - server.comments = new CommentsCommand(server) - server.sql = new SQLCommand(server) - server.notifications = new NotificationsCommand(server) - server.servers = new ServersCommand(server) - server.login = new LoginCommand(server) - server.users = new UsersCommand(server) - server.videos = new VideosCommand(server) -} - -async function reRunServer (server: ServerInfo, configOverride?: any) { - const newServer = await runServer(server, configOverride) - server.app = newServer.app - - return server + return Promise.all(serverPromises) } -async function killallServers (servers: ServerInfo[]) { - for (const server of servers) { - if (!server.app) continue - - await server.sql.cleanup() - - process.kill(-server.app.pid) - - server.app = null - } +async function killallServers (servers: PeerTubeServer[]) { + return Promise.all(servers.map(s => s.kill())) } -async function cleanupTests (servers: ServerInfo[]) { +async function cleanupTests (servers: PeerTubeServer[]) { await killallServers(servers) if (isGithubCI()) { @@ -403,11 +42,8 @@ async function cleanupTests (servers: ServerInfo[]) { // --------------------------------------------------------------------------- export { - ServerInfo, + createSingleServer, + createMultipleServers, cleanupTests, - flushAndRunMultipleServers, - flushAndRunServer, - killallServers, - reRunServer, - assignCommands + killallServers } diff --git a/shared/extra-utils/shared/abstract-command.ts b/shared/extra-utils/shared/abstract-command.ts index 5fddcf639..967f8f2ac 100644 --- a/shared/extra-utils/shared/abstract-command.ts +++ b/shared/extra-utils/shared/abstract-command.ts @@ -9,7 +9,7 @@ import { unwrapBody, unwrapText } from '../requests/requests' -import { ServerInfo } from '../server/servers' +import { PeerTubeServer } from '../server/server' export interface OverrideCommandOptions { token?: string @@ -38,7 +38,7 @@ interface InternalGetCommandOptions extends InternalCommonCommandOptions { abstract class AbstractCommand { constructor ( - protected server: ServerInfo + protected server: PeerTubeServer ) { } diff --git a/shared/extra-utils/users/accounts.ts b/shared/extra-utils/users/accounts.ts index 2c9a4b71c..9fc1bcfc4 100644 --- a/shared/extra-utils/users/accounts.ts +++ b/shared/extra-utils/users/accounts.ts @@ -4,10 +4,10 @@ import { expect } from 'chai' import { pathExists, readdir } from 'fs-extra' import { join } from 'path' import { root } from '@server/helpers/core-utils' -import { ServerInfo } from '../server' +import { PeerTubeServer } from '../server' async function expectAccountFollows (options: { - server: ServerInfo + server: PeerTubeServer handle: string followers: number following: number diff --git a/shared/extra-utils/users/login.ts b/shared/extra-utils/users/login.ts index d0c26a4f0..f1df027d3 100644 --- a/shared/extra-utils/users/login.ts +++ b/shared/extra-utils/users/login.ts @@ -1,6 +1,6 @@ -import { ServerInfo } from '../server/servers' +import { PeerTubeServer } from '../server/server' -function setAccessTokensToServers (servers: ServerInfo[]) { +function setAccessTokensToServers (servers: PeerTubeServer[]) { const tasks: Promise[] = [] for (const server of servers) { diff --git a/shared/extra-utils/users/notifications.ts b/shared/extra-utils/users/notifications.ts index 9196f0bf5..4c42fad3e 100644 --- a/shared/extra-utils/users/notifications.ts +++ b/shared/extra-utils/users/notifications.ts @@ -5,8 +5,9 @@ import { inspect } from 'util' import { AbuseState, PluginType } from '@shared/models' import { UserNotification, UserNotificationSetting, UserNotificationSettingValue, UserNotificationType } from '../../models/users' import { MockSmtpServer } from '../mock-servers/mock-email' +import { PeerTubeServer } from '../server' import { doubleFollow } from '../server/follows' -import { flushAndRunMultipleServers, ServerInfo } from '../server/servers' +import { createMultipleServers } from '../server/servers' import { setAccessTokensToServers } from './login' function getAllNotificationsSettings (): UserNotificationSetting { @@ -31,7 +32,7 @@ function getAllNotificationsSettings (): UserNotificationSetting { } type CheckerBaseParams = { - server: ServerInfo + server: PeerTubeServer emails: any[] socketNotifications: UserNotification[] token: string @@ -642,7 +643,7 @@ async function prepareNotificationsTest (serversCount = 3, overrideConfigArg: an limit: 20 } } - const servers = await flushAndRunMultipleServers(serversCount, Object.assign(overrideConfig, overrideConfigArg)) + const servers = await createMultipleServers(serversCount, Object.assign(overrideConfig, overrideConfigArg)) await setAccessTokensToServers(servers) diff --git a/shared/extra-utils/videos/channels.ts b/shared/extra-utils/videos/channels.ts index 81e818094..756c47453 100644 --- a/shared/extra-utils/videos/channels.ts +++ b/shared/extra-utils/videos/channels.ts @@ -1,6 +1,6 @@ -import { ServerInfo } from '../server/servers' +import { PeerTubeServer } from '../server/server' -function setDefaultVideoChannel (servers: ServerInfo[]) { +function setDefaultVideoChannel (servers: PeerTubeServer[]) { const tasks: Promise[] = [] for (const server of servers) { diff --git a/shared/extra-utils/videos/live.ts b/shared/extra-utils/videos/live.ts index 353595811..502964b1a 100644 --- a/shared/extra-utils/videos/live.ts +++ b/shared/extra-utils/videos/live.ts @@ -5,7 +5,7 @@ import * as ffmpeg from 'fluent-ffmpeg' import { pathExists, readdir } from 'fs-extra' import { join } from 'path' import { buildAbsoluteFixturePath, wait } from '../miscs' -import { ServerInfo } from '../server/servers' +import { PeerTubeServer } from '../server/server' function sendRTMPStream (rtmpBaseUrl: string, streamKey: string, fixtureName = 'video_short.mp4') { const fixture = buildAbsoluteFixturePath(fixtureName) @@ -70,13 +70,13 @@ async function stopFfmpeg (command: ffmpeg.FfmpegCommand) { await wait(500) } -async function waitUntilLivePublishedOnAllServers (servers: ServerInfo[], videoId: string) { +async function waitUntilLivePublishedOnAllServers (servers: PeerTubeServer[], videoId: string) { for (const server of servers) { await server.live.waitUntilPublished({ videoId }) } } -async function checkLiveCleanup (server: ServerInfo, videoUUID: string, resolutions: number[] = []) { +async function checkLiveCleanup (server: PeerTubeServer, videoUUID: string, resolutions: number[] = []) { const basePath = server.servers.buildDirectory('streaming-playlists') const hlsPath = join(basePath, 'hls', videoUUID) diff --git a/shared/extra-utils/videos/streaming-playlists.ts b/shared/extra-utils/videos/streaming-playlists.ts index e8fd2f232..002ae08b2 100644 --- a/shared/extra-utils/videos/streaming-playlists.ts +++ b/shared/extra-utils/videos/streaming-playlists.ts @@ -2,10 +2,10 @@ import { expect } from 'chai' import { sha256 } from '@server/helpers/core-utils' import { HttpStatusCode } from '@shared/core-utils' import { VideoStreamingPlaylist } from '@shared/models' -import { ServerInfo } from '../server' +import { PeerTubeServer } from '../server' async function checkSegmentHash (options: { - server: ServerInfo + server: PeerTubeServer baseUrlPlaylist: string baseUrlSegment: string videoUUID: string @@ -36,7 +36,7 @@ async function checkSegmentHash (options: { } async function checkLiveSegmentHash (options: { - server: ServerInfo + server: PeerTubeServer baseUrlSegment: string videoUUID: string segmentName: string @@ -52,7 +52,7 @@ async function checkLiveSegmentHash (options: { } async function checkResolutionsInMasterPlaylist (options: { - server: ServerInfo + server: PeerTubeServer playlistUrl: string resolutions: number[] }) { diff --git a/shared/extra-utils/videos/videos-command.ts b/shared/extra-utils/videos/videos-command.ts index 5556cddf6..feef5a771 100644 --- a/shared/extra-utils/videos/videos-command.ts +++ b/shared/extra-utils/videos/videos-command.ts @@ -22,7 +22,7 @@ import { } from '@shared/models' import { buildAbsoluteFixturePath, wait } from '../miscs' import { unwrapBody } from '../requests' -import { ServerInfo, waitJobs } from '../server' +import { PeerTubeServer, waitJobs } from '../server' import { AbstractCommand, OverrideCommandOptions } from '../shared' export type VideoEdit = Partial> & { @@ -33,7 +33,7 @@ export type VideoEdit = Partial, expectedStatus = HttpStatusCode.OK_200, @@ -52,7 +52,7 @@ function checkUploadVideoParam ( } async function completeVideoCheck ( - server: ServerInfo, + server: PeerTubeServer, video: any, attributes: { name: string @@ -197,7 +197,7 @@ async function completeVideoCheck ( // serverNumber starts from 1 async function uploadRandomVideoOnServers ( - servers: ServerInfo[], + servers: PeerTubeServer[], serverNumber: number, additionalParams?: VideoEdit & { prefixName?: string } ) { -- cgit v1.2.3 From 59bbcced37005dd511daca9bd58ae2998cb931b1 Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Fri, 16 Jul 2021 10:19:16 +0200 Subject: Centralize test URLs --- server/tests/api/check-params/upload-quota.ts | 6 ++-- server/tests/api/check-params/video-imports.ts | 6 ++-- server/tests/api/moderation/video-blacklist.ts | 8 ++--- .../tests/api/notifications/user-notifications.ts | 16 ++++----- server/tests/api/videos/video-imports.ts | 18 +++++----- server/tests/cli/peertube.ts | 8 ++--- server/tests/helpers/request.ts | 10 +++--- server/tests/plugins/filter-hooks.ts | 12 +++---- shared/extra-utils/miscs/tests.ts | 32 ++++++++++++++++++ shared/extra-utils/requests/requests.ts | 5 --- shared/extra-utils/videos/imports-command.ts | 38 ---------------------- 11 files changed, 74 insertions(+), 85 deletions(-) diff --git a/server/tests/api/check-params/upload-quota.ts b/server/tests/api/check-params/upload-quota.ts index 2c73e6a19..bd8dce975 100644 --- a/server/tests/api/check-params/upload-quota.ts +++ b/server/tests/api/check-params/upload-quota.ts @@ -6,7 +6,7 @@ import { HttpStatusCode, randomInt } from '@shared/core-utils' import { cleanupTests, createSingleServer, - ImportsCommand, + FIXTURE_URLS, PeerTubeServer, setAccessTokensToServers, setDefaultVideoChannel, @@ -76,8 +76,8 @@ describe('Test upload quota', function () { channelId: server.store.channel.id, privacy: VideoPrivacy.PUBLIC } - await server.imports.importVideo({ attributes: { ...baseAttributes, targetUrl: ImportsCommand.getGoodVideoUrl() } }) - await server.imports.importVideo({ attributes: { ...baseAttributes, magnetUri: ImportsCommand.getMagnetURI() } }) + await server.imports.importVideo({ attributes: { ...baseAttributes, targetUrl: FIXTURE_URLS.goodVideo } }) + await server.imports.importVideo({ attributes: { ...baseAttributes, magnetUri: FIXTURE_URLS.magnet } }) await server.imports.importVideo({ attributes: { ...baseAttributes, torrentfile: 'video-720p.torrent' as any } }) await waitJobs([ server ]) diff --git a/server/tests/api/check-params/video-imports.ts b/server/tests/api/check-params/video-imports.ts index 627f0c7ad..0209275ac 100644 --- a/server/tests/api/check-params/video-imports.ts +++ b/server/tests/api/check-params/video-imports.ts @@ -10,7 +10,7 @@ import { checkBadStartPagination, cleanupTests, createSingleServer, - ImportsCommand, + FIXTURE_URLS, makeGetRequest, makePostBodyRequest, makeUploadRequest, @@ -70,7 +70,7 @@ describe('Test video imports API validator', function () { before(function () { baseCorrectParams = { - targetUrl: ImportsCommand.getGoodVideoUrl(), + targetUrl: FIXTURE_URLS.goodVideo, name: 'my super name', category: 5, licence: 1, @@ -297,7 +297,7 @@ describe('Test video imports API validator', function () { }) let fields = omit(baseCorrectParams, 'targetUrl') - fields = { ...fields, magnetUri: ImportsCommand.getMagnetURI() } + fields = { ...fields, magnetUri: FIXTURE_URLS.magnet } await makePostBodyRequest({ url: server.url, diff --git a/server/tests/api/moderation/video-blacklist.ts b/server/tests/api/moderation/video-blacklist.ts index 62cbf2e07..d5838191a 100644 --- a/server/tests/api/moderation/video-blacklist.ts +++ b/server/tests/api/moderation/video-blacklist.ts @@ -6,9 +6,9 @@ import { orderBy } from 'lodash' import { BlacklistCommand, cleanupTests, - doubleFollow, createMultipleServers, - ImportsCommand, + doubleFollow, + FIXTURE_URLS, killallServers, PeerTubeServer, setAccessTokensToServers, @@ -387,7 +387,7 @@ describe('Test video blacklist', function () { this.timeout(15000) const attributes = { - targetUrl: ImportsCommand.getGoodVideoUrl(), + targetUrl: FIXTURE_URLS.goodVideo, name: 'URL import', channelId: channelOfUserWithoutFlag } @@ -400,7 +400,7 @@ describe('Test video blacklist', function () { it('Should auto blacklist a video on torrent import', async function () { const attributes = { - magnetUri: ImportsCommand.getMagnetURI(), + magnetUri: FIXTURE_URLS.magnet, name: 'Torrent import', channelId: channelOfUserWithoutFlag } diff --git a/server/tests/api/notifications/user-notifications.ts b/server/tests/api/notifications/user-notifications.ts index b7c22d118..ca592d466 100644 --- a/server/tests/api/notifications/user-notifications.ts +++ b/server/tests/api/notifications/user-notifications.ts @@ -10,10 +10,10 @@ import { checkNewVideoFromSubscription, checkVideoIsPublished, cleanupTests, - ImportsCommand, + FIXTURE_URLS, MockSmtpServer, - prepareNotificationsTest, PeerTubeServer, + prepareNotificationsTest, uploadRandomVideoOnServers, wait, waitJobs @@ -205,7 +205,7 @@ describe('Test user notifications', function () { name, channelId, privacy: VideoPrivacy.PUBLIC, - targetUrl: ImportsCommand.getGoodVideoUrl() + targetUrl: FIXTURE_URLS.goodVideo } const { video } = await servers[0].imports.importVideo({ attributes }) @@ -275,7 +275,7 @@ describe('Test user notifications', function () { name, channelId, privacy: VideoPrivacy.PUBLIC, - targetUrl: ImportsCommand.getGoodVideoUrl(), + targetUrl: FIXTURE_URLS.goodVideo, waitTranscoding: true } const { video } = await servers[1].imports.importVideo({ attributes }) @@ -343,12 +343,12 @@ describe('Test user notifications', function () { name, channelId, privacy: VideoPrivacy.PRIVATE, - targetUrl: ImportsCommand.getBadVideoUrl() + targetUrl: FIXTURE_URLS.badVideo } const { video } = await servers[0].imports.importVideo({ attributes }) await waitJobs(servers) - await checkMyVideoImportIsFinished(baseParams, name, video.uuid, ImportsCommand.getBadVideoUrl(), false, 'presence') + await checkMyVideoImportIsFinished(baseParams, name, video.uuid, FIXTURE_URLS.badVideo, false, 'presence') }) it('Should send a notification when the video import succeeded', async function () { @@ -360,12 +360,12 @@ describe('Test user notifications', function () { name, channelId, privacy: VideoPrivacy.PRIVATE, - targetUrl: ImportsCommand.getGoodVideoUrl() + targetUrl: FIXTURE_URLS.goodVideo } const { video } = await servers[0].imports.importVideo({ attributes }) await waitJobs(servers) - await checkMyVideoImportIsFinished(baseParams, name, video.uuid, ImportsCommand.getGoodVideoUrl(), true, 'presence') + await checkMyVideoImportIsFinished(baseParams, name, video.uuid, FIXTURE_URLS.goodVideo, true, 'presence') }) }) diff --git a/server/tests/api/videos/video-imports.ts b/server/tests/api/videos/video-imports.ts index 4ef55c3af..192f5232e 100644 --- a/server/tests/api/videos/video-imports.ts +++ b/server/tests/api/videos/video-imports.ts @@ -5,9 +5,9 @@ import * as chai from 'chai' import { areHttpImportTestsDisabled, cleanupTests, - doubleFollow, createMultipleServers, - ImportsCommand, + doubleFollow, + FIXTURE_URLS, PeerTubeServer, setAccessTokensToServers, testCaptionFile, @@ -110,7 +110,7 @@ describe('Test video imports', function () { } { - const attributes = { ...baseAttributes, targetUrl: ImportsCommand.getYoutubeVideoUrl() } + const attributes = { ...baseAttributes, targetUrl: FIXTURE_URLS.youtube } const { video } = await servers[0].imports.importVideo({ attributes }) expect(video.name).to.equal('small video - youtube') @@ -162,7 +162,7 @@ Ajouter un sous-titre est vraiment facile`) { const attributes = { ...baseAttributes, - magnetUri: ImportsCommand.getMagnetURI(), + magnetUri: FIXTURE_URLS.magnet, description: 'this is a super torrent description', tags: [ 'tag_torrent1', 'tag_torrent2' ] } @@ -199,13 +199,13 @@ Ajouter un sous-titre est vraiment facile`) expect(videoImports).to.have.lengthOf(3) - expect(videoImports[2].targetUrl).to.equal(ImportsCommand.getYoutubeVideoUrl()) + expect(videoImports[2].targetUrl).to.equal(FIXTURE_URLS.youtube) expect(videoImports[2].magnetUri).to.be.null expect(videoImports[2].torrentName).to.be.null expect(videoImports[2].video.name).to.equal('small video - youtube') expect(videoImports[1].targetUrl).to.be.null - expect(videoImports[1].magnetUri).to.equal(ImportsCommand.getMagnetURI()) + expect(videoImports[1].magnetUri).to.equal(FIXTURE_URLS.magnet) expect(videoImports[1].torrentName).to.be.null expect(videoImports[1].video.name).to.equal('super peertube2 video') @@ -234,7 +234,7 @@ Ajouter un sous-titre est vraiment facile`) this.timeout(60_000) const attributes = { - targetUrl: ImportsCommand.getYoutubeVideoUrl(), + targetUrl: FIXTURE_URLS.youtube, channelId: channelIdServer2, privacy: VideoPrivacy.PUBLIC, category: 10, @@ -270,7 +270,7 @@ Ajouter un sous-titre est vraiment facile`) const attributes = { name: 'transcoded video', - magnetUri: ImportsCommand.getMagnetURI(), + magnetUri: FIXTURE_URLS.magnet, channelId: channelIdServer2, privacy: VideoPrivacy.PUBLIC } @@ -320,7 +320,7 @@ Ajouter un sous-titre est vraiment facile`) const attributes = { name: 'hdr video', - targetUrl: ImportsCommand.getYoutubeHDRVideoUrl(), + targetUrl: FIXTURE_URLS.youtubeHDR, channelId: channelIdServer1, privacy: VideoPrivacy.PUBLIC } diff --git a/server/tests/cli/peertube.ts b/server/tests/cli/peertube.ts index f19b6ae22..f2a984962 100644 --- a/server/tests/cli/peertube.ts +++ b/server/tests/cli/peertube.ts @@ -7,9 +7,9 @@ import { buildAbsoluteFixturePath, cleanupTests, CLICommand, - doubleFollow, createSingleServer, - ImportsCommand, + doubleFollow, + FIXTURE_URLS, PeerTubeServer, setAccessTokensToServers, testHelloWorldRegisteredSettings, @@ -117,7 +117,7 @@ describe('Test CLI wrapper', function () { this.timeout(60000) - const params = `--target-url ${ImportsCommand.getYoutubeVideoUrl()} --channel-name user_channel` + const params = `--target-url ${FIXTURE_URLS.youtube} --channel-name user_channel` await cliCommand.execWithEnv(`${cmd} import ${params}`) }) @@ -148,7 +148,7 @@ describe('Test CLI wrapper', function () { this.timeout(60000) - const params = `--target-url ${ImportsCommand.getYoutubeVideoUrl()} ` + + const params = `--target-url ${FIXTURE_URLS.youtube} ` + `--channel-name user_channel --video-name toto --nsfw --support support` await cliCommand.execWithEnv(`${cmd} import ${params}`) diff --git a/server/tests/helpers/request.ts b/server/tests/helpers/request.ts index 5e77f129e..7f7873df3 100644 --- a/server/tests/helpers/request.ts +++ b/server/tests/helpers/request.ts @@ -4,7 +4,7 @@ import 'mocha' import { expect } from 'chai' import { pathExists, remove } from 'fs-extra' import { join } from 'path' -import { get4KFileUrl, root, wait } from '../../../shared/extra-utils' +import { FIXTURE_URLS, root, wait } from '../../../shared/extra-utils' import { doRequest, doRequestAndSaveToFile } from '../../helpers/requests' describe('Request helpers', function () { @@ -13,7 +13,7 @@ describe('Request helpers', function () { it('Should throw an error when the bytes limit is exceeded for request', async function () { try { - await doRequest(get4KFileUrl(), { bodyKBLimit: 3 }) + await doRequest(FIXTURE_URLS.video4K, { bodyKBLimit: 3 }) } catch { return } @@ -23,7 +23,7 @@ describe('Request helpers', function () { it('Should throw an error when the bytes limit is exceeded for request and save file', async function () { try { - await doRequestAndSaveToFile(get4KFileUrl(), destPath1, { bodyKBLimit: 3 }) + await doRequestAndSaveToFile(FIXTURE_URLS.video4K, destPath1, { bodyKBLimit: 3 }) } catch { await wait(500) @@ -35,8 +35,8 @@ describe('Request helpers', function () { }) it('Should succeed if the file is below the limit', async function () { - await doRequest(get4KFileUrl(), { bodyKBLimit: 5 }) - await doRequestAndSaveToFile(get4KFileUrl(), destPath2, { bodyKBLimit: 5 }) + await doRequest(FIXTURE_URLS.video4K, { bodyKBLimit: 5 }) + await doRequestAndSaveToFile(FIXTURE_URLS.video4K, destPath2, { bodyKBLimit: 5 }) expect(await pathExists(destPath2)).to.be.true }) diff --git a/server/tests/plugins/filter-hooks.ts b/server/tests/plugins/filter-hooks.ts index 5d94303a9..df52bb3b5 100644 --- a/server/tests/plugins/filter-hooks.ts +++ b/server/tests/plugins/filter-hooks.ts @@ -5,12 +5,12 @@ import * as chai from 'chai' import { HttpStatusCode } from '@shared/core-utils' import { cleanupTests, - doubleFollow, createMultipleServers, - ImportsCommand, + doubleFollow, + FIXTURE_URLS, makeRawRequest, - PluginsCommand, PeerTubeServer, + PluginsCommand, setAccessTokensToServers, setDefaultVideoChannel, waitJobs @@ -136,7 +136,7 @@ describe('Test plugin filter hooks', function () { name: 'normal title', privacy: VideoPrivacy.PUBLIC, channelId: servers[0].store.channel.id, - targetUrl: ImportsCommand.getGoodVideoUrl() + 'bad' + targetUrl: FIXTURE_URLS.goodVideo + 'bad' } await servers[0].imports.importVideo({ attributes, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) @@ -161,7 +161,7 @@ describe('Test plugin filter hooks', function () { name: 'title with bad word', privacy: VideoPrivacy.PUBLIC, channelId: servers[0].store.channel.id, - targetUrl: ImportsCommand.getGoodVideoUrl() + targetUrl: FIXTURE_URLS.goodVideo } const body = await servers[0].imports.importVideo({ attributes }) videoImportId = body.id @@ -273,7 +273,7 @@ describe('Test plugin filter hooks', function () { const attributes = { name: 'video please blacklist me', - targetUrl: ImportsCommand.getGoodVideoUrl(), + targetUrl: FIXTURE_URLS.goodVideo, channelId: servers[0].store.channel.id } const body = await servers[0].imports.importVideo({ attributes }) diff --git a/shared/extra-utils/miscs/tests.ts b/shared/extra-utils/miscs/tests.ts index 8f7a2f92b..3dfb2487e 100644 --- a/shared/extra-utils/miscs/tests.ts +++ b/shared/extra-utils/miscs/tests.ts @@ -1,6 +1,36 @@ import { stat } from 'fs-extra' import { basename, isAbsolute, join, resolve } from 'path' +const FIXTURE_URLS = { + youtube: 'https://www.youtube.com/watch?v=msX3jv1XdvM', + + /** + * The video is used to check format-selection correctness wrt. HDR, + * which brings its own set of oddities outside of a MediaSource. + * FIXME: refactor once HDR is supported at playback + * + * The video needs to have the following format_ids: + * (which you can check by using `youtube-dl -F`): + * - 303 (1080p webm vp9) + * - 299 (1080p mp4 avc1) + * - 335 (1080p webm vp9.2 HDR) + * + * 15 jan. 2021: TEST VIDEO NOT CURRENTLY PROVIDING + * - 400 (1080p mp4 av01) + * - 315 (2160p webm vp9 HDR) + * - 337 (2160p webm vp9.2 HDR) + * - 401 (2160p mp4 av01 HDR) + */ + youtubeHDR: 'https://www.youtube.com/watch?v=qR5vOXbZsI4', + + // eslint-disable-next-line max-len + magnet: 'magnet:?xs=https%3A%2F%2Fpeertube2.cpy.re%2Fstatic%2Ftorrents%2Fb209ca00-c8bb-4b2b-b421-1ede169f3dbc-720.torrent&xt=urn:btih:0f498834733e8057ed5c6f2ee2b4efd8d84a76ee&dn=super+peertube2+video&tr=wss%3A%2F%2Fpeertube2.cpy.re%3A443%2Ftracker%2Fsocket&tr=https%3A%2F%2Fpeertube2.cpy.re%2Ftracker%2Fannounce&ws=https%3A%2F%2Fpeertube2.cpy.re%2Fstatic%2Fwebseed%2Fb209ca00-c8bb-4b2b-b421-1ede169f3dbc-720.mp4', + + badVideo: 'https://download.cpy.re/peertube/bad_video.mp4', + goodVideo: 'https://download.cpy.re/peertube/good_video.mp4', + video4K: 'https://download.cpy.re/peertube/4k_file.txt' +} + function parallelTests () { return process.env.MOCHA_PARALLEL === 'true' } @@ -51,6 +81,8 @@ function buildRequestStub (): any { } export { + FIXTURE_URLS, + parallelTests, isGithubCI, areHttpImportTestsDisabled, diff --git a/shared/extra-utils/requests/requests.ts b/shared/extra-utils/requests/requests.ts index 3f1ac6650..60c9b938b 100644 --- a/shared/extra-utils/requests/requests.ts +++ b/shared/extra-utils/requests/requests.ts @@ -7,10 +7,6 @@ import { URL } from 'url' import { HttpStatusCode } from '@shared/core-utils' import { buildAbsoluteFixturePath, root } from '../miscs/tests' -function get4KFileUrl () { - return 'https://download.cpy.re/peertube/4k_file.txt' -} - function makeRawRequest (url: string, statusCodeExpected?: HttpStatusCode, range?: string) { const { host, protocol, pathname } = new URL(url) @@ -227,7 +223,6 @@ function unwrapText (test: request.Test): Promise { // --------------------------------------------------------------------------- export { - get4KFileUrl, makeHTMLRequest, makeGetRequest, decodeQueryString, diff --git a/shared/extra-utils/videos/imports-command.ts b/shared/extra-utils/videos/imports-command.ts index 024aa363f..de8b65829 100644 --- a/shared/extra-utils/videos/imports-command.ts +++ b/shared/extra-utils/videos/imports-command.ts @@ -7,44 +7,6 @@ import { AbstractCommand, OverrideCommandOptions } from '../shared' export class ImportsCommand extends AbstractCommand { - static getYoutubeVideoUrl () { - return 'https://www.youtube.com/watch?v=msX3jv1XdvM' - } - - static getYoutubeHDRVideoUrl () { - /** - * The video is used to check format-selection correctness wrt. HDR, - * which brings its own set of oddities outside of a MediaSource. - * FIXME: refactor once HDR is supported at playback - * - * The video needs to have the following format_ids: - * (which you can check by using `youtube-dl -F`): - * - 303 (1080p webm vp9) - * - 299 (1080p mp4 avc1) - * - 335 (1080p webm vp9.2 HDR) - * - * 15 jan. 2021: TEST VIDEO NOT CURRENTLY PROVIDING - * - 400 (1080p mp4 av01) - * - 315 (2160p webm vp9 HDR) - * - 337 (2160p webm vp9.2 HDR) - * - 401 (2160p mp4 av01 HDR) - */ - return 'https://www.youtube.com/watch?v=qR5vOXbZsI4' - } - - static getMagnetURI () { - // eslint-disable-next-line max-len - return 'magnet:?xs=https%3A%2F%2Fpeertube2.cpy.re%2Fstatic%2Ftorrents%2Fb209ca00-c8bb-4b2b-b421-1ede169f3dbc-720.torrent&xt=urn:btih:0f498834733e8057ed5c6f2ee2b4efd8d84a76ee&dn=super+peertube2+video&tr=wss%3A%2F%2Fpeertube2.cpy.re%3A443%2Ftracker%2Fsocket&tr=https%3A%2F%2Fpeertube2.cpy.re%2Ftracker%2Fannounce&ws=https%3A%2F%2Fpeertube2.cpy.re%2Fstatic%2Fwebseed%2Fb209ca00-c8bb-4b2b-b421-1ede169f3dbc-720.mp4' - } - - static getBadVideoUrl () { - return 'https://download.cpy.re/peertube/bad_video.mp4' - } - - static getGoodVideoUrl () { - return 'https://download.cpy.re/peertube/good_video.mp4' - } - importVideo (options: OverrideCommandOptions & { attributes: VideoImportCreate & { torrentfile?: string } }) { -- cgit v1.2.3 From 08642a765ea514a00f159db898edf14c376fbe6c Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Fri, 16 Jul 2021 10:20:44 +0200 Subject: Fix server run --- server/tests/api/check-params/video-comments.ts | 2 +- shared/extra-utils/server/server.ts | 14 ++++++++------ 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/server/tests/api/check-params/video-comments.ts b/server/tests/api/check-params/video-comments.ts index ea5340b40..92c29da0e 100644 --- a/server/tests/api/check-params/video-comments.ts +++ b/server/tests/api/check-params/video-comments.ts @@ -38,7 +38,7 @@ describe('Test video comments API validator', function () { await setAccessTokensToServers([ server ]) { - const video = await server.videos.upload({ attributes: {} }) + video = await server.videos.upload({ attributes: {} }) pathThread = '/api/v1/videos/' + video.uuid + '/comment-threads' } diff --git a/shared/extra-utils/server/server.ts b/shared/extra-utils/server/server.ts index b1347661f..cc6df2efe 100644 --- a/shared/extra-utils/server/server.ts +++ b/shared/extra-utils/server/server.ts @@ -219,6 +219,8 @@ export class PeerTubeServer { } return new Promise(res => { + const self = this + this.app = fork(join(root(), 'dist', 'server.js'), args, forkOptions) this.app.stdout.on('data', function onStdout (data) { let dontContinue = false @@ -228,10 +230,10 @@ export class PeerTubeServer { const regexp = regexps[key] const matches = data.toString().match(regexp) if (matches !== null) { - if (key === 'client_id') this.store.client.id = matches[1] - else if (key === 'client_secret') this.store.client.secret = matches[1] - else if (key === 'user_username') this.store.user.username = matches[1] - else if (key === 'user_password') this.store.user.password = matches[1] + if (key === 'client_id') self.store.client.id = matches[1] + else if (key === 'client_secret') self.store.client.secret = matches[1] + else if (key === 'user_username') self.store.user.username = matches[1] + else if (key === 'user_password') self.store.user.password = matches[1] } } @@ -247,12 +249,12 @@ export class PeerTubeServer { if (options.hideLogs === false) { console.log(data.toString()) } else { - this.app.stdout.removeListener('data', onStdout) + self.app.stdout.removeListener('data', onStdout) } process.on('exit', () => { try { - process.kill(this.server.app.pid) + process.kill(self.server.app.pid) } catch { /* empty */ } }) -- cgit v1.2.3 From c0e8b12e7fd554ba4d2ceb0c4900804c6a4c63ea Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Fri, 16 Jul 2021 10:42:24 +0200 Subject: Refactor requests --- .../contact-admin-modal.component.ts | 3 +- client/src/app/+accounts/accounts.component.ts | 3 +- .../my-video-channel-create.component.ts | 7 +- .../+page-not-found/page-not-found.component.ts | 3 +- .../+video-channels/video-channels.component.ts | 2 +- .../video-add-components/video-upload.component.ts | 3 +- .../+videos/+video-watch/video-watch.component.ts | 11 +- client/src/app/core/auth/auth.service.ts | 3 +- client/src/app/core/rest/rest-extractor.service.ts | 3 +- client/src/app/helpers/utils.ts | 2 +- .../shared-main/auth/auth-interceptor.service.ts | 8 +- client/src/standalone/videos/embed.ts | 2 +- server.ts | 2 +- server/controllers/activitypub/inbox.ts | 2 +- server/controllers/api/abuse.ts | 2 +- server/controllers/api/bulk.ts | 2 +- server/controllers/api/custom-page.ts | 2 +- server/controllers/api/index.ts | 2 +- server/controllers/api/oauth-clients.ts | 2 +- server/controllers/api/plugins.ts | 2 +- .../api/search/search-video-channels.ts | 2 +- .../api/search/search-video-playlists.ts | 2 +- server/controllers/api/search/search-videos.ts | 2 +- server/controllers/api/server/contact.ts | 4 +- server/controllers/api/server/debug.ts | 2 +- server/controllers/api/server/follows.ts | 2 +- server/controllers/api/server/redundancy.ts | 16 +- server/controllers/api/server/server-blocklist.ts | 4 +- server/controllers/api/users/index.ts | 2 +- server/controllers/api/users/me.ts | 2 +- server/controllers/api/users/my-blocklist.ts | 2 +- server/controllers/api/users/my-history.ts | 2 +- server/controllers/api/users/my-notifications.ts | 2 +- server/controllers/api/users/my-subscriptions.ts | 2 +- server/controllers/api/video-channel.ts | 2 +- server/controllers/api/video-playlist.ts | 2 +- server/controllers/api/videos/blacklist.ts | 2 +- server/controllers/api/videos/captions.ts | 2 +- server/controllers/api/videos/comment.ts | 2 +- server/controllers/api/videos/index.ts | 2 +- server/controllers/api/videos/live.ts | 2 +- server/controllers/api/videos/ownership.ts | 2 +- server/controllers/api/videos/rate.ts | 2 +- server/controllers/api/videos/update.ts | 4 +- server/controllers/api/videos/upload.ts | 2 +- server/controllers/api/videos/watching.ts | 2 +- server/controllers/client.ts | 2 +- server/controllers/download.ts | 2 +- server/controllers/lazy-static.ts | 2 +- server/controllers/live.ts | 2 +- server/controllers/plugins.ts | 2 +- server/controllers/static.ts | 2 +- .../helpers/custom-validators/video-ownership.ts | 2 +- server/helpers/express-utils.ts | 2 +- server/helpers/youtube-dl.ts | 2 +- server/lib/activitypub/actors/refresh.ts | 2 +- server/lib/activitypub/playlists/refresh.ts | 2 +- server/lib/activitypub/videos/refresh.ts | 2 +- server/lib/client-html.ts | 2 +- .../lib/job-queue/handlers/activitypub-cleaner.ts | 2 +- server/middlewares/activitypub.ts | 2 +- server/middlewares/auth.ts | 2 +- server/middlewares/cache.ts | 2 +- server/middlewares/error.ts | 2 +- server/middlewares/servers.ts | 2 +- server/middlewares/user-right.ts | 2 +- server/middlewares/validators/abuse.ts | 2 +- .../middlewares/validators/activitypub/activity.ts | 2 +- server/middlewares/validators/blocklist.ts | 2 +- server/middlewares/validators/bulk.ts | 2 +- server/middlewares/validators/feeds.ts | 2 +- server/middlewares/validators/follows.ts | 2 +- server/middlewares/validators/oembed.ts | 2 +- server/middlewares/validators/plugins.ts | 2 +- server/middlewares/validators/redundancy.ts | 2 +- server/middlewares/validators/server.ts | 2 +- server/middlewares/validators/shared/abuses.ts | 2 +- server/middlewares/validators/shared/accounts.ts | 2 +- .../validators/shared/video-blacklists.ts | 2 +- .../validators/shared/video-captions.ts | 2 +- .../validators/shared/video-channels.ts | 2 +- .../validators/shared/video-comments.ts | 2 +- .../middlewares/validators/shared/video-imports.ts | 2 +- .../validators/shared/video-ownerships.ts | 2 +- .../validators/shared/video-playlists.ts | 2 +- server/middlewares/validators/shared/videos.ts | 2 +- server/middlewares/validators/themes.ts | 2 +- .../middlewares/validators/user-subscriptions.ts | 2 +- server/middlewares/validators/users.ts | 2 +- .../validators/videos/video-blacklist.ts | 2 +- .../validators/videos/video-channels.ts | 2 +- .../validators/videos/video-comments.ts | 2 +- .../middlewares/validators/videos/video-imports.ts | 2 +- server/middlewares/validators/videos/video-live.ts | 2 +- .../validators/videos/video-ownership-changes.ts | 2 +- .../validators/videos/video-playlists.ts | 2 +- .../middlewares/validators/videos/video-rates.ts | 2 +- .../middlewares/validators/videos/video-shares.ts | 2 +- .../middlewares/validators/videos/video-watch.ts | 2 +- server/middlewares/validators/videos/videos.ts | 2 +- server/middlewares/validators/webfinger.ts | 2 +- server/tests/api/activitypub/client.ts | 4 +- server/tests/api/activitypub/refresher.ts | 2 +- server/tests/api/activitypub/security.ts | 19 +- server/tests/api/check-params/abuses.ts | 26 +- server/tests/api/check-params/accounts.ts | 2 +- server/tests/api/check-params/blocklist.ts | 91 +++--- server/tests/api/check-params/bulk.ts | 20 +- server/tests/api/check-params/config.ts | 24 +- server/tests/api/check-params/contact-form.ts | 2 +- server/tests/api/check-params/custom-pages.ts | 15 +- server/tests/api/check-params/debug.ts | 17 +- server/tests/api/check-params/follows.ts | 64 ++-- server/tests/api/check-params/jobs.ts | 19 +- server/tests/api/check-params/live.ts | 14 +- server/tests/api/check-params/logs.ts | 25 +- server/tests/api/check-params/plugins.ts | 66 ++-- server/tests/api/check-params/redundancy.ts | 39 ++- server/tests/api/check-params/search.ts | 62 ++-- server/tests/api/check-params/services.ts | 6 +- server/tests/api/check-params/upload-quota.ts | 4 +- .../tests/api/check-params/user-notifications.ts | 32 +- .../tests/api/check-params/user-subscriptions.ts | 68 ++-- server/tests/api/check-params/users.ts | 74 ++--- server/tests/api/check-params/video-blacklist.ts | 18 +- server/tests/api/check-params/video-captions.ts | 30 +- server/tests/api/check-params/video-channels.ts | 26 +- server/tests/api/check-params/video-comments.ts | 52 +-- server/tests/api/check-params/video-imports.ts | 14 +- server/tests/api/check-params/video-playlists.ts | 18 +- server/tests/api/check-params/videos-filter.ts | 14 +- server/tests/api/check-params/videos-history.ts | 24 +- server/tests/api/check-params/videos.ts | 36 +- server/tests/api/live/live-save-replay.ts | 2 +- server/tests/api/live/live.ts | 2 +- server/tests/api/moderation/abuses.ts | 8 +- .../tests/api/redundancy/redundancy-constraints.ts | 2 +- server/tests/api/redundancy/redundancy.ts | 6 +- .../search/search-activitypub-video-channels.ts | 8 +- server/tests/api/server/config.ts | 6 +- server/tests/api/server/contact-form.ts | 2 +- server/tests/api/server/email.ts | 2 +- server/tests/api/server/follow-constraints.ts | 50 +-- server/tests/api/server/handle-down.ts | 2 +- server/tests/api/server/homepage.ts | 2 +- server/tests/api/server/no-client.ts | 5 +- server/tests/api/server/plugins.ts | 2 +- server/tests/api/server/reverse-proxy.ts | 2 +- server/tests/api/users/users-multiple-servers.ts | 4 +- server/tests/api/users/users-verification.ts | 2 +- server/tests/api/users/users.ts | 4 +- server/tests/api/videos/multiple-servers.ts | 2 +- server/tests/api/videos/resumable-upload.ts | 2 +- server/tests/api/videos/video-change-ownership.ts | 2 +- server/tests/api/videos/video-channels.ts | 6 +- server/tests/api/videos/video-hls.ts | 2 +- server/tests/api/videos/video-nsfw.ts | 12 +- server/tests/api/videos/video-playlists.ts | 2 +- server/tests/api/videos/video-privacy.ts | 2 +- server/tests/api/videos/video-transcoder.ts | 10 +- server/tests/api/videos/videos-filter.ts | 6 +- server/tests/api/videos/videos-history.ts | 2 +- server/tests/cli/prune-storage.ts | 6 +- server/tests/cli/regenerate-thumbnails.ts | 2 +- server/tests/client.ts | 30 +- server/tests/external-plugins/auth-ldap.ts | 2 +- server/tests/external-plugins/auto-block-videos.ts | 8 +- server/tests/external-plugins/auto-mute.ts | 12 +- server/tests/feeds/feeds.ts | 2 +- server/tests/misc-endpoints.ts | 26 +- server/tests/plugins/external-auth.ts | 20 +- server/tests/plugins/filter-hooks.ts | 10 +- server/tests/plugins/id-and-pass-auth.ts | 2 +- server/tests/plugins/plugin-helpers.ts | 20 +- server/tests/plugins/plugin-router.ts | 14 +- server/tests/plugins/plugin-storage.ts | 4 +- server/tests/plugins/plugin-unloading.ts | 10 +- server/tests/plugins/video-constants.ts | 2 +- server/tools/peertube-redundancy.ts | 2 +- server/typings/express/index.d.ts | 3 +- shared/core-utils/miscs/http-error-codes.ts | 364 --------------------- shared/core-utils/miscs/http-methods.ts | 21 -- shared/core-utils/miscs/index.ts | 2 - shared/extra-utils/bulk/bulk-command.ts | 4 +- .../custom-pages/custom-pages-command.ts | 2 +- shared/extra-utils/feeds/feeds-command.ts | 2 +- shared/extra-utils/logs/logs-command.ts | 2 +- shared/extra-utils/miscs/checks.ts | 4 +- shared/extra-utils/moderation/abuses-command.ts | 2 +- shared/extra-utils/overviews/overviews-command.ts | 2 +- shared/extra-utils/requests/check-api-params.ts | 10 +- shared/extra-utils/requests/requests.ts | 256 ++++++--------- shared/extra-utils/search/search-command.ts | 2 +- shared/extra-utils/server/config-command.ts | 4 +- shared/extra-utils/server/contact-form-command.ts | 2 +- shared/extra-utils/server/debug-command.ts | 2 +- shared/extra-utils/server/follows-command.ts | 2 +- shared/extra-utils/server/jobs-command.ts | 2 +- shared/extra-utils/server/plugins-command.ts | 2 +- shared/extra-utils/server/redundancy-command.ts | 2 +- shared/extra-utils/server/server.ts | 2 +- shared/extra-utils/server/servers-command.ts | 2 +- shared/extra-utils/server/stats-command.ts | 2 +- shared/extra-utils/shared/abstract-command.ts | 66 ++-- shared/extra-utils/users/accounts-command.ts | 2 +- shared/extra-utils/users/blocklist-command.ts | 2 +- shared/extra-utils/users/index.ts | 1 - shared/extra-utils/users/login-command.ts | 10 +- shared/extra-utils/users/notifications-command.ts | 2 +- shared/extra-utils/users/subscriptions-command.ts | 2 +- shared/extra-utils/users/users-command.ts | 2 +- shared/extra-utils/users/users.ts | 20 -- shared/extra-utils/videos/blacklist-command.ts | 2 +- shared/extra-utils/videos/captions-command.ts | 2 +- shared/extra-utils/videos/captions.ts | 2 +- .../extra-utils/videos/change-ownership-command.ts | 2 +- shared/extra-utils/videos/channels-command.ts | 2 +- shared/extra-utils/videos/comments-command.ts | 2 +- shared/extra-utils/videos/history-command.ts | 2 +- shared/extra-utils/videos/imports-command.ts | 2 +- shared/extra-utils/videos/live-command.ts | 2 +- shared/extra-utils/videos/playlists-command.ts | 2 +- shared/extra-utils/videos/services-command.ts | 2 +- .../videos/streaming-playlists-command.ts | 3 +- shared/extra-utils/videos/streaming-playlists.ts | 2 +- shared/extra-utils/videos/videos-command.ts | 36 +- shared/extra-utils/videos/videos.ts | 2 +- shared/models/http/http-error-codes.ts | 364 +++++++++++++++++++++ shared/models/http/http-methods.ts | 21 ++ shared/models/http/index.ts | 2 + shared/models/index.ts | 1 + .../server/peertube-problem-document.model.ts | 2 +- 232 files changed, 1325 insertions(+), 1441 deletions(-) delete mode 100644 shared/core-utils/miscs/http-error-codes.ts delete mode 100644 shared/core-utils/miscs/http-methods.ts delete mode 100644 shared/extra-utils/users/users.ts create mode 100644 shared/models/http/http-error-codes.ts create mode 100644 shared/models/http/http-methods.ts create mode 100644 shared/models/http/index.ts diff --git a/client/src/app/+about/about-instance/contact-admin-modal.component.ts b/client/src/app/+about/about-instance/contact-admin-modal.component.ts index a528faa20..37e9feacb 100644 --- a/client/src/app/+about/about-instance/contact-admin-modal.component.ts +++ b/client/src/app/+about/about-instance/contact-admin-modal.component.ts @@ -11,8 +11,7 @@ import { FormReactive, FormValidatorService } from '@app/shared/shared-forms' import { InstanceService } from '@app/shared/shared-instance' import { NgbModal } from '@ng-bootstrap/ng-bootstrap' import { NgbModalRef } from '@ng-bootstrap/ng-bootstrap/modal/modal-ref' -import { HttpStatusCode } from '@shared/core-utils/miscs/http-error-codes' -import { HTMLServerConfig } from '@shared/models' +import { HTMLServerConfig, HttpStatusCode } from '@shared/models' type Prefill = { subject?: string diff --git a/client/src/app/+accounts/accounts.component.ts b/client/src/app/+accounts/accounts.component.ts index c69b04a01..5b59f3cd0 100644 --- a/client/src/app/+accounts/accounts.component.ts +++ b/client/src/app/+accounts/accounts.component.ts @@ -13,8 +13,7 @@ import { VideoService } from '@app/shared/shared-main' import { AccountReportComponent } from '@app/shared/shared-moderation' -import { HttpStatusCode } from '@shared/core-utils/miscs/http-error-codes' -import { User, UserRight } from '@shared/models' +import { HttpStatusCode, User, UserRight } from '@shared/models' import { AccountSearchComponent } from './account-search/account-search.component' @Component({ diff --git a/client/src/app/+my-library/+my-video-channels/my-video-channel-create.component.ts b/client/src/app/+my-library/+my-video-channels/my-video-channel-create.component.ts index b3265210f..433475f66 100644 --- a/client/src/app/+my-library/+my-video-channels/my-video-channel-create.component.ts +++ b/client/src/app/+my-library/+my-video-channels/my-video-channel-create.component.ts @@ -1,3 +1,5 @@ +import { of } from 'rxjs' +import { switchMap } from 'rxjs/operators' import { Component, OnInit } from '@angular/core' import { Router } from '@angular/router' import { AuthService, Notifier } from '@app/core' @@ -9,11 +11,8 @@ import { } from '@app/shared/form-validators/video-channel-validators' import { FormValidatorService } from '@app/shared/shared-forms' import { VideoChannel, VideoChannelService } from '@app/shared/shared-main' -import { VideoChannelCreate } from '@shared/models' -import { HttpStatusCode } from '@shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode, VideoChannelCreate } from '@shared/models' import { MyVideoChannelEdit } from './my-video-channel-edit' -import { switchMap } from 'rxjs/operators' -import { of } from 'rxjs' @Component({ templateUrl: './my-video-channel-edit.component.html', diff --git a/client/src/app/+page-not-found/page-not-found.component.ts b/client/src/app/+page-not-found/page-not-found.component.ts index 639e5db78..10645a634 100644 --- a/client/src/app/+page-not-found/page-not-found.component.ts +++ b/client/src/app/+page-not-found/page-not-found.component.ts @@ -1,7 +1,8 @@ import { Component, OnInit } from '@angular/core' import { Title } from '@angular/platform-browser' import { Router } from '@angular/router' -import { HttpStatusCode } from '@shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '@shared/models' + @Component({ selector: 'my-page-not-found', templateUrl: './page-not-found.component.html', diff --git a/client/src/app/+video-channels/video-channels.component.ts b/client/src/app/+video-channels/video-channels.component.ts index 3833d9c54..6479644f1 100644 --- a/client/src/app/+video-channels/video-channels.component.ts +++ b/client/src/app/+video-channels/video-channels.component.ts @@ -7,7 +7,7 @@ import { AuthService, MarkdownService, Notifier, RestExtractor, ScreenService } import { ListOverflowItem, VideoChannel, VideoChannelService, VideoService } from '@app/shared/shared-main' import { SupportModalComponent } from '@app/shared/shared-support-modal' import { SubscribeButtonComponent } from '@app/shared/shared-user-subscription' -import { HttpStatusCode } from '@shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '@shared/models' @Component({ templateUrl: './video-channels.component.html', diff --git a/client/src/app/+videos/+video-edit/video-add-components/video-upload.component.ts b/client/src/app/+videos/+video-edit/video-add-components/video-upload.component.ts index 627de33c0..e9420fe62 100644 --- a/client/src/app/+videos/+video-edit/video-add-components/video-upload.component.ts +++ b/client/src/app/+videos/+video-edit/video-add-components/video-upload.component.ts @@ -7,8 +7,7 @@ import { genericUploadErrorHandler, scrollToTop } from '@app/helpers' import { FormValidatorService } from '@app/shared/shared-forms' import { BytesPipe, Video, VideoCaptionService, VideoEdit, VideoService } from '@app/shared/shared-main' import { LoadingBarService } from '@ngx-loading-bar/core' -import { HttpStatusCode } from '@shared/core-utils/miscs/http-error-codes' -import { VideoPrivacy } from '@shared/models' +import { HttpStatusCode, VideoPrivacy } from '@shared/models' import { UploaderXFormData } from './uploaderx-form-data' import { VideoSend } from './video-send' diff --git a/client/src/app/+videos/+video-watch/video-watch.component.ts b/client/src/app/+videos/+video-watch/video-watch.component.ts index d078844c3..7460ae3fc 100644 --- a/client/src/app/+videos/+video-watch/video-watch.component.ts +++ b/client/src/app/+videos/+video-watch/video-watch.component.ts @@ -21,8 +21,15 @@ import { isXPercentInViewport, scrollToTop } from '@app/helpers' import { Video, VideoCaptionService, VideoDetails, VideoService } from '@app/shared/shared-main' import { SubscribeButtonComponent } from '@app/shared/shared-user-subscription' import { VideoPlaylist, VideoPlaylistService } from '@app/shared/shared-video-playlist' -import { HttpStatusCode } from '@shared/core-utils/miscs/http-error-codes' -import { HTMLServerConfig, PeerTubeProblemDocument, ServerErrorCode, VideoCaption, VideoPrivacy, VideoState } from '@shared/models' +import { + HTMLServerConfig, + HttpStatusCode, + PeerTubeProblemDocument, + ServerErrorCode, + VideoCaption, + VideoPrivacy, + VideoState +} from '@shared/models' import { cleanupVideoWatch, getStoredTheater, getStoredVideoWatchHistory } from '../../../assets/player/peertube-player-local-storage' import { CustomizationOptions, diff --git a/client/src/app/core/auth/auth.service.ts b/client/src/app/core/auth/auth.service.ts index cdf13186b..60bd72c60 100644 --- a/client/src/app/core/auth/auth.service.ts +++ b/client/src/app/core/auth/auth.service.ts @@ -6,12 +6,11 @@ import { Injectable } from '@angular/core' import { Router } from '@angular/router' import { Notifier } from '@app/core/notification/notifier.service' import { objectToUrlEncoded, peertubeLocalStorage } from '@root-helpers/index' -import { MyUser as UserServerModel, OAuthClientLocal, User, UserLogin, UserRefreshToken } from '@shared/models' +import { HttpStatusCode, MyUser as UserServerModel, OAuthClientLocal, User, UserLogin, UserRefreshToken } from '@shared/models' import { environment } from '../../../environments/environment' import { RestExtractor } from '../rest/rest-extractor.service' import { AuthStatus } from './auth-status.model' import { AuthUser } from './auth-user.model' -import { HttpStatusCode } from '@shared/core-utils/miscs/http-error-codes' interface UserLoginWithUsername extends UserLogin { access_token: string diff --git a/client/src/app/core/rest/rest-extractor.service.ts b/client/src/app/core/rest/rest-extractor.service.ts index 08ab49512..2a926e68f 100644 --- a/client/src/app/core/rest/rest-extractor.service.ts +++ b/client/src/app/core/rest/rest-extractor.service.ts @@ -2,8 +2,7 @@ import { throwError as observableThrowError } from 'rxjs' import { Injectable } from '@angular/core' import { Router } from '@angular/router' import { dateToHuman } from '@app/helpers' -import { ResultList } from '@shared/models' -import { HttpStatusCode } from '@shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode, ResultList } from '@shared/models' @Injectable() export class RestExtractor { diff --git a/client/src/app/helpers/utils.ts b/client/src/app/helpers/utils.ts index 94f6def26..edcaf50e0 100644 --- a/client/src/app/helpers/utils.ts +++ b/client/src/app/helpers/utils.ts @@ -3,7 +3,7 @@ import { SelectChannelItem } from 'src/types/select-options-item.model' import { DatePipe } from '@angular/common' import { HttpErrorResponse } from '@angular/common/http' import { Notifier } from '@app/core' -import { HttpStatusCode } from '@shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '@shared/models' import { environment } from '../../environments/environment' import { AuthService } from '../core/auth' diff --git a/client/src/app/shared/shared-main/auth/auth-interceptor.service.ts b/client/src/app/shared/shared-main/auth/auth-interceptor.service.ts index 5bcad36d0..a75c8a25c 100644 --- a/client/src/app/shared/shared-main/auth/auth-interceptor.service.ts +++ b/client/src/app/shared/shared-main/auth/auth-interceptor.service.ts @@ -1,11 +1,11 @@ import { Observable, of, throwError as observableThrowError } from 'rxjs' import { catchError, switchMap } from 'rxjs/operators' -import { HTTP_INTERCEPTORS, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpErrorResponse } from '@angular/common/http' +import { HTTP_INTERCEPTORS, HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http' import { Injectable, Injector } from '@angular/core' -import { AuthService } from '@app/core/auth/auth.service' import { Router } from '@angular/router' -import { HttpStatusCode } from '@shared/core-utils/miscs/http-error-codes' -import { OAuth2ErrorCode, PeerTubeProblemDocument, ServerErrorCode } from '@shared/models/server' +import { AuthService } from '@app/core/auth/auth.service' +import { HttpStatusCode } from '@shared/models' +import { OAuth2ErrorCode, PeerTubeProblemDocument } from '@shared/models/server' @Injectable() export class AuthInterceptor implements HttpInterceptor { diff --git a/client/src/standalone/videos/embed.ts b/client/src/standalone/videos/embed.ts index e59d8b940..97437ce45 100644 --- a/client/src/standalone/videos/embed.ts +++ b/client/src/standalone/videos/embed.ts @@ -1,9 +1,9 @@ import './embed.scss' import videojs from 'video.js' import { peertubeTranslate } from '../../../../shared/core-utils/i18n' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' import { HTMLServerConfig, + HttpStatusCode, OAuth2ErrorCode, ResultList, UserRefreshToken, diff --git a/server.ts b/server.ts index e46300dce..582321a5b 100644 --- a/server.ts +++ b/server.ts @@ -125,7 +125,7 @@ import { PeerTubeVersionCheckScheduler } from './server/lib/schedulers/peertube- import { Hooks } from './server/lib/plugins/hooks' import { PluginManager } from './server/lib/plugins/plugin-manager' import { LiveManager } from './server/lib/live' -import { HttpStatusCode } from './shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from './shared/models/http/http-error-codes' import { VideosTorrentCache } from '@server/lib/files-cache/videos-torrent-cache' import { ServerConfigManager } from '@server/lib/server-config-manager' diff --git a/server/controllers/activitypub/inbox.ts b/server/controllers/activitypub/inbox.ts index 14f301ab7..30662990a 100644 --- a/server/controllers/activitypub/inbox.ts +++ b/server/controllers/activitypub/inbox.ts @@ -1,7 +1,7 @@ import * as express from 'express' import { InboxManager } from '@server/lib/activitypub/inbox-manager' import { Activity, ActivityPubCollection, ActivityPubOrderedCollection, RootActivity } from '../../../shared' -import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '../../../shared/models/http/http-error-codes' import { isActivityValid } from '../../helpers/custom-validators/activitypub/activity' import { logger } from '../../helpers/logger' import { asyncMiddleware, checkSignature, localAccountValidator, localVideoChannelValidator, signatureValidator } from '../../middlewares' diff --git a/server/controllers/api/abuse.ts b/server/controllers/api/abuse.ts index ba5b94840..e851365e9 100644 --- a/server/controllers/api/abuse.ts +++ b/server/controllers/api/abuse.ts @@ -6,7 +6,7 @@ import { AbuseModel } from '@server/models/abuse/abuse' import { AbuseMessageModel } from '@server/models/abuse/abuse-message' import { getServerActor } from '@server/models/application/application' import { abusePredefinedReasonsMap } from '@shared/core-utils/abuse' -import { HttpStatusCode } from '@shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '@shared/models' import { AbuseCreate, AbuseState, UserRight } from '../../../shared' import { getFormattedObjects } from '../../helpers/utils' import { sequelizeTypescript } from '../../initializers/database' diff --git a/server/controllers/api/bulk.ts b/server/controllers/api/bulk.ts index 192daccde..10d83571d 100644 --- a/server/controllers/api/bulk.ts +++ b/server/controllers/api/bulk.ts @@ -4,7 +4,7 @@ import { bulkRemoveCommentsOfValidator } from '@server/middlewares/validators/bu import { VideoCommentModel } from '@server/models/video/video-comment' import { removeComment } from '@server/lib/video-comment' import { BulkRemoveCommentsOfBody } from '@shared/models/bulk/bulk-remove-comments-of-body.model' -import { HttpStatusCode } from '@shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '@shared/models' const bulkRouter = express.Router() diff --git a/server/controllers/api/custom-page.ts b/server/controllers/api/custom-page.ts index c19f03c56..cc1aa8427 100644 --- a/server/controllers/api/custom-page.ts +++ b/server/controllers/api/custom-page.ts @@ -1,7 +1,7 @@ import * as express from 'express' import { ServerConfigManager } from '@server/lib/server-config-manager' import { ActorCustomPageModel } from '@server/models/account/actor-custom-page' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { UserRight } from '@shared/models' import { asyncMiddleware, authenticate, ensureUserHasRight } from '../../middlewares' diff --git a/server/controllers/api/index.ts b/server/controllers/api/index.ts index 28378654a..93b14dadb 100644 --- a/server/controllers/api/index.ts +++ b/server/controllers/api/index.ts @@ -1,7 +1,7 @@ import * as cors from 'cors' import * as express from 'express' import * as RateLimit from 'express-rate-limit' -import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '../../../shared/models' import { badRequest } from '../../helpers/express-utils' import { CONFIG } from '../../initializers/config' import { abuseRouter } from './abuse' diff --git a/server/controllers/api/oauth-clients.ts b/server/controllers/api/oauth-clients.ts index 15bbf5c4d..f95f06864 100644 --- a/server/controllers/api/oauth-clients.ts +++ b/server/controllers/api/oauth-clients.ts @@ -1,6 +1,6 @@ import * as express from 'express' import { OAuthClientLocal } from '../../../shared' -import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '../../../shared/models/http/http-error-codes' import { logger } from '../../helpers/logger' import { CONFIG } from '../../initializers/config' import { asyncMiddleware, openapiOperationDoc } from '../../middlewares' diff --git a/server/controllers/api/plugins.ts b/server/controllers/api/plugins.ts index 1e6a02c49..4b213c246 100644 --- a/server/controllers/api/plugins.ts +++ b/server/controllers/api/plugins.ts @@ -23,7 +23,7 @@ import { updatePluginSettingsValidator } from '@server/middlewares/validators/plugins' import { PluginModel } from '@server/models/server/plugin' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { InstallOrUpdatePlugin, ManagePlugin, diff --git a/server/controllers/api/search/search-video-channels.ts b/server/controllers/api/search/search-video-channels.ts index 16beeed60..fe9178e69 100644 --- a/server/controllers/api/search/search-video-channels.ts +++ b/server/controllers/api/search/search-video-channels.ts @@ -6,7 +6,7 @@ import { WEBSERVER } from '@server/initializers/constants' import { Hooks } from '@server/lib/plugins/hooks' import { buildMutedForSearchIndex, isSearchIndexSearch, isURISearch } from '@server/lib/search' import { getServerActor } from '@server/models/application/application' -import { HttpStatusCode } from '@shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '@shared/models' import { ResultList, VideoChannel } from '@shared/models' import { VideoChannelsSearchQuery } from '../../../../shared/models/search' import { isUserAbleToSearchRemoteURI } from '../../../helpers/express-utils' diff --git a/server/controllers/api/search/search-video-playlists.ts b/server/controllers/api/search/search-video-playlists.ts index b231ff1e2..a0e2c1747 100644 --- a/server/controllers/api/search/search-video-playlists.ts +++ b/server/controllers/api/search/search-video-playlists.ts @@ -11,7 +11,7 @@ import { buildMutedForSearchIndex, isSearchIndexSearch, isURISearch } from '@ser import { getServerActor } from '@server/models/application/application' import { VideoPlaylistModel } from '@server/models/video/video-playlist' import { MVideoPlaylistFullSummary } from '@server/types/models' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { ResultList, VideoPlaylist, VideoPlaylistsSearchQuery } from '@shared/models' import { asyncMiddleware, diff --git a/server/controllers/api/search/search-videos.ts b/server/controllers/api/search/search-videos.ts index b626baa28..0e6fd9c72 100644 --- a/server/controllers/api/search/search-videos.ts +++ b/server/controllers/api/search/search-videos.ts @@ -6,7 +6,7 @@ import { WEBSERVER } from '@server/initializers/constants' import { getOrCreateAPVideo } from '@server/lib/activitypub/videos' import { Hooks } from '@server/lib/plugins/hooks' import { buildMutedForSearchIndex, isSearchIndexSearch, isURISearch } from '@server/lib/search' -import { HttpStatusCode } from '@shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '@shared/models' import { ResultList, Video } from '@shared/models' import { VideosSearchQuery } from '../../../../shared/models/search' import { buildNSFWFilter, isUserAbleToSearchRemoteURI } from '../../../helpers/express-utils' diff --git a/server/controllers/api/server/contact.ts b/server/controllers/api/server/contact.ts index caddc0909..ae36dd599 100644 --- a/server/controllers/api/server/contact.ts +++ b/server/controllers/api/server/contact.ts @@ -3,7 +3,7 @@ import { asyncMiddleware, contactAdministratorValidator } from '../../../middlew import { Redis } from '../../../lib/redis' import { Emailer } from '../../../lib/emailer' import { ContactForm } from '../../../../shared/models/server' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '../../../../shared/models/http/http-error-codes' const contactRouter = express.Router() @@ -15,7 +15,7 @@ contactRouter.post('/contact', async function contactAdministrator (req: express.Request, res: express.Response) { const data = req.body as ContactForm - await Emailer.Instance.addContactFormJob(data.fromEmail, data.fromName, data.subject, data.body) + Emailer.Instance.addContactFormJob(data.fromEmail, data.fromName, data.subject, data.body) await Redis.Instance.setContactFormIp(req.ip) diff --git a/server/controllers/api/server/debug.ts b/server/controllers/api/server/debug.ts index 31888e963..0601b89ce 100644 --- a/server/controllers/api/server/debug.ts +++ b/server/controllers/api/server/debug.ts @@ -2,7 +2,7 @@ import * as express from 'express' import { InboxManager } from '@server/lib/activitypub/inbox-manager' import { RemoveDanglingResumableUploadsScheduler } from '@server/lib/schedulers/remove-dangling-resumable-uploads-scheduler' import { Debug, SendDebugCommand } from '@shared/models' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '../../../../shared/models/http/http-error-codes' import { UserRight } from '../../../../shared/models/users' import { authenticate, ensureUserHasRight } from '../../../middlewares' diff --git a/server/controllers/api/server/follows.ts b/server/controllers/api/server/follows.ts index 12357a2ca..e6f4f6b92 100644 --- a/server/controllers/api/server/follows.ts +++ b/server/controllers/api/server/follows.ts @@ -1,6 +1,6 @@ import * as express from 'express' import { getServerActor } from '@server/models/application/application' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '../../../../shared/models/http/http-error-codes' import { UserRight } from '../../../../shared/models/users' import { logger } from '../../../helpers/logger' import { getFormattedObjects } from '../../../helpers/utils' diff --git a/server/controllers/api/server/redundancy.ts b/server/controllers/api/server/redundancy.ts index bc593ad43..99d1c762b 100644 --- a/server/controllers/api/server/redundancy.ts +++ b/server/controllers/api/server/redundancy.ts @@ -1,5 +1,10 @@ import * as express from 'express' +import { JobQueue } from '@server/lib/job-queue' +import { VideoRedundancyModel } from '@server/models/redundancy/video-redundancy' +import { HttpStatusCode } from '../../../../shared/models/http/http-error-codes' import { UserRight } from '../../../../shared/models/users' +import { logger } from '../../../helpers/logger' +import { removeRedundanciesOfServer, removeVideoRedundancy } from '../../../lib/redundancy' import { asyncMiddleware, authenticate, @@ -10,16 +15,11 @@ import { videoRedundanciesSortValidator } from '../../../middlewares' import { - listVideoRedundanciesValidator, - updateServerRedundancyValidator, addVideoRedundancyValidator, - removeVideoRedundancyValidator + listVideoRedundanciesValidator, + removeVideoRedundancyValidator, + updateServerRedundancyValidator } from '../../../middlewares/validators/redundancy' -import { removeRedundanciesOfServer, removeVideoRedundancy } from '../../../lib/redundancy' -import { logger } from '../../../helpers/logger' -import { VideoRedundancyModel } from '@server/models/redundancy/video-redundancy' -import { JobQueue } from '@server/lib/job-queue' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' const serverRedundancyRouter = express.Router() diff --git a/server/controllers/api/server/server-blocklist.ts b/server/controllers/api/server/server-blocklist.ts index a86bc7d19..b3ee50d85 100644 --- a/server/controllers/api/server/server-blocklist.ts +++ b/server/controllers/api/server/server-blocklist.ts @@ -1,8 +1,9 @@ import 'multer' import * as express from 'express' import { logger } from '@server/helpers/logger' -import { UserNotificationModel } from '@server/models/user/user-notification' import { getServerActor } from '@server/models/application/application' +import { UserNotificationModel } from '@server/models/user/user-notification' +import { HttpStatusCode } from '../../../../shared/models/http/http-error-codes' import { UserRight } from '../../../../shared/models/users' import { getFormattedObjects } from '../../../helpers/utils' import { addAccountInBlocklist, addServerInBlocklist, removeAccountFromBlocklist, removeServerFromBlocklist } from '../../../lib/blocklist' @@ -25,7 +26,6 @@ import { } from '../../../middlewares/validators' import { AccountBlocklistModel } from '../../../models/account/account-blocklist' import { ServerBlocklistModel } from '../../../models/server/server-blocklist' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' const serverBlocklistRouter = express.Router() diff --git a/server/controllers/api/users/index.ts b/server/controllers/api/users/index.ts index b86fc94ef..be800e8b5 100644 --- a/server/controllers/api/users/index.ts +++ b/server/controllers/api/users/index.ts @@ -5,7 +5,7 @@ import { Hooks } from '@server/lib/plugins/hooks' import { OAuthTokenModel } from '@server/models/oauth/oauth-token' import { MUser, MUserAccountDefault } from '@server/types/models' import { UserCreate, UserCreateResult, UserRight, UserRole, UserUpdate } from '../../../../shared' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '../../../../shared/models/http/http-error-codes' import { UserAdminFlag } from '../../../../shared/models/users/user-flag.model' import { UserRegister } from '../../../../shared/models/users/user-register.model' import { auditLoggerFactory, getAuditIdFromRes, UserAuditView } from '../../../helpers/audit-logger' diff --git a/server/controllers/api/users/me.ts b/server/controllers/api/users/me.ts index 1f2b2f9dd..c9610c59f 100644 --- a/server/controllers/api/users/me.ts +++ b/server/controllers/api/users/me.ts @@ -3,7 +3,7 @@ import * as express from 'express' import { auditLoggerFactory, getAuditIdFromRes, UserAuditView } from '@server/helpers/audit-logger' import { Hooks } from '@server/lib/plugins/hooks' import { ActorImageType, UserUpdateMe, UserVideoRate as FormattedUserVideoRate } from '../../../../shared' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '../../../../shared/models/http/http-error-codes' import { UserVideoQuota } from '../../../../shared/models/users/user-video-quota.model' import { createReqFiles } from '../../../helpers/express-utils' import { getFormattedObjects } from '../../../helpers/utils' diff --git a/server/controllers/api/users/my-blocklist.ts b/server/controllers/api/users/my-blocklist.ts index a1561b751..fe11b6e77 100644 --- a/server/controllers/api/users/my-blocklist.ts +++ b/server/controllers/api/users/my-blocklist.ts @@ -22,7 +22,7 @@ import { addAccountInBlocklist, addServerInBlocklist, removeAccountFromBlocklist import { ServerBlocklistModel } from '../../../models/server/server-blocklist' import { UserNotificationModel } from '@server/models/user/user-notification' import { logger } from '@server/helpers/logger' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '../../../../shared/models/http/http-error-codes' const myBlocklistRouter = express.Router() diff --git a/server/controllers/api/users/my-history.ts b/server/controllers/api/users/my-history.ts index cff1697ab..85e04925e 100644 --- a/server/controllers/api/users/my-history.ts +++ b/server/controllers/api/users/my-history.ts @@ -11,7 +11,7 @@ import { import { getFormattedObjects } from '../../../helpers/utils' import { UserVideoHistoryModel } from '../../../models/user/user-video-history' import { sequelizeTypescript } from '../../../initializers/database' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '../../../../shared/models/http/http-error-codes' const myVideosHistoryRouter = express.Router() diff --git a/server/controllers/api/users/my-notifications.ts b/server/controllers/api/users/my-notifications.ts index 2909770da..3beee07c0 100644 --- a/server/controllers/api/users/my-notifications.ts +++ b/server/controllers/api/users/my-notifications.ts @@ -1,7 +1,7 @@ import 'multer' import * as express from 'express' import { UserNotificationModel } from '@server/models/user/user-notification' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '../../../../shared/models/http/http-error-codes' import { UserNotificationSetting } from '../../../../shared/models/users' import { getFormattedObjects } from '../../../helpers/utils' import { diff --git a/server/controllers/api/users/my-subscriptions.ts b/server/controllers/api/users/my-subscriptions.ts index 46a73d49e..84f519926 100644 --- a/server/controllers/api/users/my-subscriptions.ts +++ b/server/controllers/api/users/my-subscriptions.ts @@ -3,7 +3,7 @@ import * as express from 'express' import { sendUndoFollow } from '@server/lib/activitypub/send' import { VideoChannelModel } from '@server/models/video/video-channel' import { VideosCommonQuery } from '@shared/models' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '../../../../shared/models/http/http-error-codes' import { buildNSFWFilter, getCountVideos } from '../../../helpers/express-utils' import { getFormattedObjects } from '../../../helpers/utils' import { WEBSERVER } from '../../../initializers/constants' diff --git a/server/controllers/api/video-channel.ts b/server/controllers/api/video-channel.ts index bc8d203b0..784f97b1e 100644 --- a/server/controllers/api/video-channel.ts +++ b/server/controllers/api/video-channel.ts @@ -3,7 +3,7 @@ import { Hooks } from '@server/lib/plugins/hooks' import { getServerActor } from '@server/models/application/application' import { MChannelBannerAccountDefault } from '@server/types/models' import { ActorImageType, VideoChannelCreate, VideoChannelUpdate, VideosCommonQuery } from '../../../shared' -import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '../../../shared/models/http/http-error-codes' import { auditLoggerFactory, getAuditIdFromRes, VideoChannelAuditView } from '../../helpers/audit-logger' import { resetSequelizeInstance } from '../../helpers/database-utils' import { buildNSFWFilter, createReqFiles, getCountVideos, isUserAbleToSearchRemoteURI } from '../../helpers/express-utils' diff --git a/server/controllers/api/video-playlist.ts b/server/controllers/api/video-playlist.ts index 78cbd9cff..4971d0a77 100644 --- a/server/controllers/api/video-playlist.ts +++ b/server/controllers/api/video-playlist.ts @@ -6,7 +6,7 @@ import { Hooks } from '@server/lib/plugins/hooks' import { getServerActor } from '@server/models/application/application' import { MVideoPlaylistFull, MVideoPlaylistThumbnail, MVideoThumbnail } from '@server/types/models' import { VideoPlaylistCreateResult, VideoPlaylistElementCreateResult } from '@shared/models' -import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '../../../shared/models/http/http-error-codes' import { VideoPlaylistCreate } from '../../../shared/models/videos/playlist/video-playlist-create.model' import { VideoPlaylistElementCreate } from '../../../shared/models/videos/playlist/video-playlist-element-create.model' import { VideoPlaylistElementUpdate } from '../../../shared/models/videos/playlist/video-playlist-element-update.model' diff --git a/server/controllers/api/videos/blacklist.ts b/server/controllers/api/videos/blacklist.ts index 530e17965..a7f5f53d8 100644 --- a/server/controllers/api/videos/blacklist.ts +++ b/server/controllers/api/videos/blacklist.ts @@ -19,7 +19,7 @@ import { videosBlacklistUpdateValidator } from '../../../middlewares' import { VideoBlacklistModel } from '../../../models/video/video-blacklist' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '../../../../shared/models/http/http-error-codes' const blacklistRouter = express.Router() diff --git a/server/controllers/api/videos/captions.ts b/server/controllers/api/videos/captions.ts index ad7423a31..4008de60f 100644 --- a/server/controllers/api/videos/captions.ts +++ b/server/controllers/api/videos/captions.ts @@ -1,6 +1,6 @@ import * as express from 'express' import { MVideoCaption } from '@server/types/models' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '../../../../shared/models/http/http-error-codes' import { moveAndProcessCaptionFile } from '../../../helpers/captions-utils' import { createReqFiles } from '../../../helpers/express-utils' import { logger } from '../../../helpers/logger' diff --git a/server/controllers/api/videos/comment.ts b/server/controllers/api/videos/comment.ts index 6a25511e5..90b633bb5 100644 --- a/server/controllers/api/videos/comment.ts +++ b/server/controllers/api/videos/comment.ts @@ -1,5 +1,5 @@ import * as express from 'express' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '../../../../shared/models/http/http-error-codes' import { ResultList, ThreadsResultList, UserRight, VideoCommentCreate } from '../../../../shared/models' import { VideoCommentThreads } from '../../../../shared/models/videos/comment/video-comment.model' import { auditLoggerFactory, CommentAuditView, getAuditIdFromRes } from '../../../helpers/audit-logger' diff --git a/server/controllers/api/videos/index.ts b/server/controllers/api/videos/index.ts index 74b100e59..5a2ff81dc 100644 --- a/server/controllers/api/videos/index.ts +++ b/server/controllers/api/videos/index.ts @@ -6,7 +6,7 @@ import { openapiOperationDoc } from '@server/middlewares/doc' import { getServerActor } from '@server/models/application/application' import { MVideoAccountLight } from '@server/types/models' import { VideosCommonQuery } from '../../../../shared' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs' +import { HttpStatusCode } from '../../../../shared/models' import { auditLoggerFactory, getAuditIdFromRes, VideoAuditView } from '../../../helpers/audit-logger' import { buildNSFWFilter, getCountVideos } from '../../../helpers/express-utils' import { logger } from '../../../helpers/logger' diff --git a/server/controllers/api/videos/live.ts b/server/controllers/api/videos/live.ts index d8c51c2d4..ed4da8f47 100644 --- a/server/controllers/api/videos/live.ts +++ b/server/controllers/api/videos/live.ts @@ -11,7 +11,7 @@ import { videoLiveAddValidator, videoLiveGetValidator, videoLiveUpdateValidator import { VideoLiveModel } from '@server/models/video/video-live' import { MVideoDetails, MVideoFullLight } from '@server/types/models' import { LiveVideoCreate, LiveVideoUpdate, VideoState } from '../../../../shared' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '../../../../shared/models/http/http-error-codes' import { logger } from '../../../helpers/logger' import { sequelizeTypescript } from '../../../initializers/database' import { updateVideoMiniatureFromExisting } from '../../../lib/thumbnail' diff --git a/server/controllers/api/videos/ownership.ts b/server/controllers/api/videos/ownership.ts index 1bb96e046..e6c94a45a 100644 --- a/server/controllers/api/videos/ownership.ts +++ b/server/controllers/api/videos/ownership.ts @@ -19,7 +19,7 @@ import { changeVideoChannelShare } from '../../../lib/activitypub/share' import { sendUpdateVideo } from '../../../lib/activitypub/send' import { VideoModel } from '../../../models/video/video' import { MVideoFullLight } from '@server/types/models' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '../../../../shared/models/http/http-error-codes' const ownershipVideoRouter = express.Router() diff --git a/server/controllers/api/videos/rate.ts b/server/controllers/api/videos/rate.ts index 84f42633e..134c9e5ca 100644 --- a/server/controllers/api/videos/rate.ts +++ b/server/controllers/api/videos/rate.ts @@ -7,7 +7,7 @@ import { asyncMiddleware, asyncRetryTransactionMiddleware, authenticate, videoUp import { AccountModel } from '../../../models/account/account' import { AccountVideoRateModel } from '../../../models/account/account-video-rate' import { sequelizeTypescript } from '../../../initializers/database' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '../../../../shared/models/http/http-error-codes' const rateVideoRouter = express.Router() diff --git a/server/controllers/api/videos/update.ts b/server/controllers/api/videos/update.ts index 8affe71c6..49639060b 100644 --- a/server/controllers/api/videos/update.ts +++ b/server/controllers/api/videos/update.ts @@ -2,10 +2,11 @@ import * as express from 'express' import { Transaction } from 'sequelize/types' import { changeVideoChannelShare } from '@server/lib/activitypub/share' import { buildVideoThumbnailsFromReq, setVideoTags } from '@server/lib/video' +import { openapiOperationDoc } from '@server/middlewares/doc' import { FilteredModelAttributes } from '@server/types' import { MVideoFullLight } from '@server/types/models' import { VideoUpdate } from '../../../../shared' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs' +import { HttpStatusCode } from '../../../../shared/models' import { auditLoggerFactory, getAuditIdFromRes, VideoAuditView } from '../../../helpers/audit-logger' import { resetSequelizeInstance } from '../../../helpers/database-utils' import { createReqFiles } from '../../../helpers/express-utils' @@ -20,7 +21,6 @@ import { autoBlacklistVideoIfNeeded } from '../../../lib/video-blacklist' import { asyncMiddleware, asyncRetryTransactionMiddleware, authenticate, videosUpdateValidator } from '../../../middlewares' import { ScheduleVideoUpdateModel } from '../../../models/video/schedule-video-update' import { VideoModel } from '../../../models/video/video' -import { openapiOperationDoc } from '@server/middlewares/doc' const lTags = loggerTagsFactory('api', 'video') const auditLogger = auditLoggerFactory('videos') diff --git a/server/controllers/api/videos/upload.ts b/server/controllers/api/videos/upload.ts index bcd21ac99..1603ef127 100644 --- a/server/controllers/api/videos/upload.ts +++ b/server/controllers/api/videos/upload.ts @@ -11,7 +11,7 @@ import { openapiOperationDoc } from '@server/middlewares/doc' import { MVideo, MVideoFile, MVideoFullLight } from '@server/types/models' import { uploadx } from '@uploadx/core' import { VideoCreate, VideoState } from '../../../../shared' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs' +import { HttpStatusCode } from '../../../../shared/models' import { auditLoggerFactory, getAuditIdFromRes, VideoAuditView } from '../../../helpers/audit-logger' import { retryTransactionWrapper } from '../../../helpers/database-utils' import { createReqFiles } from '../../../helpers/express-utils' diff --git a/server/controllers/api/videos/watching.ts b/server/controllers/api/videos/watching.ts index 8b15525aa..2899dbd9c 100644 --- a/server/controllers/api/videos/watching.ts +++ b/server/controllers/api/videos/watching.ts @@ -8,7 +8,7 @@ import { videoWatchingValidator } from '../../../middlewares' import { UserVideoHistoryModel } from '../../../models/user/user-video-history' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '../../../../shared/models/http/http-error-codes' const watchingRouter = express.Router() diff --git a/server/controllers/client.ts b/server/controllers/client.ts index eb1ee6cbd..ba3c54440 100644 --- a/server/controllers/client.ts +++ b/server/controllers/client.ts @@ -5,7 +5,7 @@ import { join } from 'path' import { logger } from '@server/helpers/logger' import { CONFIG } from '@server/initializers/config' import { Hooks } from '@server/lib/plugins/hooks' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { buildFileLocale, getCompleteLocale, is18nLocale, LOCALE_FILES } from '@shared/core-utils/i18n' import { root } from '../helpers/core-utils' import { STATIC_MAX_AGE } from '../initializers/constants' diff --git a/server/controllers/download.ts b/server/controllers/download.ts index 4293a32e2..13bc66900 100644 --- a/server/controllers/download.ts +++ b/server/controllers/download.ts @@ -5,7 +5,7 @@ import { VideosTorrentCache } from '@server/lib/files-cache/videos-torrent-cache import { Hooks } from '@server/lib/plugins/hooks' import { getVideoFilePath } from '@server/lib/video-paths' import { MStreamingPlaylist, MVideo, MVideoFile, MVideoFullLight } from '@server/types/models' -import { HttpStatusCode } from '@shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '@shared/models' import { VideoStreamingPlaylistType } from '@shared/models' import { STATIC_DOWNLOAD_PATHS } from '../initializers/constants' import { asyncMiddleware, videosDownloadValidator } from '../middlewares' diff --git a/server/controllers/lazy-static.ts b/server/controllers/lazy-static.ts index 9a7dacba0..632e4dcd8 100644 --- a/server/controllers/lazy-static.ts +++ b/server/controllers/lazy-static.ts @@ -1,7 +1,7 @@ import * as cors from 'cors' import * as express from 'express' import { VideosTorrentCache } from '@server/lib/files-cache/videos-torrent-cache' -import { HttpStatusCode } from '../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '../../shared/models/http/http-error-codes' import { logger } from '../helpers/logger' import { LAZY_STATIC_PATHS, STATIC_MAX_AGE } from '../initializers/constants' import { VideosCaptionCache, VideosPreviewCache } from '../lib/files-cache' diff --git a/server/controllers/live.ts b/server/controllers/live.ts index f2686fb23..95d5c0135 100644 --- a/server/controllers/live.ts +++ b/server/controllers/live.ts @@ -2,7 +2,7 @@ import * as cors from 'cors' import * as express from 'express' import { mapToJSON } from '@server/helpers/core-utils' import { LiveSegmentShaStore } from '@server/lib/live' -import { HttpStatusCode } from '@shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '@shared/models' const liveRouter = express.Router() diff --git a/server/controllers/plugins.ts b/server/controllers/plugins.ts index 7213e3f15..11ab3f10a 100644 --- a/server/controllers/plugins.ts +++ b/server/controllers/plugins.ts @@ -3,7 +3,7 @@ import { join } from 'path' import { logger } from '@server/helpers/logger' import { optionalAuthenticate } from '@server/middlewares/auth' import { getCompleteLocale, is18nLocale } from '../../shared/core-utils/i18n' -import { HttpStatusCode } from '../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '../../shared/models/http/http-error-codes' import { PluginType } from '../../shared/models/plugins/plugin.type' import { isTestInstance } from '../helpers/core-utils' import { PLUGIN_GLOBAL_CSS_PATH } from '../initializers/constants' diff --git a/server/controllers/static.ts b/server/controllers/static.ts index 35e024dda..5900eaff3 100644 --- a/server/controllers/static.ts +++ b/server/controllers/static.ts @@ -3,7 +3,7 @@ import * as express from 'express' import { join } from 'path' import { serveIndexHTML } from '@server/lib/client-html' import { ServerConfigManager } from '@server/lib/server-config-manager' -import { HttpStatusCode } from '@shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '@shared/models' import { HttpNodeinfoDiasporaSoftwareNsSchema20 } from '../../shared/models/nodeinfo/nodeinfo.model' import { root } from '../helpers/core-utils' import { CONFIG, isEmailEnabled } from '../initializers/config' diff --git a/server/helpers/custom-validators/video-ownership.ts b/server/helpers/custom-validators/video-ownership.ts index 0e1c63bad..cf15b385a 100644 --- a/server/helpers/custom-validators/video-ownership.ts +++ b/server/helpers/custom-validators/video-ownership.ts @@ -1,7 +1,7 @@ import { Response } from 'express' import { MUserId } from '@server/types/models' import { MVideoChangeOwnershipFull } from '@server/types/models/video/video-change-ownership' -import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '../../../shared/models/http/http-error-codes' function checkUserCanTerminateOwnershipChange (user: MUserId, videoChangeOwnership: MVideoChangeOwnershipFull, res: Response) { if (videoChangeOwnership.NextOwner.userId === user.id) { diff --git a/server/helpers/express-utils.ts b/server/helpers/express-utils.ts index 0ff113274..c299b70f1 100644 --- a/server/helpers/express-utils.ts +++ b/server/helpers/express-utils.ts @@ -1,6 +1,6 @@ import * as express from 'express' import * as multer from 'multer' -import { HttpStatusCode } from '../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '../../shared/models/http/http-error-codes' import { CONFIG } from '../initializers/config' import { REMOTE_SCHEME } from '../initializers/constants' import { getLowercaseExtension } from './core-utils' diff --git a/server/helpers/youtube-dl.ts b/server/helpers/youtube-dl.ts index fdd361390..3c80e7d41 100644 --- a/server/helpers/youtube-dl.ts +++ b/server/helpers/youtube-dl.ts @@ -3,7 +3,7 @@ import { ensureDir, move, pathExists, remove, writeFile } from 'fs-extra' import got from 'got' import { join } from 'path' import { CONFIG } from '@server/initializers/config' -import { HttpStatusCode } from '../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '../../shared/models/http/http-error-codes' import { VideoResolution } from '../../shared/models/videos' import { CONSTRAINTS_FIELDS, VIDEO_CATEGORIES, VIDEO_LANGUAGES, VIDEO_LICENCES } from '../initializers/constants' import { peertubeTruncate, pipelinePromise, root } from './core-utils' diff --git a/server/lib/activitypub/actors/refresh.ts b/server/lib/activitypub/actors/refresh.ts index b2fe3932f..0acaa9f62 100644 --- a/server/lib/activitypub/actors/refresh.ts +++ b/server/lib/activitypub/actors/refresh.ts @@ -4,7 +4,7 @@ import { PeerTubeRequestError } from '@server/helpers/requests' import { ActorLoadByUrlType } from '@server/lib/model-loaders' import { ActorModel } from '@server/models/actor/actor' import { MActorAccountChannelId, MActorFull } from '@server/types/models' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { fetchRemoteActor } from './shared' import { APActorUpdater } from './updater' import { getUrlFromWebfinger } from './webfinger' diff --git a/server/lib/activitypub/playlists/refresh.ts b/server/lib/activitypub/playlists/refresh.ts index ef3cb3fe4..493e8c7ec 100644 --- a/server/lib/activitypub/playlists/refresh.ts +++ b/server/lib/activitypub/playlists/refresh.ts @@ -2,7 +2,7 @@ import { logger, loggerTagsFactory } from '@server/helpers/logger' import { PeerTubeRequestError } from '@server/helpers/requests' import { JobQueue } from '@server/lib/job-queue' import { MVideoPlaylist, MVideoPlaylistOwner } from '@server/types/models' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { createOrUpdateVideoPlaylist } from './create-update' import { fetchRemoteVideoPlaylist } from './shared' diff --git a/server/lib/activitypub/videos/refresh.ts b/server/lib/activitypub/videos/refresh.ts index a7b82f286..3af08acf4 100644 --- a/server/lib/activitypub/videos/refresh.ts +++ b/server/lib/activitypub/videos/refresh.ts @@ -4,7 +4,7 @@ import { ActorFollowScoreCache } from '@server/lib/files-cache' import { VideoLoadByUrlType } from '@server/lib/model-loaders' import { VideoModel } from '@server/models/video/video' import { MVideoAccountLightBlacklistAllFiles, MVideoThumbnail } from '@server/types/models' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { fetchRemoteVideo, SyncParam, syncVideoExternalAttributes } from './shared' import { APVideoUpdater } from './updater' diff --git a/server/lib/client-html.ts b/server/lib/client-html.ts index 72194416d..c5d39445b 100644 --- a/server/lib/client-html.ts +++ b/server/lib/client-html.ts @@ -5,7 +5,7 @@ import validator from 'validator' import { escapeHTML } from '@shared/core-utils/renderer' import { HTMLServerConfig } from '@shared/models' import { buildFileLocale, getDefaultLocale, is18nLocale, POSSIBLE_LOCALES } from '../../shared/core-utils/i18n/i18n' -import { HttpStatusCode } from '../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '../../shared/models/http/http-error-codes' import { VideoPlaylistPrivacy, VideoPrivacy } from '../../shared/models/videos' import { isTestInstance, sha256 } from '../helpers/core-utils' import { logger } from '../helpers/logger' diff --git a/server/lib/job-queue/handlers/activitypub-cleaner.ts b/server/lib/job-queue/handlers/activitypub-cleaner.ts index 1caca1dcc..56e2b0ceb 100644 --- a/server/lib/job-queue/handlers/activitypub-cleaner.ts +++ b/server/lib/job-queue/handlers/activitypub-cleaner.ts @@ -12,7 +12,7 @@ import { AP_CLEANER_CONCURRENCY } from '@server/initializers/constants' import { VideoModel } from '@server/models/video/video' import { VideoCommentModel } from '@server/models/video/video-comment' import { VideoShareModel } from '@server/models/video/video-share' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { logger } from '../../../helpers/logger' import { AccountVideoRateModel } from '../../../models/account/account-video-rate' diff --git a/server/middlewares/activitypub.ts b/server/middlewares/activitypub.ts index 6b43b7764..6ef90b275 100644 --- a/server/middlewares/activitypub.ts +++ b/server/middlewares/activitypub.ts @@ -2,7 +2,7 @@ import { NextFunction, Request, Response } from 'express' import { getAPId } from '@server/helpers/activitypub' import { isActorDeleteActivityValid } from '@server/helpers/custom-validators/activitypub/actor' import { ActivityDelete, ActivityPubSignature } from '../../shared' -import { HttpStatusCode } from '../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '../../shared/models/http/http-error-codes' import { logger } from '../helpers/logger' import { isHTTPSignatureVerified, isJsonLDSignatureVerified, parseHTTPSignature } from '../helpers/peertube-crypto' import { ACCEPT_HEADERS, ACTIVITY_PUB, HTTP_SIGNATURE } from '../initializers/constants' diff --git a/server/middlewares/auth.ts b/server/middlewares/auth.ts index 176461cc2..9e6327b23 100644 --- a/server/middlewares/auth.ts +++ b/server/middlewares/auth.ts @@ -1,7 +1,7 @@ import * as express from 'express' import { Socket } from 'socket.io' import { getAccessToken } from '@server/lib/auth/oauth-model' -import { HttpStatusCode } from '../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '../../shared/models/http/http-error-codes' import { logger } from '../helpers/logger' import { handleOAuthAuthenticate } from '../lib/auth/oauth' diff --git a/server/middlewares/cache.ts b/server/middlewares/cache.ts index 0708ee8e8..1ced06042 100644 --- a/server/middlewares/cache.ts +++ b/server/middlewares/cache.ts @@ -1,6 +1,6 @@ import { Redis } from '../lib/redis' import * as apicache from 'apicache' -import { HttpStatusCode } from '../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '../../shared/models/http/http-error-codes' // Ensure Redis is initialized Redis.Instance.init() diff --git a/server/middlewares/error.ts b/server/middlewares/error.ts index e3eb1c8f5..af5a9c29a 100644 --- a/server/middlewares/error.ts +++ b/server/middlewares/error.ts @@ -1,6 +1,6 @@ import * as express from 'express' import { ProblemDocument, ProblemDocumentExtension } from 'http-problem-details' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' function apiFailMiddleware (req: express.Request, res: express.Response, next: express.NextFunction) { res.fail = options => { diff --git a/server/middlewares/servers.ts b/server/middlewares/servers.ts index 9aa56bc93..49a2241b3 100644 --- a/server/middlewares/servers.ts +++ b/server/middlewares/servers.ts @@ -1,6 +1,6 @@ import * as express from 'express' import { getHostWithPort } from '../helpers/express-utils' -import { HttpStatusCode } from '../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '../../shared/models/http/http-error-codes' function setBodyHostsPort (req: express.Request, res: express.Response, next: express.NextFunction) { if (!req.body.hosts) return next() diff --git a/server/middlewares/user-right.ts b/server/middlewares/user-right.ts index d1888c2d3..87a1766cf 100644 --- a/server/middlewares/user-right.ts +++ b/server/middlewares/user-right.ts @@ -1,7 +1,7 @@ import * as express from 'express' import { UserRight } from '../../shared' import { logger } from '../helpers/logger' -import { HttpStatusCode } from '../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '../../shared/models/http/http-error-codes' function ensureUserHasRight (userRight: UserRight) { return function (req: express.Request, res: express.Response, next: express.NextFunction) { diff --git a/server/middlewares/validators/abuse.ts b/server/middlewares/validators/abuse.ts index c048bc6af..f4d9c3af2 100644 --- a/server/middlewares/validators/abuse.ts +++ b/server/middlewares/validators/abuse.ts @@ -16,7 +16,7 @@ import { exists, isIdOrUUIDValid, isIdValid, toCompleteUUID, toIntOrNull } from import { logger } from '@server/helpers/logger' import { AbuseMessageModel } from '@server/models/abuse/abuse-message' import { AbuseCreate, UserRight } from '@shared/models' -import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '../../../shared/models/http/http-error-codes' import { areValidationErrors, doesAbuseExist, doesAccountIdExist, doesCommentIdExist, doesVideoExist } from './shared' const abuseReportValidator = [ diff --git a/server/middlewares/validators/activitypub/activity.ts b/server/middlewares/validators/activitypub/activity.ts index cc6acd4b1..d65a8e455 100644 --- a/server/middlewares/validators/activitypub/activity.ts +++ b/server/middlewares/validators/activitypub/activity.ts @@ -2,7 +2,7 @@ import * as express from 'express' import { isRootActivityValid } from '../../../helpers/custom-validators/activitypub/activity' import { logger } from '../../../helpers/logger' import { getServerActor } from '@server/models/application/application' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '../../../../shared/models/http/http-error-codes' async function activityPubValidator (req: express.Request, res: express.Response, next: express.NextFunction) { logger.debug('Checking activity pub parameters') diff --git a/server/middlewares/validators/blocklist.ts b/server/middlewares/validators/blocklist.ts index 826b16fc8..f15b293e9 100644 --- a/server/middlewares/validators/blocklist.ts +++ b/server/middlewares/validators/blocklist.ts @@ -1,7 +1,7 @@ import * as express from 'express' import { body, param } from 'express-validator' import { getServerActor } from '@server/models/application/application' -import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '../../../shared/models/http/http-error-codes' import { isHostValid } from '../../helpers/custom-validators/servers' import { logger } from '../../helpers/logger' import { WEBSERVER } from '../../initializers/constants' diff --git a/server/middlewares/validators/bulk.ts b/server/middlewares/validators/bulk.ts index 9bb95f5b7..4057b1e01 100644 --- a/server/middlewares/validators/bulk.ts +++ b/server/middlewares/validators/bulk.ts @@ -1,7 +1,7 @@ import * as express from 'express' import { body } from 'express-validator' import { isBulkRemoveCommentsOfScopeValid } from '@server/helpers/custom-validators/bulk' -import { HttpStatusCode } from '@shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '@shared/models' import { UserRight } from '@shared/models' import { BulkRemoveCommentsOfBody } from '@shared/models/bulk/bulk-remove-comments-of-body.model' import { logger } from '../../helpers/logger' diff --git a/server/middlewares/validators/feeds.ts b/server/middlewares/validators/feeds.ts index 51b8fdd19..1a5a8ffa0 100644 --- a/server/middlewares/validators/feeds.ts +++ b/server/middlewares/validators/feeds.ts @@ -1,7 +1,7 @@ import * as express from 'express' import { param, query } from 'express-validator' -import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '../../../shared/models/http/http-error-codes' import { isValidRSSFeed } from '../../helpers/custom-validators/feeds' import { exists, isIdOrUUIDValid, isIdValid, toCompleteUUID } from '../../helpers/custom-validators/misc' import { logger } from '../../helpers/logger' diff --git a/server/middlewares/validators/follows.ts b/server/middlewares/validators/follows.ts index 205baca48..05cc66c38 100644 --- a/server/middlewares/validators/follows.ts +++ b/server/middlewares/validators/follows.ts @@ -4,7 +4,7 @@ import { isFollowStateValid } from '@server/helpers/custom-validators/follows' import { loadActorUrlOrGetFromWebfinger } from '@server/lib/activitypub/actors' import { getServerActor } from '@server/models/application/application' import { MActorFollowActorsDefault } from '@server/types/models' -import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '../../../shared/models/http/http-error-codes' import { isTestInstance } from '../../helpers/core-utils' import { isActorTypeValid, isValidActorHandle } from '../../helpers/custom-validators/activitypub/actor' import { isEachUniqueHostValid, isHostValid } from '../../helpers/custom-validators/servers' diff --git a/server/middlewares/validators/oembed.ts b/server/middlewares/validators/oembed.ts index 0a82e6932..e5fc0c277 100644 --- a/server/middlewares/validators/oembed.ts +++ b/server/middlewares/validators/oembed.ts @@ -4,7 +4,7 @@ import { join } from 'path' import { loadVideo } from '@server/lib/model-loaders' import { VideoPlaylistModel } from '@server/models/video/video-playlist' import { VideoPlaylistPrivacy, VideoPrivacy } from '@shared/models' -import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '../../../shared/models/http/http-error-codes' import { isTestInstance } from '../../helpers/core-utils' import { isIdOrUUIDValid, toCompleteUUID } from '../../helpers/custom-validators/misc' import { logger } from '../../helpers/logger' diff --git a/server/middlewares/validators/plugins.ts b/server/middlewares/validators/plugins.ts index 8c76d2e36..3fb2176b9 100644 --- a/server/middlewares/validators/plugins.ts +++ b/server/middlewares/validators/plugins.ts @@ -1,6 +1,6 @@ import * as express from 'express' import { body, param, query, ValidationChain } from 'express-validator' -import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '../../../shared/models/http/http-error-codes' import { PluginType } from '../../../shared/models/plugins/plugin.type' import { InstallOrUpdatePlugin } from '../../../shared/models/plugins/server/api/install-plugin.model' import { exists, isBooleanValid, isSafePath, toBooleanOrNull, toIntOrNull } from '../../helpers/custom-validators/misc' diff --git a/server/middlewares/validators/redundancy.ts b/server/middlewares/validators/redundancy.ts index 116c8c611..f1b2ff5cd 100644 --- a/server/middlewares/validators/redundancy.ts +++ b/server/middlewares/validators/redundancy.ts @@ -1,7 +1,7 @@ import * as express from 'express' import { body, param, query } from 'express-validator' import { isVideoRedundancyTarget } from '@server/helpers/custom-validators/video-redundancies' -import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '../../../shared/models/http/http-error-codes' import { exists, isBooleanValid, diff --git a/server/middlewares/validators/server.ts b/server/middlewares/validators/server.ts index fc7239b25..29fdc13d2 100644 --- a/server/middlewares/validators/server.ts +++ b/server/middlewares/validators/server.ts @@ -1,6 +1,6 @@ import * as express from 'express' import { body } from 'express-validator' -import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '../../../shared/models/http/http-error-codes' import { isHostValid, isValidContactBody } from '../../helpers/custom-validators/servers' import { isUserDisplayNameValid } from '../../helpers/custom-validators/users' import { logger } from '../../helpers/logger' diff --git a/server/middlewares/validators/shared/abuses.ts b/server/middlewares/validators/shared/abuses.ts index 4a20a55fa..2b8d86ba5 100644 --- a/server/middlewares/validators/shared/abuses.ts +++ b/server/middlewares/validators/shared/abuses.ts @@ -1,6 +1,6 @@ import { Response } from 'express' import { AbuseModel } from '@server/models/abuse/abuse' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' async function doesAbuseExist (abuseId: number | string, res: Response) { const abuse = await AbuseModel.loadByIdWithReporter(parseInt(abuseId + '', 10)) diff --git a/server/middlewares/validators/shared/accounts.ts b/server/middlewares/validators/shared/accounts.ts index 04da15441..fe4f83aa0 100644 --- a/server/middlewares/validators/shared/accounts.ts +++ b/server/middlewares/validators/shared/accounts.ts @@ -2,7 +2,7 @@ import { Response } from 'express' import { AccountModel } from '@server/models/account/account' import { UserModel } from '@server/models/user/user' import { MAccountDefault } from '@server/types/models' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' function doesAccountIdExist (id: number | string, res: Response, sendNotFound = true) { const promise = AccountModel.load(parseInt(id + '', 10)) diff --git a/server/middlewares/validators/shared/video-blacklists.ts b/server/middlewares/validators/shared/video-blacklists.ts index 01491c10f..f85b39b23 100644 --- a/server/middlewares/validators/shared/video-blacklists.ts +++ b/server/middlewares/validators/shared/video-blacklists.ts @@ -1,6 +1,6 @@ import { Response } from 'express' import { VideoBlacklistModel } from '@server/models/video/video-blacklist' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' async function doesVideoBlacklistExist (videoId: number, res: Response) { const videoBlacklist = await VideoBlacklistModel.loadByVideoId(videoId) diff --git a/server/middlewares/validators/shared/video-captions.ts b/server/middlewares/validators/shared/video-captions.ts index 80f6c5a52..831b366ea 100644 --- a/server/middlewares/validators/shared/video-captions.ts +++ b/server/middlewares/validators/shared/video-captions.ts @@ -1,7 +1,7 @@ import { Response } from 'express' import { VideoCaptionModel } from '@server/models/video/video-caption' import { MVideoId } from '@server/types/models' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' async function doesVideoCaptionExist (video: MVideoId, language: string, res: Response) { const videoCaption = await VideoCaptionModel.loadByVideoIdAndLanguage(video.id, language) diff --git a/server/middlewares/validators/shared/video-channels.ts b/server/middlewares/validators/shared/video-channels.ts index fe2e663b7..3fc3d012a 100644 --- a/server/middlewares/validators/shared/video-channels.ts +++ b/server/middlewares/validators/shared/video-channels.ts @@ -1,7 +1,7 @@ import * as express from 'express' import { VideoChannelModel } from '@server/models/video/video-channel' import { MChannelBannerAccountDefault } from '@server/types/models' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' async function doesLocalVideoChannelNameExist (name: string, res: express.Response) { const videoChannel = await VideoChannelModel.loadLocalByNameAndPopulateAccount(name) diff --git a/server/middlewares/validators/shared/video-comments.ts b/server/middlewares/validators/shared/video-comments.ts index 83ea15c98..60132fb6e 100644 --- a/server/middlewares/validators/shared/video-comments.ts +++ b/server/middlewares/validators/shared/video-comments.ts @@ -1,7 +1,7 @@ import * as express from 'express' import { VideoCommentModel } from '@server/models/video/video-comment' import { MVideoId } from '@server/types/models' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' async function doesVideoCommentThreadExist (idArg: number | string, video: MVideoId, res: express.Response) { const id = parseInt(idArg + '', 10) diff --git a/server/middlewares/validators/shared/video-imports.ts b/server/middlewares/validators/shared/video-imports.ts index 0f984bc17..50b49ffcb 100644 --- a/server/middlewares/validators/shared/video-imports.ts +++ b/server/middlewares/validators/shared/video-imports.ts @@ -1,6 +1,6 @@ import * as express from 'express' import { VideoImportModel } from '@server/models/video/video-import' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' async function doesVideoImportExist (id: number, res: express.Response) { const videoImport = await VideoImportModel.loadAndPopulateVideo(id) diff --git a/server/middlewares/validators/shared/video-ownerships.ts b/server/middlewares/validators/shared/video-ownerships.ts index fc27006ce..93a23ef40 100644 --- a/server/middlewares/validators/shared/video-ownerships.ts +++ b/server/middlewares/validators/shared/video-ownerships.ts @@ -1,6 +1,6 @@ import * as express from 'express' import { VideoChangeOwnershipModel } from '@server/models/video/video-change-ownership' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' async function doesChangeVideoOwnershipExist (idArg: number | string, res: express.Response) { const id = parseInt(idArg + '', 10) diff --git a/server/middlewares/validators/shared/video-playlists.ts b/server/middlewares/validators/shared/video-playlists.ts index d762859a8..3f6768179 100644 --- a/server/middlewares/validators/shared/video-playlists.ts +++ b/server/middlewares/validators/shared/video-playlists.ts @@ -1,7 +1,7 @@ import * as express from 'express' import { VideoPlaylistModel } from '@server/models/video/video-playlist' import { MVideoPlaylist } from '@server/types/models' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' export type VideoPlaylistFetchType = 'summary' | 'all' async function doesVideoPlaylistExist (id: number | string, res: express.Response, fetchType: VideoPlaylistFetchType = 'summary') { diff --git a/server/middlewares/validators/shared/videos.ts b/server/middlewares/validators/shared/videos.ts index 2c66c1a3a..7f42a4893 100644 --- a/server/middlewares/validators/shared/videos.ts +++ b/server/middlewares/validators/shared/videos.ts @@ -12,7 +12,7 @@ import { MVideoImmutable, MVideoThumbnail } from '@server/types/models' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { UserRight } from '@shared/models' async function doesVideoExist (id: number | string, res: Response, fetchType: VideoLoadType = 'all') { diff --git a/server/middlewares/validators/themes.ts b/server/middlewares/validators/themes.ts index d4716257f..2953b9505 100644 --- a/server/middlewares/validators/themes.ts +++ b/server/middlewares/validators/themes.ts @@ -1,6 +1,6 @@ import * as express from 'express' import { param } from 'express-validator' -import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '../../../shared/models/http/http-error-codes' import { isSafePath } from '../../helpers/custom-validators/misc' import { isPluginNameValid, isPluginVersionValid } from '../../helpers/custom-validators/plugins' import { logger } from '../../helpers/logger' diff --git a/server/middlewares/validators/user-subscriptions.ts b/server/middlewares/validators/user-subscriptions.ts index ab7962923..df5777771 100644 --- a/server/middlewares/validators/user-subscriptions.ts +++ b/server/middlewares/validators/user-subscriptions.ts @@ -1,6 +1,6 @@ import * as express from 'express' import { body, param, query } from 'express-validator' -import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '../../../shared/models/http/http-error-codes' import { areValidActorHandles, isValidActorHandle } from '../../helpers/custom-validators/activitypub/actor' import { toArray } from '../../helpers/custom-validators/misc' import { logger } from '../../helpers/logger' diff --git a/server/middlewares/validators/users.ts b/server/middlewares/validators/users.ts index 698d7d814..748b89f8f 100644 --- a/server/middlewares/validators/users.ts +++ b/server/middlewares/validators/users.ts @@ -3,7 +3,7 @@ import { body, param, query } from 'express-validator' import { omit } from 'lodash' import { Hooks } from '@server/lib/plugins/hooks' import { MUserDefault } from '@server/types/models' -import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '../../../shared/models/http/http-error-codes' import { UserRole } from '../../../shared/models/users' import { UserRegister } from '../../../shared/models/users/user-register.model' import { isActorPreferredUsernameValid } from '../../helpers/custom-validators/activitypub/actor' diff --git a/server/middlewares/validators/videos/video-blacklist.ts b/server/middlewares/validators/videos/video-blacklist.ts index 21141d84d..3a4937b7b 100644 --- a/server/middlewares/validators/videos/video-blacklist.ts +++ b/server/middlewares/validators/videos/video-blacklist.ts @@ -1,6 +1,6 @@ import * as express from 'express' import { body, query } from 'express-validator' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '../../../../shared/models/http/http-error-codes' import { isBooleanValid, toBooleanOrNull, toIntOrNull } from '../../../helpers/custom-validators/misc' import { isVideoBlacklistReasonValid, isVideoBlacklistTypeValid } from '../../../helpers/custom-validators/video-blacklist' import { logger } from '../../../helpers/logger' diff --git a/server/middlewares/validators/videos/video-channels.ts b/server/middlewares/validators/videos/video-channels.ts index e7df185e4..ea10fe425 100644 --- a/server/middlewares/validators/videos/video-channels.ts +++ b/server/middlewares/validators/videos/video-channels.ts @@ -3,7 +3,7 @@ import { body, param, query } from 'express-validator' import { VIDEO_CHANNELS } from '@server/initializers/constants' import { MChannelAccountDefault, MUser } from '@server/types/models' import { UserRight } from '../../../../shared' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '../../../../shared/models/http/http-error-codes' import { isActorPreferredUsernameValid } from '../../../helpers/custom-validators/activitypub/actor' import { isBooleanValid, toBooleanOrNull } from '../../../helpers/custom-validators/misc' import { diff --git a/server/middlewares/validators/videos/video-comments.ts b/server/middlewares/validators/videos/video-comments.ts index 885506ebe..61c2ed92f 100644 --- a/server/middlewares/validators/videos/video-comments.ts +++ b/server/middlewares/validators/videos/video-comments.ts @@ -2,7 +2,7 @@ import * as express from 'express' import { body, param, query } from 'express-validator' import { MUserAccountUrl } from '@server/types/models' import { UserRight } from '../../../../shared' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '../../../../shared/models/http/http-error-codes' import { exists, isBooleanValid, isIdValid, toBooleanOrNull } from '../../../helpers/custom-validators/misc' import { isValidVideoCommentText } from '../../../helpers/custom-validators/video-comments' import { logger } from '../../../helpers/logger' diff --git a/server/middlewares/validators/videos/video-imports.ts b/server/middlewares/validators/videos/video-imports.ts index 85dc647ce..52b839e56 100644 --- a/server/middlewares/validators/videos/video-imports.ts +++ b/server/middlewares/validators/videos/video-imports.ts @@ -2,7 +2,7 @@ import * as express from 'express' import { body } from 'express-validator' import { isPreImportVideoAccepted } from '@server/lib/moderation' import { Hooks } from '@server/lib/plugins/hooks' -import { HttpStatusCode } from '@shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '@shared/models' import { VideoImportCreate } from '@shared/models/videos/import/video-import-create.model' import { isIdValid, toIntOrNull } from '../../../helpers/custom-validators/misc' import { isVideoImportTargetUrlValid, isVideoImportTorrentFile } from '../../../helpers/custom-validators/video-imports' diff --git a/server/middlewares/validators/videos/video-live.ts b/server/middlewares/validators/videos/video-live.ts index 7cfb935e3..5c8a4269d 100644 --- a/server/middlewares/validators/videos/video-live.ts +++ b/server/middlewares/validators/videos/video-live.ts @@ -5,7 +5,7 @@ import { isLocalLiveVideoAccepted } from '@server/lib/moderation' import { Hooks } from '@server/lib/plugins/hooks' import { VideoModel } from '@server/models/video/video' import { VideoLiveModel } from '@server/models/video/video-live' -import { HttpStatusCode } from '@shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '@shared/models' import { ServerErrorCode, UserRight, VideoState } from '@shared/models' import { isBooleanValid, isIdValid, toBooleanOrNull, toIntOrNull } from '../../../helpers/custom-validators/misc' import { isVideoNameValid } from '../../../helpers/custom-validators/videos' diff --git a/server/middlewares/validators/videos/video-ownership-changes.ts b/server/middlewares/validators/videos/video-ownership-changes.ts index 54ac46c99..06f86a4c8 100644 --- a/server/middlewares/validators/videos/video-ownership-changes.ts +++ b/server/middlewares/validators/videos/video-ownership-changes.ts @@ -6,7 +6,7 @@ import { logger } from '@server/helpers/logger' import { isAbleToUploadVideo } from '@server/lib/user' import { AccountModel } from '@server/models/account/account' import { MVideoWithAllFiles } from '@server/types/models' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { ServerErrorCode, UserRight, VideoChangeOwnershipAccept, VideoChangeOwnershipStatus, VideoState } from '@shared/models' import { areValidationErrors, diff --git a/server/middlewares/validators/videos/video-playlists.ts b/server/middlewares/validators/videos/video-playlists.ts index 5ee7ee0ce..ab84b4814 100644 --- a/server/middlewares/validators/videos/video-playlists.ts +++ b/server/middlewares/validators/videos/video-playlists.ts @@ -3,7 +3,7 @@ import { body, param, query, ValidationChain } from 'express-validator' import { ExpressPromiseHandler } from '@server/types/express' import { MUserAccountId } from '@server/types/models' import { UserRight, VideoPlaylistCreate, VideoPlaylistUpdate } from '../../../../shared' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '../../../../shared/models/http/http-error-codes' import { VideoPlaylistPrivacy } from '../../../../shared/models/videos/playlist/video-playlist-privacy.model' import { VideoPlaylistType } from '../../../../shared/models/videos/playlist/video-playlist-type.model' import { diff --git a/server/middlewares/validators/videos/video-rates.ts b/server/middlewares/validators/videos/video-rates.ts index 5d5dfb222..5fe78b39e 100644 --- a/server/middlewares/validators/videos/video-rates.ts +++ b/server/middlewares/validators/videos/video-rates.ts @@ -1,6 +1,6 @@ import * as express from 'express' import { body, param, query } from 'express-validator' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '../../../../shared/models/http/http-error-codes' import { VideoRateType } from '../../../../shared/models/videos' import { isAccountNameValid } from '../../../helpers/custom-validators/accounts' import { isIdValid } from '../../../helpers/custom-validators/misc' diff --git a/server/middlewares/validators/videos/video-shares.ts b/server/middlewares/validators/videos/video-shares.ts index 7e54b6fc0..3b8d61768 100644 --- a/server/middlewares/validators/videos/video-shares.ts +++ b/server/middlewares/validators/videos/video-shares.ts @@ -1,6 +1,6 @@ import * as express from 'express' import { param } from 'express-validator' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '../../../../shared/models/http/http-error-codes' import { isIdValid } from '../../../helpers/custom-validators/misc' import { logger } from '../../../helpers/logger' import { VideoShareModel } from '../../../models/video/video-share' diff --git a/server/middlewares/validators/videos/video-watch.ts b/server/middlewares/validators/videos/video-watch.ts index 43306f7cd..431515eb1 100644 --- a/server/middlewares/validators/videos/video-watch.ts +++ b/server/middlewares/validators/videos/video-watch.ts @@ -1,6 +1,6 @@ import * as express from 'express' import { body } from 'express-validator' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '../../../../shared/models/http/http-error-codes' import { toIntOrNull } from '../../../helpers/custom-validators/misc' import { logger } from '../../../helpers/logger' import { areValidationErrors, doesVideoExist, isValidVideoIdParam } from '../shared' diff --git a/server/middlewares/validators/videos/videos.ts b/server/middlewares/validators/videos/videos.ts index 49e10e2b5..374a59c50 100644 --- a/server/middlewares/validators/videos/videos.ts +++ b/server/middlewares/validators/videos/videos.ts @@ -6,7 +6,7 @@ import { getServerActor } from '@server/models/application/application' import { ExpressPromiseHandler } from '@server/types/express' import { MUserAccountId, MVideoFullLight } from '@server/types/models' import { ServerErrorCode, UserRight, VideoPrivacy } from '../../../../shared' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '../../../../shared/models/http/http-error-codes' import { exists, isBooleanValid, diff --git a/server/middlewares/validators/webfinger.ts b/server/middlewares/validators/webfinger.ts index bcdd136c6..131360820 100644 --- a/server/middlewares/validators/webfinger.ts +++ b/server/middlewares/validators/webfinger.ts @@ -1,6 +1,6 @@ import * as express from 'express' import { query } from 'express-validator' -import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '../../../shared/models/http/http-error-codes' import { isWebfingerLocalResourceValid } from '../../helpers/custom-validators/webfinger' import { getHostWithPort } from '../../helpers/express-utils' import { logger } from '../../helpers/logger' diff --git a/server/tests/api/activitypub/client.ts b/server/tests/api/activitypub/client.ts index 720231f02..53cc40663 100644 --- a/server/tests/api/activitypub/client.ts +++ b/server/tests/api/activitypub/client.ts @@ -2,7 +2,7 @@ import 'mocha' import * as chai from 'chai' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { cleanupTests, doubleFollow, @@ -68,7 +68,7 @@ describe('Test activitypub', function () { await setDefaultVideoChannel(servers) { - video = await await servers[0].videos.quickUpload({ name: 'video' }) + video = await servers[0].videos.quickUpload({ name: 'video' }) } { diff --git a/server/tests/api/activitypub/refresher.ts b/server/tests/api/activitypub/refresher.ts index bbec0d309..a0b72c7e6 100644 --- a/server/tests/api/activitypub/refresher.ts +++ b/server/tests/api/activitypub/refresher.ts @@ -1,7 +1,7 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ import 'mocha' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { cleanupTests, doubleFollow, diff --git a/server/tests/api/activitypub/security.ts b/server/tests/api/activitypub/security.ts index c173648b3..94d946563 100644 --- a/server/tests/api/activitypub/security.ts +++ b/server/tests/api/activitypub/security.ts @@ -2,20 +2,13 @@ import 'mocha' import * as chai from 'chai' +import { activityPubContextify, buildSignedActivity } from '@server/helpers/activitypub' import { buildDigest } from '@server/helpers/peertube-crypto' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' -import { - buildAbsoluteFixturePath, - cleanupTests, - createMultipleServers, - killallServers, - PeerTubeServer, - wait -} from '../../../../shared/extra-utils' -import { makeFollowRequest, makePOSTAPRequest } from '../../../../shared/extra-utils/requests/activitypub' -import { activityPubContextify, buildSignedActivity } from '../../../helpers/activitypub' -import { HTTP_SIGNATURE } from '../../../initializers/constants' -import { buildGlobalHeaders } from '../../../lib/job-queue/handlers/utils/activitypub-http-utils' +import { HTTP_SIGNATURE } from '@server/initializers/constants' +import { buildGlobalHeaders } from '@server/lib/job-queue/handlers/utils/activitypub-http-utils' +import { buildAbsoluteFixturePath, cleanupTests, createMultipleServers, killallServers, PeerTubeServer, wait } from '@shared/extra-utils' +import { makeFollowRequest, makePOSTAPRequest } from '@shared/extra-utils/requests/activitypub' +import { HttpStatusCode } from '@shared/models' const expect = chai.expect diff --git a/server/tests/api/check-params/abuses.ts b/server/tests/api/check-params/abuses.ts index 62811f932..87d93195c 100644 --- a/server/tests/api/check-params/abuses.ts +++ b/server/tests/api/check-params/abuses.ts @@ -1,7 +1,7 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ import 'mocha' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { AbusesCommand, checkBadCountPagination, @@ -66,7 +66,7 @@ describe('Test abuses API validators', function () { await makeGetRequest({ url: server.url, path, - statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 + expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -75,7 +75,7 @@ describe('Test abuses API validators', function () { url: server.url, path, token: userToken, - statusCodeExpected: HttpStatusCode.FORBIDDEN_403 + expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) @@ -110,7 +110,7 @@ describe('Test abuses API validators', function () { videoIs: 'deleted' } - await makeGetRequest({ url: server.url, path, token: server.accessToken, query, statusCodeExpected: HttpStatusCode.OK_200 }) + await makeGetRequest({ url: server.url, path, token: server.accessToken, query, expectedStatus: HttpStatusCode.OK_200 }) }) }) @@ -133,7 +133,7 @@ describe('Test abuses API validators', function () { await makeGetRequest({ url: server.url, path, - statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 + expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -152,7 +152,7 @@ describe('Test abuses API validators', function () { state: 2 } - await makeGetRequest({ url: server.url, path, token: userToken, query, statusCodeExpected: HttpStatusCode.OK_200 }) + await makeGetRequest({ url: server.url, path, token: userToken, query, expectedStatus: HttpStatusCode.OK_200 }) }) }) @@ -176,7 +176,7 @@ describe('Test abuses API validators', function () { path, token: userToken, fields, - statusCodeExpected: HttpStatusCode.NOT_FOUND_404 + expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) @@ -192,7 +192,7 @@ describe('Test abuses API validators', function () { path, token: userToken, fields, - statusCodeExpected: HttpStatusCode.NOT_FOUND_404 + expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) @@ -208,7 +208,7 @@ describe('Test abuses API validators', function () { path, token: userToken, fields, - statusCodeExpected: HttpStatusCode.NOT_FOUND_404 + expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) @@ -219,14 +219,14 @@ describe('Test abuses API validators', function () { path, token: userToken, fields, - statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 + expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) it('Should fail with a non authenticated user', async function () { const fields = { video: { id: server.store.video.id }, reason: 'my super reason' } - await makePostBodyRequest({ url: server.url, path, token: 'hello', fields, statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) + await makePostBodyRequest({ url: server.url, path, token: 'hello', fields, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should fail with a reason too short', async function () { @@ -249,7 +249,7 @@ describe('Test abuses API validators', function () { path, token: userToken, fields, - statusCodeExpected: HttpStatusCode.OK_200 + expectedStatus: HttpStatusCode.OK_200 }) abuseId = res.body.abuse.id }) @@ -283,7 +283,7 @@ describe('Test abuses API validators', function () { predefinedReasons: [ 'serverRules' ] } - await makePostBodyRequest({ url: server.url, path, token: userToken, fields, statusCodeExpected: HttpStatusCode.OK_200 }) + await makePostBodyRequest({ url: server.url, path, token: userToken, fields, expectedStatus: HttpStatusCode.OK_200 }) }) }) diff --git a/server/tests/api/check-params/accounts.ts b/server/tests/api/check-params/accounts.ts index e866593db..0cae485d9 100644 --- a/server/tests/api/check-params/accounts.ts +++ b/server/tests/api/check-params/accounts.ts @@ -1,7 +1,7 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ import 'mocha' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { checkBadCountPagination, checkBadSortPagination, diff --git a/server/tests/api/check-params/blocklist.ts b/server/tests/api/check-params/blocklist.ts index b2a1cc4e2..7d5fae5cf 100644 --- a/server/tests/api/check-params/blocklist.ts +++ b/server/tests/api/check-params/blocklist.ts @@ -1,23 +1,20 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ import 'mocha' - import { + checkBadCountPagination, + checkBadSortPagination, + checkBadStartPagination, cleanupTests, - doubleFollow, createMultipleServers, + doubleFollow, makeDeleteRequest, makeGetRequest, makePostBodyRequest, PeerTubeServer, setAccessTokensToServers -} from '../../../../shared/extra-utils' -import { - checkBadCountPagination, - checkBadSortPagination, - checkBadStartPagination -} from '../../../../shared/extra-utils/requests/check-api-params' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' +} from '@shared/extra-utils' +import { HttpStatusCode } from '@shared/models' describe('Test blocklist API validators', function () { let servers: PeerTubeServer[] @@ -52,7 +49,7 @@ describe('Test blocklist API validators', function () { await makeGetRequest({ url: server.url, path, - statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 + expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -75,7 +72,7 @@ describe('Test blocklist API validators', function () { url: server.url, path, fields: { accountName: 'user1' }, - statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 + expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -85,7 +82,7 @@ describe('Test blocklist API validators', function () { token: server.accessToken, path, fields: { accountName: 'user2' }, - statusCodeExpected: HttpStatusCode.NOT_FOUND_404 + expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) @@ -95,7 +92,7 @@ describe('Test blocklist API validators', function () { token: server.accessToken, path, fields: { accountName: 'root' }, - statusCodeExpected: HttpStatusCode.CONFLICT_409 + expectedStatus: HttpStatusCode.CONFLICT_409 }) }) @@ -105,7 +102,7 @@ describe('Test blocklist API validators', function () { token: server.accessToken, path, fields: { accountName: 'user1' }, - statusCodeExpected: HttpStatusCode.NO_CONTENT_204 + expectedStatus: HttpStatusCode.NO_CONTENT_204 }) }) }) @@ -115,7 +112,7 @@ describe('Test blocklist API validators', function () { await makeDeleteRequest({ url: server.url, path: path + '/user1', - statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 + expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -124,7 +121,7 @@ describe('Test blocklist API validators', function () { url: server.url, path: path + '/user2', token: server.accessToken, - statusCodeExpected: HttpStatusCode.NOT_FOUND_404 + expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) @@ -133,7 +130,7 @@ describe('Test blocklist API validators', function () { url: server.url, path: path + '/user1', token: server.accessToken, - statusCodeExpected: HttpStatusCode.NO_CONTENT_204 + expectedStatus: HttpStatusCode.NO_CONTENT_204 }) }) }) @@ -147,7 +144,7 @@ describe('Test blocklist API validators', function () { await makeGetRequest({ url: server.url, path, - statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 + expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -170,7 +167,7 @@ describe('Test blocklist API validators', function () { url: server.url, path, fields: { host: 'localhost:9002' }, - statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 + expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -180,7 +177,7 @@ describe('Test blocklist API validators', function () { token: server.accessToken, path, fields: { host: 'localhost:9003' }, - statusCodeExpected: HttpStatusCode.NO_CONTENT_204 + expectedStatus: HttpStatusCode.NO_CONTENT_204 }) }) @@ -190,7 +187,7 @@ describe('Test blocklist API validators', function () { token: server.accessToken, path, fields: { host: 'localhost:' + server.port }, - statusCodeExpected: HttpStatusCode.CONFLICT_409 + expectedStatus: HttpStatusCode.CONFLICT_409 }) }) @@ -200,7 +197,7 @@ describe('Test blocklist API validators', function () { token: server.accessToken, path, fields: { host: 'localhost:' + servers[1].port }, - statusCodeExpected: HttpStatusCode.NO_CONTENT_204 + expectedStatus: HttpStatusCode.NO_CONTENT_204 }) }) }) @@ -210,7 +207,7 @@ describe('Test blocklist API validators', function () { await makeDeleteRequest({ url: server.url, path: path + '/localhost:' + servers[1].port, - statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 + expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -219,7 +216,7 @@ describe('Test blocklist API validators', function () { url: server.url, path: path + '/localhost:9004', token: server.accessToken, - statusCodeExpected: HttpStatusCode.NOT_FOUND_404 + expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) @@ -228,7 +225,7 @@ describe('Test blocklist API validators', function () { url: server.url, path: path + '/localhost:' + servers[1].port, token: server.accessToken, - statusCodeExpected: HttpStatusCode.NO_CONTENT_204 + expectedStatus: HttpStatusCode.NO_CONTENT_204 }) }) }) @@ -245,7 +242,7 @@ describe('Test blocklist API validators', function () { await makeGetRequest({ url: server.url, path, - statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 + expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -254,7 +251,7 @@ describe('Test blocklist API validators', function () { url: server.url, token: userAccessToken, path, - statusCodeExpected: HttpStatusCode.FORBIDDEN_403 + expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) @@ -277,7 +274,7 @@ describe('Test blocklist API validators', function () { url: server.url, path, fields: { accountName: 'user1' }, - statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 + expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -287,7 +284,7 @@ describe('Test blocklist API validators', function () { token: userAccessToken, path, fields: { accountName: 'user1' }, - statusCodeExpected: HttpStatusCode.FORBIDDEN_403 + expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) @@ -297,7 +294,7 @@ describe('Test blocklist API validators', function () { token: server.accessToken, path, fields: { accountName: 'user2' }, - statusCodeExpected: HttpStatusCode.NOT_FOUND_404 + expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) @@ -307,7 +304,7 @@ describe('Test blocklist API validators', function () { token: server.accessToken, path, fields: { accountName: 'root' }, - statusCodeExpected: HttpStatusCode.CONFLICT_409 + expectedStatus: HttpStatusCode.CONFLICT_409 }) }) @@ -317,7 +314,7 @@ describe('Test blocklist API validators', function () { token: server.accessToken, path, fields: { accountName: 'user1' }, - statusCodeExpected: HttpStatusCode.NO_CONTENT_204 + expectedStatus: HttpStatusCode.NO_CONTENT_204 }) }) }) @@ -327,7 +324,7 @@ describe('Test blocklist API validators', function () { await makeDeleteRequest({ url: server.url, path: path + '/user1', - statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 + expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -336,7 +333,7 @@ describe('Test blocklist API validators', function () { url: server.url, path: path + '/user1', token: userAccessToken, - statusCodeExpected: HttpStatusCode.FORBIDDEN_403 + expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) @@ -345,7 +342,7 @@ describe('Test blocklist API validators', function () { url: server.url, path: path + '/user2', token: server.accessToken, - statusCodeExpected: HttpStatusCode.NOT_FOUND_404 + expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) @@ -354,7 +351,7 @@ describe('Test blocklist API validators', function () { url: server.url, path: path + '/user1', token: server.accessToken, - statusCodeExpected: HttpStatusCode.NO_CONTENT_204 + expectedStatus: HttpStatusCode.NO_CONTENT_204 }) }) }) @@ -368,7 +365,7 @@ describe('Test blocklist API validators', function () { await makeGetRequest({ url: server.url, path, - statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 + expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -377,7 +374,7 @@ describe('Test blocklist API validators', function () { url: server.url, token: userAccessToken, path, - statusCodeExpected: HttpStatusCode.FORBIDDEN_403 + expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) @@ -400,7 +397,7 @@ describe('Test blocklist API validators', function () { url: server.url, path, fields: { host: 'localhost:' + servers[1].port }, - statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 + expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -410,7 +407,7 @@ describe('Test blocklist API validators', function () { token: userAccessToken, path, fields: { host: 'localhost:' + servers[1].port }, - statusCodeExpected: HttpStatusCode.FORBIDDEN_403 + expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) @@ -420,7 +417,7 @@ describe('Test blocklist API validators', function () { token: server.accessToken, path, fields: { host: 'localhost:9003' }, - statusCodeExpected: HttpStatusCode.NO_CONTENT_204 + expectedStatus: HttpStatusCode.NO_CONTENT_204 }) }) @@ -430,7 +427,7 @@ describe('Test blocklist API validators', function () { token: server.accessToken, path, fields: { host: 'localhost:' + server.port }, - statusCodeExpected: HttpStatusCode.CONFLICT_409 + expectedStatus: HttpStatusCode.CONFLICT_409 }) }) @@ -440,7 +437,7 @@ describe('Test blocklist API validators', function () { token: server.accessToken, path, fields: { host: 'localhost:' + servers[1].port }, - statusCodeExpected: HttpStatusCode.NO_CONTENT_204 + expectedStatus: HttpStatusCode.NO_CONTENT_204 }) }) }) @@ -450,7 +447,7 @@ describe('Test blocklist API validators', function () { await makeDeleteRequest({ url: server.url, path: path + '/localhost:' + servers[1].port, - statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 + expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -459,7 +456,7 @@ describe('Test blocklist API validators', function () { url: server.url, path: path + '/localhost:' + servers[1].port, token: userAccessToken, - statusCodeExpected: HttpStatusCode.FORBIDDEN_403 + expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) @@ -468,7 +465,7 @@ describe('Test blocklist API validators', function () { url: server.url, path: path + '/localhost:9004', token: server.accessToken, - statusCodeExpected: HttpStatusCode.NOT_FOUND_404 + expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) @@ -477,7 +474,7 @@ describe('Test blocklist API validators', function () { url: server.url, path: path + '/localhost:' + servers[1].port, token: server.accessToken, - statusCodeExpected: HttpStatusCode.NO_CONTENT_204 + expectedStatus: HttpStatusCode.NO_CONTENT_204 }) }) }) diff --git a/server/tests/api/check-params/bulk.ts b/server/tests/api/check-params/bulk.ts index a660c3d80..bc9d7784d 100644 --- a/server/tests/api/check-params/bulk.ts +++ b/server/tests/api/check-params/bulk.ts @@ -1,14 +1,8 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ import 'mocha' -import { - cleanupTests, - createSingleServer, - PeerTubeServer, - setAccessTokensToServers -} from '../../../../shared/extra-utils' -import { makePostBodyRequest } from '../../../../shared/extra-utils/requests/requests' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' +import { cleanupTests, createSingleServer, makePostBodyRequest, PeerTubeServer, setAccessTokensToServers } from '@shared/extra-utils' +import { HttpStatusCode } from '@shared/models' describe('Test bulk API validators', function () { let server: PeerTubeServer @@ -36,7 +30,7 @@ describe('Test bulk API validators', function () { url: server.url, path, fields: { accountName: 'user1', scope: 'my-videos' }, - statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 + expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -46,7 +40,7 @@ describe('Test bulk API validators', function () { token: server.accessToken, path, fields: { accountName: 'user2', scope: 'my-videos' }, - statusCodeExpected: HttpStatusCode.NOT_FOUND_404 + expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) @@ -56,7 +50,7 @@ describe('Test bulk API validators', function () { token: server.accessToken, path, fields: { accountName: 'user1', scope: 'my-videoss' }, - statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 + expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) @@ -66,7 +60,7 @@ describe('Test bulk API validators', function () { token: userAccessToken, path, fields: { accountName: 'user1', scope: 'instance' }, - statusCodeExpected: HttpStatusCode.FORBIDDEN_403 + expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) @@ -76,7 +70,7 @@ describe('Test bulk API validators', function () { token: server.accessToken, path, fields: { accountName: 'user1', scope: 'instance' }, - statusCodeExpected: HttpStatusCode.NO_CONTENT_204 + expectedStatus: HttpStatusCode.NO_CONTENT_204 }) }) }) diff --git a/server/tests/api/check-params/config.ts b/server/tests/api/check-params/config.ts index 1756d58ee..c3438917e 100644 --- a/server/tests/api/check-params/config.ts +++ b/server/tests/api/check-params/config.ts @@ -2,7 +2,7 @@ import 'mocha' import { omit } from 'lodash' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { cleanupTests, createSingleServer, @@ -214,7 +214,7 @@ describe('Test config API validators', function () { await makeGetRequest({ url: server.url, path, - statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 + expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -223,7 +223,7 @@ describe('Test config API validators', function () { url: server.url, path, token: userAccessToken, - statusCodeExpected: HttpStatusCode.FORBIDDEN_403 + expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) }) @@ -234,7 +234,7 @@ describe('Test config API validators', function () { url: server.url, path, fields: updateParams, - statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 + expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -244,7 +244,7 @@ describe('Test config API validators', function () { path, fields: updateParams, token: userAccessToken, - statusCodeExpected: HttpStatusCode.FORBIDDEN_403 + expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) @@ -256,7 +256,7 @@ describe('Test config API validators', function () { path, fields: newUpdateParams, token: server.accessToken, - statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 + expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) @@ -274,7 +274,7 @@ describe('Test config API validators', function () { path, fields: newUpdateParams, token: server.accessToken, - statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 + expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) @@ -295,7 +295,7 @@ describe('Test config API validators', function () { path, fields: newUpdateParams, token: server.accessToken, - statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 + expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) @@ -318,7 +318,7 @@ describe('Test config API validators', function () { path, fields: newUpdateParams, token: server.accessToken, - statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 + expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) @@ -328,7 +328,7 @@ describe('Test config API validators', function () { path, fields: updateParams, token: server.accessToken, - statusCodeExpected: HttpStatusCode.OK_200 + expectedStatus: HttpStatusCode.OK_200 }) }) }) @@ -338,7 +338,7 @@ describe('Test config API validators', function () { await makeDeleteRequest({ url: server.url, path, - statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 + expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -347,7 +347,7 @@ describe('Test config API validators', function () { url: server.url, path, token: userAccessToken, - statusCodeExpected: HttpStatusCode.FORBIDDEN_403 + expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) }) diff --git a/server/tests/api/check-params/contact-form.ts b/server/tests/api/check-params/contact-form.ts index 8c2b2a84b..8e755c69b 100644 --- a/server/tests/api/check-params/contact-form.ts +++ b/server/tests/api/check-params/contact-form.ts @@ -1,7 +1,7 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ import 'mocha' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { cleanupTests, createSingleServer, killallServers, MockSmtpServer, PeerTubeServer } from '@shared/extra-utils' import { ContactFormCommand } from '@shared/extra-utils/server' diff --git a/server/tests/api/check-params/custom-pages.ts b/server/tests/api/check-params/custom-pages.ts index 043505e32..9fbbea315 100644 --- a/server/tests/api/check-params/custom-pages.ts +++ b/server/tests/api/check-params/custom-pages.ts @@ -1,14 +1,15 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ import 'mocha' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' import { cleanupTests, createSingleServer, + makeGetRequest, + makePutBodyRequest, PeerTubeServer, setAccessTokensToServers -} from '../../../../shared/extra-utils' -import { makeGetRequest, makePutBodyRequest } from '../../../../shared/extra-utils/requests/requests' +} from '@shared/extra-utils' +import { HttpStatusCode } from '@shared/models' describe('Test custom pages validators', function () { const path = '/api/v1/custom-pages/homepage/instance' @@ -37,7 +38,7 @@ describe('Test custom pages validators', function () { url: server.url, path, fields: { content: 'super content' }, - statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 + expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -47,7 +48,7 @@ describe('Test custom pages validators', function () { path, token: userAccessToken, fields: { content: 'super content' }, - statusCodeExpected: HttpStatusCode.FORBIDDEN_403 + expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) @@ -57,7 +58,7 @@ describe('Test custom pages validators', function () { path, token: server.accessToken, fields: { content: 'super content' }, - statusCodeExpected: HttpStatusCode.NO_CONTENT_204 + expectedStatus: HttpStatusCode.NO_CONTENT_204 }) }) }) @@ -68,7 +69,7 @@ describe('Test custom pages validators', function () { await makeGetRequest({ url: server.url, path, - statusCodeExpected: HttpStatusCode.OK_200 + expectedStatus: HttpStatusCode.OK_200 }) }) }) diff --git a/server/tests/api/check-params/debug.ts b/server/tests/api/check-params/debug.ts index 9c13e9daf..a55786359 100644 --- a/server/tests/api/check-params/debug.ts +++ b/server/tests/api/check-params/debug.ts @@ -1,15 +1,8 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ import 'mocha' - -import { - cleanupTests, - createSingleServer, - PeerTubeServer, - setAccessTokensToServers -} from '../../../../shared/extra-utils' -import { makeGetRequest } from '../../../../shared/extra-utils/requests/requests' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' +import { cleanupTests, createSingleServer, makeGetRequest, PeerTubeServer, setAccessTokensToServers } from '@shared/extra-utils' +import { HttpStatusCode } from '@shared/models' describe('Test debug API validators', function () { const path = '/api/v1/server/debug' @@ -39,7 +32,7 @@ describe('Test debug API validators', function () { await makeGetRequest({ url: server.url, path, - statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 + expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -48,7 +41,7 @@ describe('Test debug API validators', function () { url: server.url, path, token: userAccessToken, - statusCodeExpected: HttpStatusCode.FORBIDDEN_403 + expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) @@ -58,7 +51,7 @@ describe('Test debug API validators', function () { path, token: server.accessToken, query: { startDate: new Date().toISOString() }, - statusCodeExpected: HttpStatusCode.OK_200 + expectedStatus: HttpStatusCode.OK_200 }) }) }) diff --git a/server/tests/api/check-params/follows.ts b/server/tests/api/check-params/follows.ts index 0fd2b4925..dfe3f226d 100644 --- a/server/tests/api/check-params/follows.ts +++ b/server/tests/api/check-params/follows.ts @@ -1,21 +1,19 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ import 'mocha' - import { + checkBadCountPagination, + checkBadSortPagination, + checkBadStartPagination, cleanupTests, createSingleServer, - makeDeleteRequest, makeGetRequest, + makeDeleteRequest, + makeGetRequest, makePostBodyRequest, PeerTubeServer, setAccessTokensToServers -} from '../../../../shared/extra-utils' -import { - checkBadCountPagination, - checkBadSortPagination, - checkBadStartPagination -} from '../../../../shared/extra-utils/requests/check-api-params' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' +} from '@shared/extra-utils' +import { HttpStatusCode } from '@shared/models' describe('Test server follows API validators', function () { let server: PeerTubeServer @@ -51,7 +49,7 @@ describe('Test server follows API validators', function () { url: server.url, path, token: server.accessToken, - statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 + expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) @@ -61,7 +59,7 @@ describe('Test server follows API validators', function () { path, token: server.accessToken, fields: { hosts: 'localhost:9002' }, - statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 + expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) @@ -71,7 +69,7 @@ describe('Test server follows API validators', function () { path, fields: { hosts: [ 'localhost:9002', 'localhost:coucou' ] }, token: server.accessToken, - statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 + expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) @@ -81,7 +79,7 @@ describe('Test server follows API validators', function () { path, fields: { hosts: [ 'localhost:9002', 'http://localhost:9003' ] }, token: server.accessToken, - statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 + expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) @@ -91,7 +89,7 @@ describe('Test server follows API validators', function () { path, fields: { urls: [ 'localhost:9002', 'localhost:9002' ] }, token: server.accessToken, - statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 + expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) @@ -101,7 +99,7 @@ describe('Test server follows API validators', function () { path, fields: { hosts: [ 'localhost:9002' ] }, token: 'fake_token', - statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 + expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -111,7 +109,7 @@ describe('Test server follows API validators', function () { path, fields: { hosts: [ 'localhost:9002' ] }, token: userAccessToken, - statusCodeExpected: HttpStatusCode.FORBIDDEN_403 + expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) }) @@ -155,7 +153,7 @@ describe('Test server follows API validators', function () { await makeGetRequest({ url: server.url, path, - statusCodeExpected: HttpStatusCode.OK_200, + expectedStatus: HttpStatusCode.OK_200, query: { state: 'accepted', actorType: 'Application' @@ -204,7 +202,7 @@ describe('Test server follows API validators', function () { await makeGetRequest({ url: server.url, path, - statusCodeExpected: HttpStatusCode.OK_200, + expectedStatus: HttpStatusCode.OK_200, query: { state: 'accepted' } @@ -220,7 +218,7 @@ describe('Test server follows API validators', function () { url: server.url, path: path + '/toto@localhost:9002', token: 'fake_token', - statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 + expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -229,7 +227,7 @@ describe('Test server follows API validators', function () { url: server.url, path: path + '/toto@localhost:9002', token: userAccessToken, - statusCodeExpected: HttpStatusCode.FORBIDDEN_403 + expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) @@ -238,7 +236,7 @@ describe('Test server follows API validators', function () { url: server.url, path: path + '/toto', token: server.accessToken, - statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 + expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) @@ -247,7 +245,7 @@ describe('Test server follows API validators', function () { url: server.url, path: path + '/toto@localhost:9003', token: server.accessToken, - statusCodeExpected: HttpStatusCode.NOT_FOUND_404 + expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) }) @@ -260,7 +258,7 @@ describe('Test server follows API validators', function () { url: server.url, path: path + '/toto@localhost:9002/accept', token: 'fake_token', - statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 + expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -269,7 +267,7 @@ describe('Test server follows API validators', function () { url: server.url, path: path + '/toto@localhost:9002/accept', token: userAccessToken, - statusCodeExpected: HttpStatusCode.FORBIDDEN_403 + expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) @@ -278,7 +276,7 @@ describe('Test server follows API validators', function () { url: server.url, path: path + '/toto/accept', token: server.accessToken, - statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 + expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) @@ -287,7 +285,7 @@ describe('Test server follows API validators', function () { url: server.url, path: path + '/toto@localhost:9003/accept', token: server.accessToken, - statusCodeExpected: HttpStatusCode.NOT_FOUND_404 + expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) }) @@ -300,7 +298,7 @@ describe('Test server follows API validators', function () { url: server.url, path: path + '/toto@localhost:9002/reject', token: 'fake_token', - statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 + expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -309,7 +307,7 @@ describe('Test server follows API validators', function () { url: server.url, path: path + '/toto@localhost:9002/reject', token: userAccessToken, - statusCodeExpected: HttpStatusCode.FORBIDDEN_403 + expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) @@ -318,7 +316,7 @@ describe('Test server follows API validators', function () { url: server.url, path: path + '/toto/reject', token: server.accessToken, - statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 + expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) @@ -327,7 +325,7 @@ describe('Test server follows API validators', function () { url: server.url, path: path + '/toto@localhost:9003/reject', token: server.accessToken, - statusCodeExpected: HttpStatusCode.NOT_FOUND_404 + expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) }) @@ -340,7 +338,7 @@ describe('Test server follows API validators', function () { url: server.url, path: path + '/localhost:9002', token: 'fake_token', - statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 + expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -349,7 +347,7 @@ describe('Test server follows API validators', function () { url: server.url, path: path + '/localhost:9002', token: userAccessToken, - statusCodeExpected: HttpStatusCode.FORBIDDEN_403 + expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) @@ -358,7 +356,7 @@ describe('Test server follows API validators', function () { url: server.url, path: path + '/example.com', token: server.accessToken, - statusCodeExpected: HttpStatusCode.NOT_FOUND_404 + expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) }) diff --git a/server/tests/api/check-params/jobs.ts b/server/tests/api/check-params/jobs.ts index a370ec2d3..23d95d8e4 100644 --- a/server/tests/api/check-params/jobs.ts +++ b/server/tests/api/check-params/jobs.ts @@ -1,20 +1,17 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ import 'mocha' - import { + checkBadCountPagination, + checkBadSortPagination, + checkBadStartPagination, cleanupTests, createSingleServer, + makeGetRequest, PeerTubeServer, setAccessTokensToServers -} from '../../../../shared/extra-utils' -import { - checkBadCountPagination, - checkBadSortPagination, - checkBadStartPagination -} from '../../../../shared/extra-utils/requests/check-api-params' -import { makeGetRequest } from '../../../../shared/extra-utils/requests/requests' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' +} from '@shared/extra-utils' +import { HttpStatusCode } from '@shared/models' describe('Test jobs API validators', function () { const path = '/api/v1/jobs/failed' @@ -75,7 +72,7 @@ describe('Test jobs API validators', function () { await makeGetRequest({ url: server.url, path, - statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 + expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -84,7 +81,7 @@ describe('Test jobs API validators', function () { url: server.url, path, token: userAccessToken, - statusCodeExpected: HttpStatusCode.FORBIDDEN_403 + expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) diff --git a/server/tests/api/check-params/live.ts b/server/tests/api/check-params/live.ts index eb5cdd1d8..0ef86a538 100644 --- a/server/tests/api/check-params/live.ts +++ b/server/tests/api/check-params/live.ts @@ -2,7 +2,7 @@ import 'mocha' import { omit } from 'lodash' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { buildAbsoluteFixturePath, cleanupTests, @@ -223,7 +223,7 @@ describe('Test video lives API validator', function () { path, token: server.accessToken, fields: baseCorrectParams, - statusCodeExpected: HttpStatusCode.OK_200 + expectedStatus: HttpStatusCode.OK_200 }) video = res.body.video @@ -243,7 +243,7 @@ describe('Test video lives API validator', function () { path, token: server.accessToken, fields: baseCorrectParams, - statusCodeExpected: HttpStatusCode.FORBIDDEN_403 + expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) @@ -264,7 +264,7 @@ describe('Test video lives API validator', function () { path, token: server.accessToken, fields, - statusCodeExpected: HttpStatusCode.FORBIDDEN_403 + expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) @@ -285,7 +285,7 @@ describe('Test video lives API validator', function () { path, token: server.accessToken, fields, - statusCodeExpected: HttpStatusCode.OK_200 + expectedStatus: HttpStatusCode.OK_200 }) }) @@ -304,7 +304,7 @@ describe('Test video lives API validator', function () { path, token: server.accessToken, fields: baseCorrectParams, - statusCodeExpected: HttpStatusCode.FORBIDDEN_403 + expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) @@ -324,7 +324,7 @@ describe('Test video lives API validator', function () { path, token: server.accessToken, fields: baseCorrectParams, - statusCodeExpected: HttpStatusCode.FORBIDDEN_403 + expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) }) diff --git a/server/tests/api/check-params/logs.ts b/server/tests/api/check-params/logs.ts index 2eb074007..05372257a 100644 --- a/server/tests/api/check-params/logs.ts +++ b/server/tests/api/check-params/logs.ts @@ -1,15 +1,8 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ import 'mocha' - -import { - cleanupTests, - createSingleServer, - PeerTubeServer, - setAccessTokensToServers -} from '../../../../shared/extra-utils' -import { makeGetRequest } from '../../../../shared/extra-utils/requests/requests' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' +import { cleanupTests, createSingleServer, makeGetRequest, PeerTubeServer, setAccessTokensToServers } from '@shared/extra-utils' +import { HttpStatusCode } from '@shared/models' describe('Test logs API validators', function () { const path = '/api/v1/server/logs' @@ -39,7 +32,7 @@ describe('Test logs API validators', function () { await makeGetRequest({ url: server.url, path, - statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 + expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -48,7 +41,7 @@ describe('Test logs API validators', function () { url: server.url, path, token: userAccessToken, - statusCodeExpected: HttpStatusCode.FORBIDDEN_403 + expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) @@ -57,7 +50,7 @@ describe('Test logs API validators', function () { url: server.url, path, token: server.accessToken, - statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 + expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) @@ -67,7 +60,7 @@ describe('Test logs API validators', function () { path, token: server.accessToken, query: { startDate: 'toto' }, - statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 + expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) @@ -77,7 +70,7 @@ describe('Test logs API validators', function () { path, token: server.accessToken, query: { startDate: new Date().toISOString(), endDate: 'toto' }, - statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 + expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) @@ -87,7 +80,7 @@ describe('Test logs API validators', function () { path, token: server.accessToken, query: { startDate: new Date().toISOString(), level: 'toto' }, - statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 + expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) @@ -97,7 +90,7 @@ describe('Test logs API validators', function () { path, token: server.accessToken, query: { startDate: new Date().toISOString() }, - statusCodeExpected: HttpStatusCode.OK_200 + expectedStatus: HttpStatusCode.OK_200 }) }) }) diff --git a/server/tests/api/check-params/plugins.ts b/server/tests/api/check-params/plugins.ts index 2b471ee7d..d3dda7fce 100644 --- a/server/tests/api/check-params/plugins.ts +++ b/server/tests/api/check-params/plugins.ts @@ -1,7 +1,7 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ import 'mocha' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { checkBadCountPagination, checkBadSortPagination, @@ -70,7 +70,7 @@ describe('Test server plugins API validators', function () { ] for (const p of paths) { - await makeGetRequest({ url: server.url, path: p, statusCodeExpected: HttpStatusCode.NOT_FOUND_404 }) + await makeGetRequest({ url: server.url, path: p, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) } }) @@ -78,7 +78,7 @@ describe('Test server plugins API validators', function () { await makeGetRequest({ url: server.url, path: '/themes/' + pluginName + '/' + npmVersion + '/static/images/chocobo.png', - statusCodeExpected: HttpStatusCode.NOT_FOUND_404 + expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) @@ -93,7 +93,7 @@ describe('Test server plugins API validators', function () { ] for (const p of paths) { - await makeGetRequest({ url: server.url, path: p, statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) + await makeGetRequest({ url: server.url, path: p, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) } }) @@ -107,14 +107,14 @@ describe('Test server plugins API validators', function () { ] for (const p of paths) { - await makeGetRequest({ url: server.url, path: p, statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) + await makeGetRequest({ url: server.url, path: p, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) } }) it('Should fail with an unknown auth name', async function () { const path = '/plugins/' + pluginName + '/' + npmVersion + '/auth/bad-auth' - await makeGetRequest({ url: server.url, path, statusCodeExpected: HttpStatusCode.NOT_FOUND_404 }) + await makeGetRequest({ url: server.url, path, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) it('Should fail with an unknown static file', async function () { @@ -126,7 +126,7 @@ describe('Test server plugins API validators', function () { ] for (const p of paths) { - await makeGetRequest({ url: server.url, path: p, statusCodeExpected: HttpStatusCode.NOT_FOUND_404 }) + await makeGetRequest({ url: server.url, path: p, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) } }) @@ -134,7 +134,7 @@ describe('Test server plugins API validators', function () { await makeGetRequest({ url: server.url, path: '/themes/' + themeName + '/' + themeVersion + '/css/assets/fake.css', - statusCodeExpected: HttpStatusCode.NOT_FOUND_404 + expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) @@ -148,11 +148,11 @@ describe('Test server plugins API validators', function () { ] for (const p of paths) { - await makeGetRequest({ url: server.url, path: p, statusCodeExpected: HttpStatusCode.OK_200 }) + await makeGetRequest({ url: server.url, path: p, expectedStatus: HttpStatusCode.OK_200 }) } const authPath = '/plugins/' + pluginName + '/' + npmVersion + '/auth/fake-auth' - await makeGetRequest({ url: server.url, path: authPath, statusCodeExpected: HttpStatusCode.FOUND_302 }) + await makeGetRequest({ url: server.url, path: authPath, expectedStatus: HttpStatusCode.FOUND_302 }) }) }) @@ -170,7 +170,7 @@ describe('Test server plugins API validators', function () { path, token: 'fake_token', query: baseQuery, - statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 + expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -180,7 +180,7 @@ describe('Test server plugins API validators', function () { path, token: userAccessToken, query: baseQuery, - statusCodeExpected: HttpStatusCode.FORBIDDEN_403 + expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) @@ -224,7 +224,7 @@ describe('Test server plugins API validators', function () { path, token: server.accessToken, query: baseQuery, - statusCodeExpected: HttpStatusCode.OK_200 + expectedStatus: HttpStatusCode.OK_200 }) }) }) @@ -241,7 +241,7 @@ describe('Test server plugins API validators', function () { path, token: 'fake_token', query: baseQuery, - statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 + expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -251,7 +251,7 @@ describe('Test server plugins API validators', function () { path, token: userAccessToken, query: baseQuery, - statusCodeExpected: HttpStatusCode.FORBIDDEN_403 + expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) @@ -284,7 +284,7 @@ describe('Test server plugins API validators', function () { path, token: server.accessToken, query: baseQuery, - statusCodeExpected: HttpStatusCode.OK_200 + expectedStatus: HttpStatusCode.OK_200 }) }) }) @@ -298,7 +298,7 @@ describe('Test server plugins API validators', function () { url: server.url, path: path + suffix, token: 'fake_token', - statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 + expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) } }) @@ -309,7 +309,7 @@ describe('Test server plugins API validators', function () { url: server.url, path: path + suffix, token: userAccessToken, - statusCodeExpected: HttpStatusCode.FORBIDDEN_403 + expectedStatus: HttpStatusCode.FORBIDDEN_403 }) } }) @@ -320,7 +320,7 @@ describe('Test server plugins API validators', function () { url: server.url, path: path + suffix, token: server.accessToken, - statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 + expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) } @@ -329,7 +329,7 @@ describe('Test server plugins API validators', function () { url: server.url, path: path + suffix, token: server.accessToken, - statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 + expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) } }) @@ -340,7 +340,7 @@ describe('Test server plugins API validators', function () { url: server.url, path: path + suffix, token: server.accessToken, - statusCodeExpected: HttpStatusCode.NOT_FOUND_404 + expectedStatus: HttpStatusCode.NOT_FOUND_404 }) } }) @@ -351,7 +351,7 @@ describe('Test server plugins API validators', function () { url: server.url, path: path + suffix, token: server.accessToken, - statusCodeExpected: HttpStatusCode.OK_200 + expectedStatus: HttpStatusCode.OK_200 }) } }) @@ -367,7 +367,7 @@ describe('Test server plugins API validators', function () { path: path + npmPlugin + '/settings', fields: { settings }, token: 'fake_token', - statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 + expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -377,7 +377,7 @@ describe('Test server plugins API validators', function () { path: path + npmPlugin + '/settings', fields: { settings }, token: userAccessToken, - statusCodeExpected: HttpStatusCode.FORBIDDEN_403 + expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) @@ -387,7 +387,7 @@ describe('Test server plugins API validators', function () { path: path + 'toto/settings', fields: { settings }, token: server.accessToken, - statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 + expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) await makePutBodyRequest({ @@ -395,7 +395,7 @@ describe('Test server plugins API validators', function () { path: path + 'peertube-plugin-TOTO/settings', fields: { settings }, token: server.accessToken, - statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 + expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) @@ -405,7 +405,7 @@ describe('Test server plugins API validators', function () { path: path + 'peertube-plugin-toto/settings', fields: { settings }, token: server.accessToken, - statusCodeExpected: HttpStatusCode.NOT_FOUND_404 + expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) @@ -415,7 +415,7 @@ describe('Test server plugins API validators', function () { path: path + npmPlugin + '/settings', fields: { settings }, token: server.accessToken, - statusCodeExpected: HttpStatusCode.NO_CONTENT_204 + expectedStatus: HttpStatusCode.NO_CONTENT_204 }) }) }) @@ -430,7 +430,7 @@ describe('Test server plugins API validators', function () { path: path + suffix, fields: { npmName: npmPlugin }, token: 'fake_token', - statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 + expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) } }) @@ -442,7 +442,7 @@ describe('Test server plugins API validators', function () { path: path + suffix, fields: { npmName: npmPlugin }, token: userAccessToken, - statusCodeExpected: HttpStatusCode.FORBIDDEN_403 + expectedStatus: HttpStatusCode.FORBIDDEN_403 }) } }) @@ -454,7 +454,7 @@ describe('Test server plugins API validators', function () { path: path + suffix, fields: { npmName: 'toto' }, token: server.accessToken, - statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 + expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) } @@ -464,7 +464,7 @@ describe('Test server plugins API validators', function () { path: path + suffix, fields: { npmName: 'peertube-plugin-TOTO' }, token: server.accessToken, - statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 + expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) } }) @@ -484,7 +484,7 @@ describe('Test server plugins API validators', function () { path: path + obj.suffix, fields: { npmName: npmPlugin }, token: server.accessToken, - statusCodeExpected: obj.status + expectedStatus: obj.status }) } }) diff --git a/server/tests/api/check-params/redundancy.ts b/server/tests/api/check-params/redundancy.ts index 18b98a0f9..d9f905549 100644 --- a/server/tests/api/check-params/redundancy.ts +++ b/server/tests/api/check-params/redundancy.ts @@ -1,15 +1,13 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ import 'mocha' -import { VideoCreateResult } from '@shared/models' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' import { checkBadCountPagination, checkBadSortPagination, checkBadStartPagination, cleanupTests, - doubleFollow, createMultipleServers, + doubleFollow, makeDeleteRequest, makeGetRequest, makePostBodyRequest, @@ -17,7 +15,8 @@ import { PeerTubeServer, setAccessTokensToServers, waitJobs -} from '../../../../shared/extra-utils' +} from '@shared/extra-utils' +import { HttpStatusCode, VideoCreateResult } from '@shared/models' describe('Test server redundancy API validators', function () { let servers: PeerTubeServer[] @@ -64,11 +63,11 @@ describe('Test server redundancy API validators', function () { }) it('Should fail with an invalid token', async function () { - await makeGetRequest({ url, path, token: 'fake_token', statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) + await makeGetRequest({ url, path, token: 'fake_token', expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should fail if the user is not an administrator', async function () { - await makeGetRequest({ url, path, token: userAccessToken, statusCodeExpected: HttpStatusCode.FORBIDDEN_403 }) + await makeGetRequest({ url, path, token: userAccessToken, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) it('Should fail with a bad start pagination', async function () { @@ -92,7 +91,7 @@ describe('Test server redundancy API validators', function () { }) it('Should succeed with the correct params', async function () { - await makeGetRequest({ url, path, token, query: { target: 'my-videos' }, statusCodeExpected: HttpStatusCode.OK_200 }) + await makeGetRequest({ url, path, token, query: { target: 'my-videos' }, expectedStatus: HttpStatusCode.OK_200 }) }) }) @@ -108,11 +107,11 @@ describe('Test server redundancy API validators', function () { }) it('Should fail with an invalid token', async function () { - await makePostBodyRequest({ url, path, token: 'fake_token', statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) + await makePostBodyRequest({ url, path, token: 'fake_token', expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should fail if the user is not an administrator', async function () { - await makePostBodyRequest({ url, path, token: userAccessToken, statusCodeExpected: HttpStatusCode.FORBIDDEN_403 }) + await makePostBodyRequest({ url, path, token: userAccessToken, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) it('Should fail without a video id', async function () { @@ -124,7 +123,7 @@ describe('Test server redundancy API validators', function () { }) it('Should fail with a not found video id', async function () { - await makePostBodyRequest({ url, path, token, fields: { videoId: 6565 }, statusCodeExpected: HttpStatusCode.NOT_FOUND_404 }) + await makePostBodyRequest({ url, path, token, fields: { videoId: 6565 }, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) it('Should fail with a local a video id', async function () { @@ -137,7 +136,7 @@ describe('Test server redundancy API validators', function () { path, token, fields: { videoId: videoRemote.shortUUID }, - statusCodeExpected: HttpStatusCode.NO_CONTENT_204 + expectedStatus: HttpStatusCode.NO_CONTENT_204 }) }) @@ -151,7 +150,7 @@ describe('Test server redundancy API validators', function () { path, token, fields: { videoId: videoRemote.uuid }, - statusCodeExpected: HttpStatusCode.CONFLICT_409 + expectedStatus: HttpStatusCode.CONFLICT_409 }) }) }) @@ -168,11 +167,11 @@ describe('Test server redundancy API validators', function () { }) it('Should fail with an invalid token', async function () { - await makeDeleteRequest({ url, path: path + '1', token: 'fake_token', statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) + await makeDeleteRequest({ url, path: path + '1', token: 'fake_token', expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should fail if the user is not an administrator', async function () { - await makeDeleteRequest({ url, path: path + '1', token: userAccessToken, statusCodeExpected: HttpStatusCode.FORBIDDEN_403 }) + await makeDeleteRequest({ url, path: path + '1', token: userAccessToken, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) it('Should fail with an incorrect video id', async function () { @@ -180,7 +179,7 @@ describe('Test server redundancy API validators', function () { }) it('Should fail with a not found video redundancy', async function () { - await makeDeleteRequest({ url, path: path + '454545', token, statusCodeExpected: HttpStatusCode.NOT_FOUND_404 }) + await makeDeleteRequest({ url, path: path + '454545', token, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) }) @@ -193,7 +192,7 @@ describe('Test server redundancy API validators', function () { path: path + '/localhost:' + servers[1].port, fields: { redundancyAllowed: true }, token: 'fake_token', - statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 + expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -203,7 +202,7 @@ describe('Test server redundancy API validators', function () { path: path + '/localhost:' + servers[1].port, fields: { redundancyAllowed: true }, token: userAccessToken, - statusCodeExpected: HttpStatusCode.FORBIDDEN_403 + expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) @@ -213,7 +212,7 @@ describe('Test server redundancy API validators', function () { path: path + '/example.com', fields: { redundancyAllowed: true }, token: servers[0].accessToken, - statusCodeExpected: HttpStatusCode.NOT_FOUND_404 + expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) @@ -223,7 +222,7 @@ describe('Test server redundancy API validators', function () { path: path + '/localhost:' + servers[1].port, fields: { blabla: true }, token: servers[0].accessToken, - statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 + expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) @@ -233,7 +232,7 @@ describe('Test server redundancy API validators', function () { path: path + '/localhost:' + servers[1].port, fields: { redundancyAllowed: true }, token: servers[0].accessToken, - statusCodeExpected: HttpStatusCode.NO_CONTENT_204 + expectedStatus: HttpStatusCode.NO_CONTENT_204 }) }) }) diff --git a/server/tests/api/check-params/search.ts b/server/tests/api/check-params/search.ts index 43cd81af9..b49169e38 100644 --- a/server/tests/api/check-params/search.ts +++ b/server/tests/api/check-params/search.ts @@ -1,7 +1,7 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ import 'mocha' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { checkBadCountPagination, checkBadSortPagination, @@ -58,83 +58,83 @@ describe('Test videos API validator', function () { }) it('Should success with the correct parameters', async function () { - await makeGetRequest({ url: server.url, path, query, statusCodeExpected: HttpStatusCode.OK_200 }) + await makeGetRequest({ url: server.url, path, query, expectedStatus: HttpStatusCode.OK_200 }) }) it('Should fail with an invalid category', async function () { const customQuery1 = { ...query, categoryOneOf: [ 'aa', 'b' ] } - await makeGetRequest({ url: server.url, path, query: customQuery1, statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) + await makeGetRequest({ url: server.url, path, query: customQuery1, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) const customQuery2 = { ...query, categoryOneOf: 'a' } - await makeGetRequest({ url: server.url, path, query: customQuery2, statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) + await makeGetRequest({ url: server.url, path, query: customQuery2, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) it('Should succeed with a valid category', async function () { const customQuery1 = { ...query, categoryOneOf: [ 1, 7 ] } - await makeGetRequest({ url: server.url, path, query: customQuery1, statusCodeExpected: HttpStatusCode.OK_200 }) + await makeGetRequest({ url: server.url, path, query: customQuery1, expectedStatus: HttpStatusCode.OK_200 }) const customQuery2 = { ...query, categoryOneOf: 1 } - await makeGetRequest({ url: server.url, path, query: customQuery2, statusCodeExpected: HttpStatusCode.OK_200 }) + await makeGetRequest({ url: server.url, path, query: customQuery2, expectedStatus: HttpStatusCode.OK_200 }) }) it('Should fail with an invalid licence', async function () { const customQuery1 = { ...query, licenceOneOf: [ 'aa', 'b' ] } - await makeGetRequest({ url: server.url, path, query: customQuery1, statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) + await makeGetRequest({ url: server.url, path, query: customQuery1, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) const customQuery2 = { ...query, licenceOneOf: 'a' } - await makeGetRequest({ url: server.url, path, query: customQuery2, statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) + await makeGetRequest({ url: server.url, path, query: customQuery2, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) it('Should succeed with a valid licence', async function () { const customQuery1 = { ...query, licenceOneOf: [ 1, 2 ] } - await makeGetRequest({ url: server.url, path, query: customQuery1, statusCodeExpected: HttpStatusCode.OK_200 }) + await makeGetRequest({ url: server.url, path, query: customQuery1, expectedStatus: HttpStatusCode.OK_200 }) const customQuery2 = { ...query, licenceOneOf: 1 } - await makeGetRequest({ url: server.url, path, query: customQuery2, statusCodeExpected: HttpStatusCode.OK_200 }) + await makeGetRequest({ url: server.url, path, query: customQuery2, expectedStatus: HttpStatusCode.OK_200 }) }) it('Should succeed with a valid language', async function () { const customQuery1 = { ...query, languageOneOf: [ 'fr', 'en' ] } - await makeGetRequest({ url: server.url, path, query: customQuery1, statusCodeExpected: HttpStatusCode.OK_200 }) + await makeGetRequest({ url: server.url, path, query: customQuery1, expectedStatus: HttpStatusCode.OK_200 }) const customQuery2 = { ...query, languageOneOf: 'fr' } - await makeGetRequest({ url: server.url, path, query: customQuery2, statusCodeExpected: HttpStatusCode.OK_200 }) + await makeGetRequest({ url: server.url, path, query: customQuery2, expectedStatus: HttpStatusCode.OK_200 }) }) it('Should succeed with valid tags', async function () { const customQuery1 = { ...query, tagsOneOf: [ 'tag1', 'tag2' ] } - await makeGetRequest({ url: server.url, path, query: customQuery1, statusCodeExpected: HttpStatusCode.OK_200 }) + await makeGetRequest({ url: server.url, path, query: customQuery1, expectedStatus: HttpStatusCode.OK_200 }) const customQuery2 = { ...query, tagsOneOf: 'tag1' } - await makeGetRequest({ url: server.url, path, query: customQuery2, statusCodeExpected: HttpStatusCode.OK_200 }) + await makeGetRequest({ url: server.url, path, query: customQuery2, expectedStatus: HttpStatusCode.OK_200 }) const customQuery3 = { ...query, tagsAllOf: [ 'tag1', 'tag2' ] } - await makeGetRequest({ url: server.url, path, query: customQuery3, statusCodeExpected: HttpStatusCode.OK_200 }) + await makeGetRequest({ url: server.url, path, query: customQuery3, expectedStatus: HttpStatusCode.OK_200 }) const customQuery4 = { ...query, tagsAllOf: 'tag1' } - await makeGetRequest({ url: server.url, path, query: customQuery4, statusCodeExpected: HttpStatusCode.OK_200 }) + await makeGetRequest({ url: server.url, path, query: customQuery4, expectedStatus: HttpStatusCode.OK_200 }) }) it('Should fail with invalid durations', async function () { const customQuery1 = { ...query, durationMin: 'hello' } - await makeGetRequest({ url: server.url, path, query: customQuery1, statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) + await makeGetRequest({ url: server.url, path, query: customQuery1, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) const customQuery2 = { ...query, durationMax: 'hello' } - await makeGetRequest({ url: server.url, path, query: customQuery2, statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) + await makeGetRequest({ url: server.url, path, query: customQuery2, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) it('Should fail with invalid dates', async function () { const customQuery1 = { ...query, startDate: 'hello' } - await makeGetRequest({ url: server.url, path, query: customQuery1, statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) + await makeGetRequest({ url: server.url, path, query: customQuery1, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) const customQuery2 = { ...query, endDate: 'hello' } - await makeGetRequest({ url: server.url, path, query: customQuery2, statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) + await makeGetRequest({ url: server.url, path, query: customQuery2, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) const customQuery3 = { ...query, originallyPublishedStartDate: 'hello' } - await makeGetRequest({ url: server.url, path, query: customQuery3, statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) + await makeGetRequest({ url: server.url, path, query: customQuery3, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) const customQuery4 = { ...query, originallyPublishedEndDate: 'hello' } - await makeGetRequest({ url: server.url, path, query: customQuery4, statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) + await makeGetRequest({ url: server.url, path, query: customQuery4, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) }) @@ -158,7 +158,7 @@ describe('Test videos API validator', function () { }) it('Should success with the correct parameters', async function () { - await makeGetRequest({ url: server.url, path, query, statusCodeExpected: HttpStatusCode.OK_200 }) + await makeGetRequest({ url: server.url, path, query, expectedStatus: HttpStatusCode.OK_200 }) }) }) @@ -182,7 +182,7 @@ describe('Test videos API validator', function () { }) it('Should success with the correct parameters', async function () { - await makeGetRequest({ url: server.url, path, query, statusCodeExpected: HttpStatusCode.OK_200 }) + await makeGetRequest({ url: server.url, path, query, expectedStatus: HttpStatusCode.OK_200 }) }) }) @@ -201,41 +201,41 @@ describe('Test videos API validator', function () { for (const path of paths) { { const customQuery = { ...query, searchTarget: 'hello' } - await makeGetRequest({ url: server.url, path, query: customQuery, statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) + await makeGetRequest({ url: server.url, path, query: customQuery, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) } { const customQuery = { ...query, searchTarget: undefined } - await makeGetRequest({ url: server.url, path, query: customQuery, statusCodeExpected: HttpStatusCode.OK_200 }) + await makeGetRequest({ url: server.url, path, query: customQuery, expectedStatus: HttpStatusCode.OK_200 }) } { const customQuery = { ...query, searchTarget: 'local' } - await makeGetRequest({ url: server.url, path, query: customQuery, statusCodeExpected: HttpStatusCode.OK_200 }) + await makeGetRequest({ url: server.url, path, query: customQuery, expectedStatus: HttpStatusCode.OK_200 }) } { const customQuery = { ...query, searchTarget: 'search-index' } - await makeGetRequest({ url: server.url, path, query: customQuery, statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) + await makeGetRequest({ url: server.url, path, query: customQuery, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) } await updateSearchIndex(server, true, true) { const customQuery = { ...query, searchTarget: 'local' } - await makeGetRequest({ url: server.url, path, query: customQuery, statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) + await makeGetRequest({ url: server.url, path, query: customQuery, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) } { const customQuery = { ...query, searchTarget: 'search-index' } - await makeGetRequest({ url: server.url, path, query: customQuery, statusCodeExpected: HttpStatusCode.OK_200 }) + await makeGetRequest({ url: server.url, path, query: customQuery, expectedStatus: HttpStatusCode.OK_200 }) } await updateSearchIndex(server, true, false) { const customQuery = { ...query, searchTarget: 'local' } - await makeGetRequest({ url: server.url, path, query: customQuery, statusCodeExpected: HttpStatusCode.OK_200 }) + await makeGetRequest({ url: server.url, path, query: customQuery, expectedStatus: HttpStatusCode.OK_200 }) } await updateSearchIndex(server, false, false) diff --git a/server/tests/api/check-params/services.ts b/server/tests/api/check-params/services.ts index c623240b7..973b25598 100644 --- a/server/tests/api/check-params/services.ts +++ b/server/tests/api/check-params/services.ts @@ -1,7 +1,7 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ import 'mocha' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { cleanupTests, createSingleServer, @@ -120,13 +120,13 @@ describe('Test services API validators', function () { }) }) -function checkParamEmbed (server: PeerTubeServer, embedUrl: string, statusCodeExpected = HttpStatusCode.BAD_REQUEST_400, query = {}) { +function checkParamEmbed (server: PeerTubeServer, embedUrl: string, expectedStatus = HttpStatusCode.BAD_REQUEST_400, query = {}) { const path = '/services/oembed' return makeGetRequest({ url: server.url, path, query: Object.assign(query, { url: embedUrl }), - statusCodeExpected + expectedStatus }) } diff --git a/server/tests/api/check-params/upload-quota.ts b/server/tests/api/check-params/upload-quota.ts index bd8dce975..322e93d0d 100644 --- a/server/tests/api/check-params/upload-quota.ts +++ b/server/tests/api/check-params/upload-quota.ts @@ -2,7 +2,7 @@ import 'mocha' import { expect } from 'chai' -import { HttpStatusCode, randomInt } from '@shared/core-utils' +import { randomInt } from '@shared/core-utils' import { cleanupTests, createSingleServer, @@ -13,7 +13,7 @@ import { VideosCommand, waitJobs } from '@shared/extra-utils' -import { VideoImportState, VideoPrivacy } from '@shared/models' +import { HttpStatusCode, VideoImportState, VideoPrivacy } from '@shared/models' describe('Test upload quota', function () { let server: PeerTubeServer diff --git a/server/tests/api/check-params/user-notifications.ts b/server/tests/api/check-params/user-notifications.ts index 038c444b3..3b709ee5a 100644 --- a/server/tests/api/check-params/user-notifications.ts +++ b/server/tests/api/check-params/user-notifications.ts @@ -2,7 +2,7 @@ import 'mocha' import { io } from 'socket.io-client' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { checkBadCountPagination, checkBadSortPagination, @@ -54,7 +54,7 @@ describe('Test user notifications API validators', function () { unread: 'toto' }, token: server.accessToken, - statusCodeExpected: HttpStatusCode.OK_200 + expectedStatus: HttpStatusCode.OK_200 }) }) @@ -62,7 +62,7 @@ describe('Test user notifications API validators', function () { await makeGetRequest({ url: server.url, path, - statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 + expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -71,7 +71,7 @@ describe('Test user notifications API validators', function () { url: server.url, path, token: server.accessToken, - statusCodeExpected: HttpStatusCode.OK_200 + expectedStatus: HttpStatusCode.OK_200 }) }) }) @@ -87,7 +87,7 @@ describe('Test user notifications API validators', function () { ids: [ 'hello' ] }, token: server.accessToken, - statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 + expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) await makePostBodyRequest({ @@ -97,7 +97,7 @@ describe('Test user notifications API validators', function () { ids: [ ] }, token: server.accessToken, - statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 + expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) await makePostBodyRequest({ @@ -107,7 +107,7 @@ describe('Test user notifications API validators', function () { ids: 5 }, token: server.accessToken, - statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 + expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) @@ -118,7 +118,7 @@ describe('Test user notifications API validators', function () { fields: { ids: [ 5 ] }, - statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 + expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -130,7 +130,7 @@ describe('Test user notifications API validators', function () { ids: [ 5 ] }, token: server.accessToken, - statusCodeExpected: HttpStatusCode.NO_CONTENT_204 + expectedStatus: HttpStatusCode.NO_CONTENT_204 }) }) }) @@ -142,7 +142,7 @@ describe('Test user notifications API validators', function () { await makePostBodyRequest({ url: server.url, path, - statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 + expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -151,7 +151,7 @@ describe('Test user notifications API validators', function () { url: server.url, path, token: server.accessToken, - statusCodeExpected: HttpStatusCode.NO_CONTENT_204 + expectedStatus: HttpStatusCode.NO_CONTENT_204 }) }) }) @@ -183,7 +183,7 @@ describe('Test user notifications API validators', function () { path, token: server.accessToken, fields: { newVideoFromSubscription: UserNotificationSettingValue.WEB }, - statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 + expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) @@ -196,7 +196,7 @@ describe('Test user notifications API validators', function () { path, token: server.accessToken, fields, - statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 + expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) } @@ -208,7 +208,7 @@ describe('Test user notifications API validators', function () { path, fields, token: server.accessToken, - statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 + expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) } }) @@ -218,7 +218,7 @@ describe('Test user notifications API validators', function () { url: server.url, path, fields: correctFields, - statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 + expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -228,7 +228,7 @@ describe('Test user notifications API validators', function () { path, token: server.accessToken, fields: correctFields, - statusCodeExpected: HttpStatusCode.NO_CONTENT_204 + expectedStatus: HttpStatusCode.NO_CONTENT_204 }) }) }) diff --git a/server/tests/api/check-params/user-subscriptions.ts b/server/tests/api/check-params/user-subscriptions.ts index 22cf130c2..624069c80 100644 --- a/server/tests/api/check-params/user-subscriptions.ts +++ b/server/tests/api/check-params/user-subscriptions.ts @@ -1,24 +1,20 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ import 'mocha' - import { + checkBadCountPagination, + checkBadSortPagination, + checkBadStartPagination, cleanupTests, createSingleServer, makeDeleteRequest, makeGetRequest, makePostBodyRequest, PeerTubeServer, - setAccessTokensToServers -} from '../../../../shared/extra-utils' - -import { - checkBadCountPagination, - checkBadSortPagination, - checkBadStartPagination -} from '../../../../shared/extra-utils/requests/check-api-params' -import { waitJobs } from '../../../../shared/extra-utils/server/jobs' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' + setAccessTokensToServers, + waitJobs +} from '@shared/extra-utils' +import { HttpStatusCode } from '@shared/models' describe('Test user subscriptions API validators', function () { const path = '/api/v1/users/me/subscriptions' @@ -59,7 +55,7 @@ describe('Test user subscriptions API validators', function () { await makeGetRequest({ url: server.url, path, - statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 + expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -68,7 +64,7 @@ describe('Test user subscriptions API validators', function () { url: server.url, path, token: userAccessToken, - statusCodeExpected: HttpStatusCode.OK_200 + expectedStatus: HttpStatusCode.OK_200 }) }) }) @@ -92,7 +88,7 @@ describe('Test user subscriptions API validators', function () { await makeGetRequest({ url: server.url, path, - statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 + expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -101,7 +97,7 @@ describe('Test user subscriptions API validators', function () { url: server.url, path, token: userAccessToken, - statusCodeExpected: HttpStatusCode.OK_200 + expectedStatus: HttpStatusCode.OK_200 }) }) }) @@ -112,7 +108,7 @@ describe('Test user subscriptions API validators', function () { url: server.url, path, fields: { uri: 'user1_channel@localhost:' + server.port }, - statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 + expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -122,7 +118,7 @@ describe('Test user subscriptions API validators', function () { path, token: server.accessToken, fields: { uri: 'root' }, - statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 + expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) await makePostBodyRequest({ @@ -130,7 +126,7 @@ describe('Test user subscriptions API validators', function () { path, token: server.accessToken, fields: { uri: 'root@' }, - statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 + expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) await makePostBodyRequest({ @@ -138,7 +134,7 @@ describe('Test user subscriptions API validators', function () { path, token: server.accessToken, fields: { uri: 'root@hello@' }, - statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 + expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) @@ -150,7 +146,7 @@ describe('Test user subscriptions API validators', function () { path, token: server.accessToken, fields: { uri: 'user1_channel@localhost:' + server.port }, - statusCodeExpected: HttpStatusCode.NO_CONTENT_204 + expectedStatus: HttpStatusCode.NO_CONTENT_204 }) await waitJobs([ server ]) @@ -162,7 +158,7 @@ describe('Test user subscriptions API validators', function () { await makeGetRequest({ url: server.url, path: path + '/user1_channel@localhost:' + server.port, - statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 + expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -171,21 +167,21 @@ describe('Test user subscriptions API validators', function () { url: server.url, path: path + '/root', token: server.accessToken, - statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 + expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) await makeGetRequest({ url: server.url, path: path + '/root@', token: server.accessToken, - statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 + expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) await makeGetRequest({ url: server.url, path: path + '/root@hello@', token: server.accessToken, - statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 + expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) @@ -194,7 +190,7 @@ describe('Test user subscriptions API validators', function () { url: server.url, path: path + '/root1@localhost:' + server.port, token: server.accessToken, - statusCodeExpected: HttpStatusCode.NOT_FOUND_404 + expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) @@ -203,7 +199,7 @@ describe('Test user subscriptions API validators', function () { url: server.url, path: path + '/user1_channel@localhost:' + server.port, token: server.accessToken, - statusCodeExpected: HttpStatusCode.OK_200 + expectedStatus: HttpStatusCode.OK_200 }) }) }) @@ -215,7 +211,7 @@ describe('Test user subscriptions API validators', function () { await makeGetRequest({ url: server.url, path: existPath, - statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 + expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -225,7 +221,7 @@ describe('Test user subscriptions API validators', function () { path: existPath, query: { uris: 'toto' }, token: server.accessToken, - statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 + expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) await makeGetRequest({ @@ -233,7 +229,7 @@ describe('Test user subscriptions API validators', function () { path: existPath, query: { 'uris[]': 1 }, token: server.accessToken, - statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 + expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) @@ -243,7 +239,7 @@ describe('Test user subscriptions API validators', function () { path: existPath, query: { 'uris[]': 'coucou@localhost:' + server.port }, token: server.accessToken, - statusCodeExpected: HttpStatusCode.OK_200 + expectedStatus: HttpStatusCode.OK_200 }) }) }) @@ -253,7 +249,7 @@ describe('Test user subscriptions API validators', function () { await makeDeleteRequest({ url: server.url, path: path + '/user1_channel@localhost:' + server.port, - statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 + expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -262,21 +258,21 @@ describe('Test user subscriptions API validators', function () { url: server.url, path: path + '/root', token: server.accessToken, - statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 + expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) await makeDeleteRequest({ url: server.url, path: path + '/root@', token: server.accessToken, - statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 + expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) await makeDeleteRequest({ url: server.url, path: path + '/root@hello@', token: server.accessToken, - statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 + expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) @@ -285,7 +281,7 @@ describe('Test user subscriptions API validators', function () { url: server.url, path: path + '/root1@localhost:' + server.port, token: server.accessToken, - statusCodeExpected: HttpStatusCode.NOT_FOUND_404 + expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) @@ -294,7 +290,7 @@ describe('Test user subscriptions API validators', function () { url: server.url, path: path + '/user1_channel@localhost:' + server.port, token: server.accessToken, - statusCodeExpected: HttpStatusCode.NO_CONTENT_204 + expectedStatus: HttpStatusCode.NO_CONTENT_204 }) }) }) diff --git a/server/tests/api/check-params/users.ts b/server/tests/api/check-params/users.ts index c2c98f429..34fe309f9 100644 --- a/server/tests/api/check-params/users.ts +++ b/server/tests/api/check-params/users.ts @@ -2,7 +2,7 @@ import 'mocha' import { omit } from 'lodash' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { buildAbsoluteFixturePath, checkBadCountPagination, @@ -103,7 +103,7 @@ describe('Test users API validators', function () { await makeGetRequest({ url: server.url, path, - statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 + expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -112,7 +112,7 @@ describe('Test users API validators', function () { url: server.url, path, token: userToken, - statusCodeExpected: HttpStatusCode.FORBIDDEN_403 + expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) }) @@ -210,7 +210,7 @@ describe('Test users API validators', function () { path: path, token: server.accessToken, fields, - statusCodeExpected: HttpStatusCode.OK_200 + expectedStatus: HttpStatusCode.OK_200 }) }) @@ -226,7 +226,7 @@ describe('Test users API validators', function () { path, token: 'super token', fields: baseCorrectParams, - statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 + expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -238,7 +238,7 @@ describe('Test users API validators', function () { path, token: server.accessToken, fields, - statusCodeExpected: HttpStatusCode.CONFLICT_409 + expectedStatus: HttpStatusCode.CONFLICT_409 }) }) @@ -250,7 +250,7 @@ describe('Test users API validators', function () { path, token: server.accessToken, fields, - statusCodeExpected: HttpStatusCode.CONFLICT_409 + expectedStatus: HttpStatusCode.CONFLICT_409 }) }) @@ -298,7 +298,7 @@ describe('Test users API validators', function () { path, token: server.accessToken, fields, - statusCodeExpected: HttpStatusCode.CONFLICT_409 + expectedStatus: HttpStatusCode.CONFLICT_409 }) }) @@ -311,7 +311,7 @@ describe('Test users API validators', function () { path, token: moderatorToken, fields, - statusCodeExpected: HttpStatusCode.FORBIDDEN_403 + expectedStatus: HttpStatusCode.FORBIDDEN_403 }) } }) @@ -324,7 +324,7 @@ describe('Test users API validators', function () { path, token: moderatorToken, fields, - statusCodeExpected: HttpStatusCode.OK_200 + expectedStatus: HttpStatusCode.OK_200 }) }) @@ -334,7 +334,7 @@ describe('Test users API validators', function () { path, token: server.accessToken, fields: baseCorrectParams, - statusCodeExpected: HttpStatusCode.OK_200 + expectedStatus: HttpStatusCode.OK_200 }) }) @@ -348,7 +348,7 @@ describe('Test users API validators', function () { password: 'my super password', videoQuota: 42000000 } - await makePostBodyRequest({ url: server.url, path, token: userToken, fields, statusCodeExpected: HttpStatusCode.FORBIDDEN_403 }) + await makePostBodyRequest({ url: server.url, path, token: userToken, fields, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) }) @@ -400,7 +400,7 @@ describe('Test users API validators', function () { path: path + 'me', token: userToken, fields, - statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 + expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -447,7 +447,7 @@ describe('Test users API validators', function () { path: path + 'me', token: 'super token', fields, - statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 + expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -525,7 +525,7 @@ describe('Test users API validators', function () { path: path + 'me', token: userToken, fields, - statusCodeExpected: HttpStatusCode.NO_CONTENT_204 + expectedStatus: HttpStatusCode.NO_CONTENT_204 }) }) @@ -540,7 +540,7 @@ describe('Test users API validators', function () { path: path + 'me', token: userToken, fields, - statusCodeExpected: HttpStatusCode.NO_CONTENT_204 + expectedStatus: HttpStatusCode.NO_CONTENT_204 }) }) }) @@ -572,7 +572,7 @@ describe('Test users API validators', function () { path: path + '/me/avatar/pick', fields, attaches, - statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 + expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -587,7 +587,7 @@ describe('Test users API validators', function () { token: server.accessToken, fields, attaches, - statusCodeExpected: HttpStatusCode.OK_200 + expectedStatus: HttpStatusCode.OK_200 }) }) }) @@ -627,16 +627,16 @@ describe('Test users API validators', function () { url: server.url, path: path + userId, token: 'super token', - statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 + expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should fail with a non admin user', async function () { - await makeGetRequest({ url: server.url, path, token: userToken, statusCodeExpected: HttpStatusCode.FORBIDDEN_403 }) + await makeGetRequest({ url: server.url, path, token: userToken, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) it('Should succeed with the correct params', async function () { - await makeGetRequest({ url: server.url, path: path + userId, token: server.accessToken, statusCodeExpected: HttpStatusCode.OK_200 }) + await makeGetRequest({ url: server.url, path: path + userId, token: server.accessToken, expectedStatus: HttpStatusCode.OK_200 }) }) }) @@ -702,7 +702,7 @@ describe('Test users API validators', function () { path: path + userId, token: 'super token', fields, - statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 + expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -730,7 +730,7 @@ describe('Test users API validators', function () { path: path + moderatorId, token: moderatorToken, fields, - statusCodeExpected: HttpStatusCode.FORBIDDEN_403 + expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) @@ -744,7 +744,7 @@ describe('Test users API validators', function () { path: path + userId, token: moderatorToken, fields, - statusCodeExpected: HttpStatusCode.NO_CONTENT_204 + expectedStatus: HttpStatusCode.NO_CONTENT_204 }) }) @@ -761,7 +761,7 @@ describe('Test users API validators', function () { path: path + userId, token: server.accessToken, fields, - statusCodeExpected: HttpStatusCode.NO_CONTENT_204 + expectedStatus: HttpStatusCode.NO_CONTENT_204 }) }) }) @@ -818,11 +818,11 @@ describe('Test users API validators', function () { }) it('Should fail with a unauthenticated user', async function () { - await makeGetRequest({ url: server.url, path, statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) + await makeGetRequest({ url: server.url, path, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should fail with a another user', async function () { - await makeGetRequest({ url: server.url, path, token: server.accessToken, statusCodeExpected: HttpStatusCode.FORBIDDEN_403 }) + await makeGetRequest({ url: server.url, path, token: server.accessToken, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) it('Should fail with a bad type', async function () { @@ -831,12 +831,12 @@ describe('Test users API validators', function () { path, token: userToken, query: { rating: 'toto ' }, - statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 + expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) it('Should succeed with the correct params', async function () { - await makeGetRequest({ url: server.url, path, token: userToken, statusCodeExpected: HttpStatusCode.OK_200 }) + await makeGetRequest({ url: server.url, path, token: userToken, expectedStatus: HttpStatusCode.OK_200 }) }) }) @@ -955,7 +955,7 @@ describe('Test users API validators', function () { path: registrationPath, token: server.accessToken, fields, - statusCodeExpected: HttpStatusCode.CONFLICT_409 + expectedStatus: HttpStatusCode.CONFLICT_409 }) }) @@ -967,7 +967,7 @@ describe('Test users API validators', function () { path: registrationPath, token: server.accessToken, fields, - statusCodeExpected: HttpStatusCode.CONFLICT_409 + expectedStatus: HttpStatusCode.CONFLICT_409 }) }) @@ -979,7 +979,7 @@ describe('Test users API validators', function () { path: registrationPath, token: server.accessToken, fields, - statusCodeExpected: HttpStatusCode.CONFLICT_409 + expectedStatus: HttpStatusCode.CONFLICT_409 }) }) @@ -1019,7 +1019,7 @@ describe('Test users API validators', function () { path: registrationPath, token: server.accessToken, fields, - statusCodeExpected: HttpStatusCode.CONFLICT_409 + expectedStatus: HttpStatusCode.CONFLICT_409 }) }) @@ -1031,7 +1031,7 @@ describe('Test users API validators', function () { path: registrationPath, token: server.accessToken, fields: fields, - statusCodeExpected: HttpStatusCode.NO_CONTENT_204 + expectedStatus: HttpStatusCode.NO_CONTENT_204 }) }) @@ -1047,7 +1047,7 @@ describe('Test users API validators', function () { path: registrationPath, token: serverWithRegistrationDisabled.accessToken, fields, - statusCodeExpected: HttpStatusCode.FORBIDDEN_403 + expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) }) @@ -1081,7 +1081,7 @@ describe('Test users API validators', function () { path, token: server.accessToken, fields, - statusCodeExpected: HttpStatusCode.NO_CONTENT_204 + expectedStatus: HttpStatusCode.NO_CONTENT_204 }) }) }) @@ -1109,7 +1109,7 @@ describe('Test users API validators', function () { path, token: server.accessToken, fields, - statusCodeExpected: HttpStatusCode.NO_CONTENT_204 + expectedStatus: HttpStatusCode.NO_CONTENT_204 }) }) }) diff --git a/server/tests/api/check-params/video-blacklist.ts b/server/tests/api/check-params/video-blacklist.ts index b5d0e0778..2072df4b6 100644 --- a/server/tests/api/check-params/video-blacklist.ts +++ b/server/tests/api/check-params/video-blacklist.ts @@ -2,7 +2,7 @@ import 'mocha' import { expect } from 'chai' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { BlacklistCommand, checkBadCountPagination, @@ -88,7 +88,7 @@ describe('Test video blacklist API validators', function () { it('Should fail with a non authenticated user', async function () { const path = basePath + servers[0].store.video + '/blacklist' const fields = {} - await makePostBodyRequest({ url: servers[0].url, path, token: 'hello', fields, statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) + await makePostBodyRequest({ url: servers[0].url, path, token: 'hello', fields, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should fail with a non admin user', async function () { @@ -99,7 +99,7 @@ describe('Test video blacklist API validators', function () { path, token: userAccessToken2, fields, - statusCodeExpected: HttpStatusCode.FORBIDDEN_403 + expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) @@ -119,7 +119,7 @@ describe('Test video blacklist API validators', function () { path, token: servers[0].accessToken, fields, - statusCodeExpected: HttpStatusCode.CONFLICT_409 + expectedStatus: HttpStatusCode.CONFLICT_409 }) }) @@ -132,7 +132,7 @@ describe('Test video blacklist API validators', function () { path, token: servers[0].accessToken, fields, - statusCodeExpected: HttpStatusCode.NO_CONTENT_204 + expectedStatus: HttpStatusCode.NO_CONTENT_204 }) }) }) @@ -154,14 +154,14 @@ describe('Test video blacklist API validators', function () { path, token: servers[0].accessToken, fields, - statusCodeExpected: HttpStatusCode.NOT_FOUND_404 + expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) it('Should fail with a non authenticated user', async function () { const path = basePath + servers[0].store.video + '/blacklist' const fields = {} - await makePutBodyRequest({ url: servers[0].url, path, token: 'hello', fields, statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) + await makePutBodyRequest({ url: servers[0].url, path, token: 'hello', fields, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should fail with a non admin user', async function () { @@ -172,7 +172,7 @@ describe('Test video blacklist API validators', function () { path, token: userAccessToken2, fields, - statusCodeExpected: HttpStatusCode.FORBIDDEN_403 + expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) @@ -192,7 +192,7 @@ describe('Test video blacklist API validators', function () { path, token: servers[0].accessToken, fields, - statusCodeExpected: HttpStatusCode.NO_CONTENT_204 + expectedStatus: HttpStatusCode.NO_CONTENT_204 }) }) }) diff --git a/server/tests/api/check-params/video-captions.ts b/server/tests/api/check-params/video-captions.ts index 26aab79e7..1b3d1aa95 100644 --- a/server/tests/api/check-params/video-captions.ts +++ b/server/tests/api/check-params/video-captions.ts @@ -1,7 +1,7 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ import 'mocha' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { buildAbsoluteFixturePath, cleanupTests, @@ -67,7 +67,7 @@ describe('Test video captions API validator', function () { token: server.accessToken, fields, attaches, - statusCodeExpected: 404 + expectedStatus: 404 }) }) @@ -103,7 +103,7 @@ describe('Test video captions API validator', function () { path: captionPath, fields, attaches, - statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 + expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -116,7 +116,7 @@ describe('Test video captions API validator', function () { token: 'blabla', fields, attaches, - statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 + expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -134,7 +134,7 @@ describe('Test video captions API validator', function () { // token: server.accessToken, // fields, // attaches, - // statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 + // expectedStatus: HttpStatusCode.BAD_REQUEST_400 // }) // }) @@ -147,7 +147,7 @@ describe('Test video captions API validator', function () { // videoId: video.uuid, // fixture: 'subtitle-bad.txt', // mimeType: 'application/octet-stream', - // statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 + // expectedStatus: HttpStatusCode.BAD_REQUEST_400 // }) // }) @@ -174,7 +174,7 @@ describe('Test video captions API validator', function () { // token: server.accessToken, // fields, // attaches, - // statusCodeExpected: HttpStatusCode.INTERNAL_SERVER_ERROR_500 + // expectedStatus: HttpStatusCode.INTERNAL_SERVER_ERROR_500 // }) // }) @@ -187,7 +187,7 @@ describe('Test video captions API validator', function () { token: server.accessToken, fields, attaches, - statusCodeExpected: HttpStatusCode.NO_CONTENT_204 + expectedStatus: HttpStatusCode.NO_CONTENT_204 }) }) }) @@ -201,12 +201,12 @@ describe('Test video captions API validator', function () { await makeGetRequest({ url: server.url, path: path + '4da6fde3-88f7-4d16-b119-108df5630b06/captions', - statusCodeExpected: HttpStatusCode.NOT_FOUND_404 + expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) it('Should success with the correct parameters', async function () { - await makeGetRequest({ url: server.url, path: path + video.shortUUID + '/captions', statusCodeExpected: HttpStatusCode.OK_200 }) + await makeGetRequest({ url: server.url, path: path + video.shortUUID + '/captions', expectedStatus: HttpStatusCode.OK_200 }) }) }) @@ -224,7 +224,7 @@ describe('Test video captions API validator', function () { url: server.url, path: path + '4da6fde3-88f7-4d16-b119-108df5630b06/captions/fr', token: server.accessToken, - statusCodeExpected: HttpStatusCode.NOT_FOUND_404 + expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) @@ -248,12 +248,12 @@ describe('Test video captions API validator', function () { it('Should fail without access token', async function () { const captionPath = path + video.shortUUID + '/captions/fr' - await makeDeleteRequest({ url: server.url, path: captionPath, statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) + await makeDeleteRequest({ url: server.url, path: captionPath, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should fail with a bad access token', async function () { const captionPath = path + video.shortUUID + '/captions/fr' - await makeDeleteRequest({ url: server.url, path: captionPath, token: 'coucou', statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) + await makeDeleteRequest({ url: server.url, path: captionPath, token: 'coucou', expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should fail with another user', async function () { @@ -262,7 +262,7 @@ describe('Test video captions API validator', function () { url: server.url, path: captionPath, token: userAccessToken, - statusCodeExpected: HttpStatusCode.FORBIDDEN_403 + expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) @@ -272,7 +272,7 @@ describe('Test video captions API validator', function () { url: server.url, path: captionPath, token: server.accessToken, - statusCodeExpected: HttpStatusCode.NO_CONTENT_204 + expectedStatus: HttpStatusCode.NO_CONTENT_204 }) }) }) diff --git a/server/tests/api/check-params/video-channels.ts b/server/tests/api/check-params/video-channels.ts index 62b8fa4f6..bbe42e43d 100644 --- a/server/tests/api/check-params/video-channels.ts +++ b/server/tests/api/check-params/video-channels.ts @@ -3,7 +3,7 @@ import 'mocha' import * as chai from 'chai' import { omit } from 'lodash' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { buildAbsoluteFixturePath, ChannelsCommand, @@ -88,7 +88,7 @@ describe('Test video channels API validator', function () { await makeGetRequest({ url: server.url, path: accountChannelPath, - statusCodeExpected: HttpStatusCode.OK_200 + expectedStatus: HttpStatusCode.OK_200 }) }) }) @@ -107,7 +107,7 @@ describe('Test video channels API validator', function () { path: videoChannelPath, token: 'none', fields: baseCorrectParams, - statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 + expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -152,7 +152,7 @@ describe('Test video channels API validator', function () { path: videoChannelPath, token: server.accessToken, fields: baseCorrectParams, - statusCodeExpected: HttpStatusCode.OK_200 + expectedStatus: HttpStatusCode.OK_200 }) }) @@ -162,7 +162,7 @@ describe('Test video channels API validator', function () { path: videoChannelPath, token: server.accessToken, fields: baseCorrectParams, - statusCodeExpected: HttpStatusCode.CONFLICT_409 + expectedStatus: HttpStatusCode.CONFLICT_409 }) }) }) @@ -186,7 +186,7 @@ describe('Test video channels API validator', function () { path, token: 'hi', fields: baseCorrectParams, - statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 + expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -196,7 +196,7 @@ describe('Test video channels API validator', function () { path, token: accessTokenUser, fields: baseCorrectParams, - statusCodeExpected: HttpStatusCode.FORBIDDEN_403 + expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) @@ -226,7 +226,7 @@ describe('Test video channels API validator', function () { path, token: server.accessToken, fields: baseCorrectParams, - statusCodeExpected: HttpStatusCode.NO_CONTENT_204 + expectedStatus: HttpStatusCode.NO_CONTENT_204 }) }) }) @@ -271,7 +271,7 @@ describe('Test video channels API validator', function () { path: `${path}/${type}/pick`, fields, attaches, - statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 + expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) } }) @@ -288,7 +288,7 @@ describe('Test video channels API validator', function () { token: server.accessToken, fields, attaches, - statusCodeExpected: HttpStatusCode.OK_200 + expectedStatus: HttpStatusCode.OK_200 }) } }) @@ -299,7 +299,7 @@ describe('Test video channels API validator', function () { const res = await makeGetRequest({ url: server.url, path: videoChannelPath, - statusCodeExpected: HttpStatusCode.OK_200 + expectedStatus: HttpStatusCode.OK_200 }) expect(res.body.data).to.be.an('array') @@ -309,7 +309,7 @@ describe('Test video channels API validator', function () { await makeGetRequest({ url: server.url, path: videoChannelPath + '/super_channel2', - statusCodeExpected: HttpStatusCode.NOT_FOUND_404 + expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) @@ -317,7 +317,7 @@ describe('Test video channels API validator', function () { await makeGetRequest({ url: server.url, path: videoChannelPath + '/super_channel', - statusCodeExpected: HttpStatusCode.OK_200 + expectedStatus: HttpStatusCode.OK_200 }) }) }) diff --git a/server/tests/api/check-params/video-comments.ts b/server/tests/api/check-params/video-comments.ts index 92c29da0e..bfd9e0172 100644 --- a/server/tests/api/check-params/video-comments.ts +++ b/server/tests/api/check-params/video-comments.ts @@ -2,7 +2,7 @@ import 'mocha' import * as chai from 'chai' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { checkBadCountPagination, checkBadSortPagination, @@ -78,7 +78,7 @@ describe('Test video comments API validator', function () { await makeGetRequest({ url: server.url, path: '/api/v1/videos/ba708d62-e3d7-45d9-9d73-41b9097cc02d/comment-threads', - statusCodeExpected: HttpStatusCode.NOT_FOUND_404 + expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) }) @@ -88,7 +88,7 @@ describe('Test video comments API validator', function () { await makeGetRequest({ url: server.url, path: '/api/v1/videos/ba708d62-e3d7-45d9-9d73-41b9097cc02d/comment-threads/' + commentId, - statusCodeExpected: HttpStatusCode.NOT_FOUND_404 + expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) @@ -96,7 +96,7 @@ describe('Test video comments API validator', function () { await makeGetRequest({ url: server.url, path: '/api/v1/videos/' + video.shortUUID + '/comment-threads/156', - statusCodeExpected: HttpStatusCode.NOT_FOUND_404 + expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) @@ -104,7 +104,7 @@ describe('Test video comments API validator', function () { await makeGetRequest({ url: server.url, path: '/api/v1/videos/' + video.shortUUID + '/comment-threads/' + commentId, - statusCodeExpected: HttpStatusCode.OK_200 + expectedStatus: HttpStatusCode.OK_200 }) }) }) @@ -120,7 +120,7 @@ describe('Test video comments API validator', function () { path: pathThread, token: 'none', fields, - statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 + expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -153,7 +153,7 @@ describe('Test video comments API validator', function () { path, token: server.accessToken, fields, - statusCodeExpected: HttpStatusCode.NOT_FOUND_404 + expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) @@ -166,7 +166,7 @@ describe('Test video comments API validator', function () { path: pathThread, token: server.accessToken, fields, - statusCodeExpected: HttpStatusCode.OK_200 + expectedStatus: HttpStatusCode.OK_200 }) }) }) @@ -181,7 +181,7 @@ describe('Test video comments API validator', function () { path: pathComment, token: 'none', fields, - statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 + expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -214,7 +214,7 @@ describe('Test video comments API validator', function () { path, token: server.accessToken, fields, - statusCodeExpected: HttpStatusCode.NOT_FOUND_404 + expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) @@ -228,7 +228,7 @@ describe('Test video comments API validator', function () { path, token: server.accessToken, fields, - statusCodeExpected: HttpStatusCode.NOT_FOUND_404 + expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) @@ -241,14 +241,14 @@ describe('Test video comments API validator', function () { path: pathComment, token: server.accessToken, fields, - statusCodeExpected: HttpStatusCode.OK_200 + expectedStatus: HttpStatusCode.OK_200 }) }) }) describe('When removing video comments', function () { it('Should fail with a non authenticated user', async function () { - await makeDeleteRequest({ url: server.url, path: pathComment, token: 'none', statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) + await makeDeleteRequest({ url: server.url, path: pathComment, token: 'none', expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should fail with another user', async function () { @@ -256,18 +256,18 @@ describe('Test video comments API validator', function () { url: server.url, path: pathComment, token: userAccessToken, - statusCodeExpected: HttpStatusCode.FORBIDDEN_403 + expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) it('Should fail with an incorrect video', async function () { const path = '/api/v1/videos/ba708d62-e3d7-45d9-9d73-41b9097cc02d/comments/' + commentId - await makeDeleteRequest({ url: server.url, path, token: server.accessToken, statusCodeExpected: HttpStatusCode.NOT_FOUND_404 }) + await makeDeleteRequest({ url: server.url, path, token: server.accessToken, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) it('Should fail with an incorrect comment', async function () { const path = '/api/v1/videos/' + video.uuid + '/comments/124' - await makeDeleteRequest({ url: server.url, path, token: server.accessToken, statusCodeExpected: HttpStatusCode.NOT_FOUND_404 }) + await makeDeleteRequest({ url: server.url, path, token: server.accessToken, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) it('Should succeed with the same user', async function () { @@ -280,8 +280,8 @@ describe('Test video comments API validator', function () { const path = '/api/v1/videos/' + video.uuid + '/comments/' + commentToDelete - await makeDeleteRequest({ url: server.url, path, token: userAccessToken2, statusCodeExpected: HttpStatusCode.FORBIDDEN_403 }) - await makeDeleteRequest({ url: server.url, path, token: userAccessToken, statusCodeExpected: HttpStatusCode.NO_CONTENT_204 }) + await makeDeleteRequest({ url: server.url, path, token: userAccessToken2, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) + await makeDeleteRequest({ url: server.url, path, token: userAccessToken, expectedStatus: HttpStatusCode.NO_CONTENT_204 }) }) it('Should succeed with the owner of the video', async function () { @@ -300,8 +300,8 @@ describe('Test video comments API validator', function () { const path = '/api/v1/videos/' + anotherVideoUUID + '/comments/' + commentToDelete - await makeDeleteRequest({ url: server.url, path, token: userAccessToken2, statusCodeExpected: HttpStatusCode.FORBIDDEN_403 }) - await makeDeleteRequest({ url: server.url, path, token: userAccessToken, statusCodeExpected: HttpStatusCode.NO_CONTENT_204 }) + await makeDeleteRequest({ url: server.url, path, token: userAccessToken2, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) + await makeDeleteRequest({ url: server.url, path, token: userAccessToken, expectedStatus: HttpStatusCode.NO_CONTENT_204 }) }) it('Should succeed with the correct parameters', async function () { @@ -309,7 +309,7 @@ describe('Test video comments API validator', function () { url: server.url, path: pathComment, token: server.accessToken, - statusCodeExpected: HttpStatusCode.NO_CONTENT_204 + expectedStatus: HttpStatusCode.NO_CONTENT_204 }) }) }) @@ -324,7 +324,7 @@ describe('Test video comments API validator', function () { const res = await makeGetRequest({ url: server.url, path: pathThread, - statusCodeExpected: HttpStatusCode.OK_200 + expectedStatus: HttpStatusCode.OK_200 }) expect(res.body.total).to.equal(0) expect(res.body.data).to.have.lengthOf(0) @@ -341,7 +341,7 @@ describe('Test video comments API validator', function () { path: pathThread, token: server.accessToken, fields, - statusCodeExpected: HttpStatusCode.CONFLICT_409 + expectedStatus: HttpStatusCode.CONFLICT_409 }) }) @@ -367,7 +367,7 @@ describe('Test video comments API validator', function () { await makeGetRequest({ url: server.url, path, - statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 + expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -376,7 +376,7 @@ describe('Test video comments API validator', function () { url: server.url, path, token: userAccessToken, - statusCodeExpected: HttpStatusCode.FORBIDDEN_403 + expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) @@ -391,7 +391,7 @@ describe('Test video comments API validator', function () { searchAccount: 'toto', searchVideo: 'toto' }, - statusCodeExpected: HttpStatusCode.OK_200 + expectedStatus: HttpStatusCode.OK_200 }) }) }) diff --git a/server/tests/api/check-params/video-imports.ts b/server/tests/api/check-params/video-imports.ts index 0209275ac..957556c9b 100644 --- a/server/tests/api/check-params/video-imports.ts +++ b/server/tests/api/check-params/video-imports.ts @@ -2,7 +2,7 @@ import 'mocha' import { omit } from 'lodash' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { buildAbsoluteFixturePath, checkBadCountPagination, @@ -61,7 +61,7 @@ describe('Test video imports API validator', function () { }) it('Should success with the correct parameters', async function () { - await makeGetRequest({ url: server.url, path: myPath, statusCodeExpected: HttpStatusCode.OK_200, token: server.accessToken }) + await makeGetRequest({ url: server.url, path: myPath, expectedStatus: HttpStatusCode.OK_200, token: server.accessToken }) }) }) @@ -99,7 +99,7 @@ describe('Test video imports API validator', function () { path, token: server.accessToken, fields, - statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 + expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) @@ -251,7 +251,7 @@ describe('Test video imports API validator', function () { path, token: server.accessToken, fields: baseCorrectParams, - statusCodeExpected: HttpStatusCode.OK_200 + expectedStatus: HttpStatusCode.OK_200 }) }) @@ -276,7 +276,7 @@ describe('Test video imports API validator', function () { path, token: server.accessToken, fields: baseCorrectParams, - statusCodeExpected: HttpStatusCode.CONFLICT_409 + expectedStatus: HttpStatusCode.CONFLICT_409 }) }) @@ -304,7 +304,7 @@ describe('Test video imports API validator', function () { path, token: server.accessToken, fields, - statusCodeExpected: HttpStatusCode.CONFLICT_409 + expectedStatus: HttpStatusCode.CONFLICT_409 }) fields = omit(fields, 'magnetUri') @@ -318,7 +318,7 @@ describe('Test video imports API validator', function () { token: server.accessToken, fields, attaches, - statusCodeExpected: HttpStatusCode.CONFLICT_409 + expectedStatus: HttpStatusCode.CONFLICT_409 }) }) }) diff --git a/server/tests/api/check-params/video-playlists.ts b/server/tests/api/check-params/video-playlists.ts index 9d054b176..7dcb4935a 100644 --- a/server/tests/api/check-params/video-playlists.ts +++ b/server/tests/api/check-params/video-playlists.ts @@ -1,7 +1,7 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ import 'mocha' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { checkBadCountPagination, checkBadSortPagination, @@ -119,7 +119,7 @@ describe('Test video playlists API validator', function () { await makeGetRequest({ url: server.url, path: accountPath, - statusCodeExpected: HttpStatusCode.NOT_FOUND_404, + expectedStatus: HttpStatusCode.NOT_FOUND_404, token: server.accessToken }) }) @@ -130,18 +130,18 @@ describe('Test video playlists API validator', function () { await makeGetRequest({ url: server.url, path: accountPath, - statusCodeExpected: HttpStatusCode.NOT_FOUND_404, + expectedStatus: HttpStatusCode.NOT_FOUND_404, token: server.accessToken }) }) it('Should success with the correct parameters', async function () { - await makeGetRequest({ url: server.url, path: globalPath, statusCodeExpected: HttpStatusCode.OK_200, token: server.accessToken }) - await makeGetRequest({ url: server.url, path: accountPath, statusCodeExpected: HttpStatusCode.OK_200, token: server.accessToken }) + await makeGetRequest({ url: server.url, path: globalPath, expectedStatus: HttpStatusCode.OK_200, token: server.accessToken }) + await makeGetRequest({ url: server.url, path: accountPath, expectedStatus: HttpStatusCode.OK_200, token: server.accessToken }) await makeGetRequest({ url: server.url, path: videoChannelPath, - statusCodeExpected: HttpStatusCode.OK_200, + expectedStatus: HttpStatusCode.OK_200, token: server.accessToken }) }) @@ -159,7 +159,7 @@ describe('Test video playlists API validator', function () { }) it('Should success with the correct parameters', async function () { - await makeGetRequest({ url: server.url, path: path + playlist.shortUUID + '/videos', statusCodeExpected: HttpStatusCode.OK_200 }) + await makeGetRequest({ url: server.url, path: path + playlist.shortUUID + '/videos', expectedStatus: HttpStatusCode.OK_200 }) }) }) @@ -580,7 +580,7 @@ describe('Test video playlists API validator', function () { url: server.url, path, query: { videoIds: [ 1, 2 ] }, - statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 + expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -613,7 +613,7 @@ describe('Test video playlists API validator', function () { token: server.accessToken, path, query: { videoIds: [ 1, 2 ] }, - statusCodeExpected: HttpStatusCode.OK_200 + expectedStatus: HttpStatusCode.OK_200 }) }) }) diff --git a/server/tests/api/check-params/videos-filter.ts b/server/tests/api/check-params/videos-filter.ts index e4e799cc7..c2c69904f 100644 --- a/server/tests/api/check-params/videos-filter.ts +++ b/server/tests/api/check-params/videos-filter.ts @@ -1,6 +1,7 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ import 'mocha' +import { HttpStatusCode } from '@shared/models' import { cleanupTests, createSingleServer, @@ -8,11 +9,10 @@ import { PeerTubeServer, setAccessTokensToServers, setDefaultVideoChannel -} from '../../../../shared/extra-utils' -import { UserRole } from '../../../../shared/models/users' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' +} from '@shared/extra-utils' +import { UserRole } from '@shared/models' -async function testEndpoints (server: PeerTubeServer, token: string, filter: string, statusCodeExpected: HttpStatusCode) { +async function testEndpoints (server: PeerTubeServer, token: string, filter: string, expectedStatus: HttpStatusCode) { const paths = [ '/api/v1/video-channels/root_channel/videos', '/api/v1/accounts/root/videos', @@ -28,7 +28,7 @@ async function testEndpoints (server: PeerTubeServer, token: string, filter: str query: { filter }, - statusCodeExpected + expectedStatus }) } } @@ -89,7 +89,7 @@ describe('Test video filters validators', function () { await makeGetRequest({ url: server.url, path: '/feeds/videos.json', - statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401, + expectedStatus: HttpStatusCode.UNAUTHORIZED_401, query: { filter } @@ -101,7 +101,7 @@ describe('Test video filters validators', function () { await makeGetRequest({ url: server.url, path: '/feeds/videos.json', - statusCodeExpected: HttpStatusCode.OK_200, + expectedStatus: HttpStatusCode.OK_200, query: { filter: 'local' } diff --git a/server/tests/api/check-params/videos-history.ts b/server/tests/api/check-params/videos-history.ts index 3c1f479e4..7283a4d28 100644 --- a/server/tests/api/check-params/videos-history.ts +++ b/server/tests/api/check-params/videos-history.ts @@ -1,7 +1,7 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ import 'mocha' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { checkBadCountPagination, checkBadStartPagination, @@ -37,7 +37,7 @@ describe('Test videos history API validator', function () { it('Should fail with an unauthenticated user', async function () { const fields = { currentTime: 5 } - await makePutBodyRequest({ url: server.url, path: watchingPath, fields, statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) + await makePutBodyRequest({ url: server.url, path: watchingPath, fields, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should fail with an incorrect video id', async function () { @@ -48,7 +48,7 @@ describe('Test videos history API validator', function () { path, fields, token: server.accessToken, - statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 + expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) @@ -61,7 +61,7 @@ describe('Test videos history API validator', function () { path, fields, token: server.accessToken, - statusCodeExpected: HttpStatusCode.NOT_FOUND_404 + expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) @@ -72,7 +72,7 @@ describe('Test videos history API validator', function () { path: watchingPath, fields, token: server.accessToken, - statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 + expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) @@ -84,7 +84,7 @@ describe('Test videos history API validator', function () { path: watchingPath, fields, token: server.accessToken, - statusCodeExpected: HttpStatusCode.NO_CONTENT_204 + expectedStatus: HttpStatusCode.NO_CONTENT_204 }) }) }) @@ -99,17 +99,17 @@ describe('Test videos history API validator', function () { }) it('Should fail with an unauthenticated user', async function () { - await makeGetRequest({ url: server.url, path: myHistoryPath, statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) + await makeGetRequest({ url: server.url, path: myHistoryPath, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should succeed with the correct params', async function () { - await makeGetRequest({ url: server.url, token: server.accessToken, path: myHistoryPath, statusCodeExpected: HttpStatusCode.OK_200 }) + await makeGetRequest({ url: server.url, token: server.accessToken, path: myHistoryPath, expectedStatus: HttpStatusCode.OK_200 }) }) }) describe('When removing user videos history', function () { it('Should fail with an unauthenticated user', async function () { - await makePostBodyRequest({ url: server.url, path: myHistoryPath + '/remove', statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) + await makePostBodyRequest({ url: server.url, path: myHistoryPath + '/remove', expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should fail with a bad beforeDate parameter', async function () { @@ -119,7 +119,7 @@ describe('Test videos history API validator', function () { token: server.accessToken, path: myHistoryRemove, fields: body, - statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 + expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) @@ -130,7 +130,7 @@ describe('Test videos history API validator', function () { token: server.accessToken, path: myHistoryRemove, fields: body, - statusCodeExpected: HttpStatusCode.NO_CONTENT_204 + expectedStatus: HttpStatusCode.NO_CONTENT_204 }) }) @@ -139,7 +139,7 @@ describe('Test videos history API validator', function () { url: server.url, token: server.accessToken, path: myHistoryRemove, - statusCodeExpected: HttpStatusCode.NO_CONTENT_204 + expectedStatus: HttpStatusCode.NO_CONTENT_204 }) }) }) diff --git a/server/tests/api/check-params/videos.ts b/server/tests/api/check-params/videos.ts index c60de2640..e11ca0c82 100644 --- a/server/tests/api/check-params/videos.ts +++ b/server/tests/api/check-params/videos.ts @@ -4,7 +4,7 @@ import 'mocha' import * as chai from 'chai' import { omit } from 'lodash' import { join } from 'path' -import { HttpStatusCode, randomInt } from '@shared/core-utils' +import { randomInt } from '@shared/core-utils' import { checkBadCountPagination, checkBadSortPagination, @@ -16,11 +16,11 @@ import { makeGetRequest, makePutBodyRequest, makeUploadRequest, - root, PeerTubeServer, + root, setAccessTokensToServers } from '@shared/extra-utils' -import { PeerTubeProblemDocument, VideoCreateResult, VideoPrivacy } from '@shared/models' +import { HttpStatusCode, PeerTubeProblemDocument, VideoCreateResult, VideoPrivacy } from '@shared/models' const expect = chai.expect @@ -69,11 +69,11 @@ describe('Test videos API validator', function () { }) it('Should fail with a bad skipVideos query', async function () { - await makeGetRequest({ url: server.url, path, statusCodeExpected: HttpStatusCode.OK_200, query: { skipCount: 'toto' } }) + await makeGetRequest({ url: server.url, path, expectedStatus: HttpStatusCode.OK_200, query: { skipCount: 'toto' } }) }) it('Should success with the correct parameters', async function () { - await makeGetRequest({ url: server.url, path, statusCodeExpected: HttpStatusCode.OK_200, query: { skipCount: false } }) + await makeGetRequest({ url: server.url, path, expectedStatus: HttpStatusCode.OK_200, query: { skipCount: false } }) }) }) @@ -83,7 +83,7 @@ describe('Test videos API validator', function () { await makeGetRequest({ url: server.url, path: join(path, 'search'), - statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 + expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) @@ -100,7 +100,7 @@ describe('Test videos API validator', function () { }) it('Should success with the correct parameters', async function () { - await makeGetRequest({ url: server.url, path, statusCodeExpected: HttpStatusCode.OK_200 }) + await makeGetRequest({ url: server.url, path, expectedStatus: HttpStatusCode.OK_200 }) }) }) @@ -120,7 +120,7 @@ describe('Test videos API validator', function () { }) it('Should success with the correct parameters', async function () { - await makeGetRequest({ url: server.url, token: server.accessToken, path, statusCodeExpected: HttpStatusCode.OK_200 }) + await makeGetRequest({ url: server.url, token: server.accessToken, path, expectedStatus: HttpStatusCode.OK_200 }) }) }) @@ -144,7 +144,7 @@ describe('Test videos API validator', function () { }) it('Should success with the correct parameters', async function () { - await makeGetRequest({ url: server.url, path, statusCodeExpected: HttpStatusCode.OK_200 }) + await makeGetRequest({ url: server.url, path, expectedStatus: HttpStatusCode.OK_200 }) }) }) @@ -168,7 +168,7 @@ describe('Test videos API validator', function () { }) it('Should success with the correct parameters', async function () { - await makeGetRequest({ url: server.url, path, statusCodeExpected: HttpStatusCode.OK_200 }) + await makeGetRequest({ url: server.url, path, expectedStatus: HttpStatusCode.OK_200 }) }) }) @@ -506,7 +506,7 @@ describe('Test videos API validator', function () { path: path + '4da6fde3-88f7-4d16-b119-108df5630b06', token: server.accessToken, fields, - statusCodeExpected: HttpStatusCode.NOT_FOUND_404 + expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) @@ -660,7 +660,7 @@ describe('Test videos API validator', function () { path: path + video.shortUUID, token: userAccessToken, fields, - statusCodeExpected: HttpStatusCode.FORBIDDEN_403 + expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) @@ -692,7 +692,7 @@ describe('Test videos API validator', function () { path: path + video.shortUUID, token: server.accessToken, fields, - statusCodeExpected: HttpStatusCode.NO_CONTENT_204 + expectedStatus: HttpStatusCode.NO_CONTENT_204 }) }) }) @@ -702,7 +702,7 @@ describe('Test videos API validator', function () { const res = await makeGetRequest({ url: server.url, path, - statusCodeExpected: HttpStatusCode.OK_200 + expectedStatus: HttpStatusCode.OK_200 }) expect(res.body.data).to.be.an('array') @@ -762,7 +762,7 @@ describe('Test videos API validator', function () { path: path + '4da6fde3-88f7-4d16-b119-108df5630b06/rate', token: server.accessToken, fields, - statusCodeExpected: HttpStatusCode.NOT_FOUND_404 + expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) @@ -782,7 +782,7 @@ describe('Test videos API validator', function () { path: path + videoId + '/rate', token: server.accessToken, fields, - statusCodeExpected: HttpStatusCode.NO_CONTENT_204 + expectedStatus: HttpStatusCode.NO_CONTENT_204 }) }) }) @@ -792,7 +792,7 @@ describe('Test videos API validator', function () { await makeDeleteRequest({ url: server.url, path, - statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 + expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) }) @@ -812,7 +812,7 @@ describe('Test videos API validator', function () { it('Shoud report the appropriate error', async function () { const body = await server.videos.remove({ id: 'hello', expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) - const error = body as unknown as PeerTubeProblemDocument + const error = body as PeerTubeProblemDocument expect(error.docs).to.equal('https://docs.joinpeertube.org/api-rest-reference.html#operation/delVideo') diff --git a/server/tests/api/live/live-save-replay.ts b/server/tests/api/live/live-save-replay.ts index d403f27bf..095c51b97 100644 --- a/server/tests/api/live/live-save-replay.ts +++ b/server/tests/api/live/live-save-replay.ts @@ -3,7 +3,7 @@ import 'mocha' import * as chai from 'chai' import { FfmpegCommand } from 'fluent-ffmpeg' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { checkLiveCleanup, cleanupTests, diff --git a/server/tests/api/live/live.ts b/server/tests/api/live/live.ts index 7cfac522c..88995910c 100644 --- a/server/tests/api/live/live.ts +++ b/server/tests/api/live/live.ts @@ -4,7 +4,7 @@ import 'mocha' import * as chai from 'chai' import { join } from 'path' import { ffprobePromise, getVideoStreamFromFile } from '@server/helpers/ffprobe-utils' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { checkLiveCleanup, checkLiveSegmentHash, diff --git a/server/tests/api/moderation/abuses.ts b/server/tests/api/moderation/abuses.ts index 360b9de35..8d6360eb3 100644 --- a/server/tests/api/moderation/abuses.ts +++ b/server/tests/api/moderation/abuses.ts @@ -5,8 +5,8 @@ import * as chai from 'chai' import { AbusesCommand, cleanupTests, - doubleFollow, createMultipleServers, + doubleFollow, PeerTubeServer, setAccessTokensToServers, waitJobs @@ -65,7 +65,7 @@ describe('Test abuses', function () { expect(data.length).to.equal(2) servers[0].store.video = data.find(video => video.name === 'my super name for server 1') - servers[1].store.video = data.find(video => video.name === 'my super name for server 2') + servers[1].store.video = data.find(video => video.name === 'my super name for server 2') }) it('Should not have abuses', async function () { @@ -402,8 +402,8 @@ describe('Test abuses', function () { before(async function () { this.timeout(50000) - servers[0].store.video = await await servers[0].videos.quickUpload({ name: 'server 1' }) - servers[1].store.video = await await servers[1].videos.quickUpload({ name: 'server 2' }) + servers[0].store.video = await servers[0].videos.quickUpload({ name: 'server 1' }) + servers[1].store.video = await servers[1].videos.quickUpload({ name: 'server 2' }) await servers[0].comments.createThread({ videoId: servers[0].store.video.id, text: 'comment server 1' }) await servers[1].comments.createThread({ videoId: servers[1].store.video.id, text: 'comment server 2' }) diff --git a/server/tests/api/redundancy/redundancy-constraints.ts b/server/tests/api/redundancy/redundancy-constraints.ts index 217691fb6..71b93901e 100644 --- a/server/tests/api/redundancy/redundancy-constraints.ts +++ b/server/tests/api/redundancy/redundancy-constraints.ts @@ -117,7 +117,7 @@ describe('Test redundancy constraints', function () { } } } - await await killallServers([ localServer ]) + await killallServers([ localServer ]) await localServer.run(config) await uploadWrapper('video 2 server 2') diff --git a/server/tests/api/redundancy/redundancy.ts b/server/tests/api/redundancy/redundancy.ts index 9d5d96efd..921a48856 100644 --- a/server/tests/api/redundancy/redundancy.ts +++ b/server/tests/api/redundancy/redundancy.ts @@ -5,7 +5,7 @@ import * as chai from 'chai' import { readdir } from 'fs-extra' import * as magnetUtil from 'magnet-uri' import { join } from 'path' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { checkSegmentHash, checkVideoFilesWereRemoved, @@ -129,13 +129,13 @@ async function check2Webseeds (videoUUID?: string) { await makeGetRequest({ url: servers[0].url, - statusCodeExpected: HttpStatusCode.OK_200, + expectedStatus: HttpStatusCode.OK_200, path: '/static/redundancy/' + `${videoUUID}-${file.resolution.id}.mp4`, contentType: null }) await makeGetRequest({ url: servers[1].url, - statusCodeExpected: HttpStatusCode.OK_200, + expectedStatus: HttpStatusCode.OK_200, path: `/static/webseed/${videoUUID}-${file.resolution.id}.mp4`, contentType: null }) diff --git a/server/tests/api/search/search-activitypub-video-channels.ts b/server/tests/api/search/search-activitypub-video-channels.ts index f5896ec25..b33f28266 100644 --- a/server/tests/api/search/search-activitypub-video-channels.ts +++ b/server/tests/api/search/search-activitypub-video-channels.ts @@ -149,7 +149,7 @@ describe('Test ActivityPub video channels search', function () { const { total, data } = await servers[0].videos.listByChannel({ token: null, - videoChannelName: 'channel1_server2@localhost:' + servers[1].port + handle: 'channel1_server2@localhost:' + servers[1].port }) expect(total).to.equal(0) expect(data).to.have.lengthOf(0) @@ -157,7 +157,7 @@ describe('Test ActivityPub video channels search', function () { it('Should list video channel videos of server 2 with token', async function () { const { total, data } = await servers[0].videos.listByChannel({ - videoChannelName: 'channel1_server2@localhost:' + servers[1].port + handle: 'channel1_server2@localhost:' + servers[1].port }) expect(total).to.equal(1) @@ -206,8 +206,8 @@ describe('Test ActivityPub video channels search', function () { await waitJobs(servers) - const videoChannelName = 'channel1_server2@localhost:' + servers[1].port - const { total, data } = await servers[0].videos.listByChannel({ videoChannelName, sort: '-createdAt' }) + const handle = 'channel1_server2@localhost:' + servers[1].port + const { total, data } = await servers[0].videos.listByChannel({ handle, sort: '-createdAt' }) expect(total).to.equal(2) expect(data[0].name).to.equal('video 2 server 2') diff --git a/server/tests/api/server/config.ts b/server/tests/api/server/config.ts index a7191c5ef..a1c2f0f39 100644 --- a/server/tests/api/server/config.ts +++ b/server/tests/api/server/config.ts @@ -2,7 +2,7 @@ import 'mocha' import * as chai from 'chai' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { cleanupTests, createSingleServer, @@ -498,7 +498,7 @@ describe('Test config', function () { const res = await makeGetRequest({ url: server.url, path: '/api/v1/config', - statusCodeExpected: 200 + expectedStatus: 200 }) expect(res.headers['x-frame-options']).to.exist @@ -517,7 +517,7 @@ describe('Test config', function () { const res = await makeGetRequest({ url: server.url, path: '/api/v1/config', - statusCodeExpected: 200 + expectedStatus: 200 }) expect(res.headers['x-frame-options']).to.not.exist diff --git a/server/tests/api/server/contact-form.ts b/server/tests/api/server/contact-form.ts index f0905bb3b..fc5d0ad6a 100644 --- a/server/tests/api/server/contact-form.ts +++ b/server/tests/api/server/contact-form.ts @@ -2,7 +2,7 @@ import 'mocha' import * as chai from 'chai' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { cleanupTests, ContactFormCommand, diff --git a/server/tests/api/server/email.ts b/server/tests/api/server/email.ts index b202cf8a7..4c5b296ee 100644 --- a/server/tests/api/server/email.ts +++ b/server/tests/api/server/email.ts @@ -2,7 +2,7 @@ import 'mocha' import * as chai from 'chai' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { cleanupTests, createSingleServer, MockSmtpServer, PeerTubeServer, setAccessTokensToServers, waitJobs } from '@shared/extra-utils' const expect = chai.expect diff --git a/server/tests/api/server/follow-constraints.ts b/server/tests/api/server/follow-constraints.ts index 4ed593b76..bd7b215db 100644 --- a/server/tests/api/server/follow-constraints.ts +++ b/server/tests/api/server/follow-constraints.ts @@ -2,7 +2,7 @@ import 'mocha' import * as chai from 'chai' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { cleanupTests, doubleFollow, createMultipleServers, PeerTubeServer, setAccessTokensToServers } from '@shared/extra-utils' import { PeerTubeProblemDocument, ServerErrorCode } from '@shared/models' @@ -54,30 +54,30 @@ describe('Test follow constraints', function () { }) it('Should list local account videos', async function () { - const { total, data } = await servers[0].videos.listByAccount({ accountName: 'root@localhost:' + servers[0].port }) + const { total, data } = await servers[0].videos.listByAccount({ handle: 'root@localhost:' + servers[0].port }) expect(total).to.equal(1) expect(data).to.have.lengthOf(1) }) it('Should list remote account videos', async function () { - const { total, data } = await servers[0].videos.listByAccount({ accountName: 'root@localhost:' + servers[1].port }) + const { total, data } = await servers[0].videos.listByAccount({ handle: 'root@localhost:' + servers[1].port }) expect(total).to.equal(1) expect(data).to.have.lengthOf(1) }) it('Should list local channel videos', async function () { - const videoChannelName = 'root_channel@localhost:' + servers[0].port - const { total, data } = await servers[0].videos.listByChannel({ videoChannelName }) + const handle = 'root_channel@localhost:' + servers[0].port + const { total, data } = await servers[0].videos.listByChannel({ handle }) expect(total).to.equal(1) expect(data).to.have.lengthOf(1) }) it('Should list remote channel videos', async function () { - const videoChannelName = 'root_channel@localhost:' + servers[1].port - const { total, data } = await servers[0].videos.listByChannel({ videoChannelName }) + const handle = 'root_channel@localhost:' + servers[1].port + const { total, data } = await servers[0].videos.listByChannel({ handle }) expect(total).to.equal(1) expect(data).to.have.lengthOf(1) @@ -94,30 +94,30 @@ describe('Test follow constraints', function () { }) it('Should list local account videos', async function () { - const { total, data } = await servers[0].videos.listByAccount({ token: userToken, accountName: 'root@localhost:' + servers[0].port }) + const { total, data } = await servers[0].videos.listByAccount({ token: userToken, handle: 'root@localhost:' + servers[0].port }) expect(total).to.equal(1) expect(data).to.have.lengthOf(1) }) it('Should list remote account videos', async function () { - const { total, data } = await servers[0].videos.listByAccount({ token: userToken, accountName: 'root@localhost:' + servers[1].port }) + const { total, data } = await servers[0].videos.listByAccount({ token: userToken, handle: 'root@localhost:' + servers[1].port }) expect(total).to.equal(1) expect(data).to.have.lengthOf(1) }) it('Should list local channel videos', async function () { - const videoChannelName = 'root_channel@localhost:' + servers[0].port - const { total, data } = await servers[0].videos.listByChannel({ token: userToken, videoChannelName }) + const handle = 'root_channel@localhost:' + servers[0].port + const { total, data } = await servers[0].videos.listByChannel({ token: userToken, handle }) expect(total).to.equal(1) expect(data).to.have.lengthOf(1) }) it('Should list remote channel videos', async function () { - const videoChannelName = 'root_channel@localhost:' + servers[1].port - const { total, data } = await servers[0].videos.listByChannel({ token: userToken, videoChannelName }) + const handle = 'root_channel@localhost:' + servers[1].port + const { total, data } = await servers[0].videos.listByChannel({ token: userToken, handle }) expect(total).to.equal(1) expect(data).to.have.lengthOf(1) @@ -158,7 +158,7 @@ describe('Test follow constraints', function () { it('Should list local account videos', async function () { const { total, data } = await servers[0].videos.listByAccount({ token: undefined, - accountName: 'root@localhost:' + servers[0].port + handle: 'root@localhost:' + servers[0].port }) expect(total).to.equal(1) @@ -168,7 +168,7 @@ describe('Test follow constraints', function () { it('Should not list remote account videos', async function () { const { total, data } = await servers[0].videos.listByAccount({ token: undefined, - accountName: 'root@localhost:' + servers[1].port + handle: 'root@localhost:' + servers[1].port }) expect(total).to.equal(0) @@ -176,16 +176,16 @@ describe('Test follow constraints', function () { }) it('Should list local channel videos', async function () { - const videoChannelName = 'root_channel@localhost:' + servers[0].port - const { total, data } = await servers[0].videos.listByChannel({ token: undefined, videoChannelName }) + const handle = 'root_channel@localhost:' + servers[0].port + const { total, data } = await servers[0].videos.listByChannel({ token: undefined, handle }) expect(total).to.equal(1) expect(data).to.have.lengthOf(1) }) it('Should not list remote channel videos', async function () { - const videoChannelName = 'root_channel@localhost:' + servers[1].port - const { total, data } = await servers[0].videos.listByChannel({ token: undefined, videoChannelName }) + const handle = 'root_channel@localhost:' + servers[1].port + const { total, data } = await servers[0].videos.listByChannel({ token: undefined, handle }) expect(total).to.equal(0) expect(data).to.have.lengthOf(0) @@ -202,30 +202,30 @@ describe('Test follow constraints', function () { }) it('Should list local account videos', async function () { - const { total, data } = await servers[0].videos.listByAccount({ token: userToken, accountName: 'root@localhost:' + servers[0].port }) + const { total, data } = await servers[0].videos.listByAccount({ token: userToken, handle: 'root@localhost:' + servers[0].port }) expect(total).to.equal(1) expect(data).to.have.lengthOf(1) }) it('Should list remote account videos', async function () { - const { total, data } = await servers[0].videos.listByAccount({ token: userToken, accountName: 'root@localhost:' + servers[1].port }) + const { total, data } = await servers[0].videos.listByAccount({ token: userToken, handle: 'root@localhost:' + servers[1].port }) expect(total).to.equal(1) expect(data).to.have.lengthOf(1) }) it('Should list local channel videos', async function () { - const videoChannelName = 'root_channel@localhost:' + servers[0].port - const { total, data } = await servers[0].videos.listByChannel({ token: userToken, videoChannelName }) + const handle = 'root_channel@localhost:' + servers[0].port + const { total, data } = await servers[0].videos.listByChannel({ token: userToken, handle }) expect(total).to.equal(1) expect(data).to.have.lengthOf(1) }) it('Should list remote channel videos', async function () { - const videoChannelName = 'root_channel@localhost:' + servers[1].port - const { total, data } = await servers[0].videos.listByChannel({ token: userToken, videoChannelName }) + const handle = 'root_channel@localhost:' + servers[1].port + const { total, data } = await servers[0].videos.listByChannel({ token: userToken, handle }) expect(total).to.equal(1) expect(data).to.have.lengthOf(1) diff --git a/server/tests/api/server/handle-down.ts b/server/tests/api/server/handle-down.ts index 5f20b0093..d22e843e0 100644 --- a/server/tests/api/server/handle-down.ts +++ b/server/tests/api/server/handle-down.ts @@ -2,7 +2,7 @@ import 'mocha' import * as chai from 'chai' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { cleanupTests, CommentsCommand, diff --git a/server/tests/api/server/homepage.ts b/server/tests/api/server/homepage.ts index c291037f2..7eae3df20 100644 --- a/server/tests/api/server/homepage.ts +++ b/server/tests/api/server/homepage.ts @@ -2,7 +2,7 @@ import 'mocha' import * as chai from 'chai' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { cleanupTests, CustomPagesCommand, diff --git a/server/tests/api/server/no-client.ts b/server/tests/api/server/no-client.ts index f45222f2f..efa890ad4 100644 --- a/server/tests/api/server/no-client.ts +++ b/server/tests/api/server/no-client.ts @@ -1,8 +1,7 @@ import 'mocha' import * as request from 'supertest' -import { PeerTubeServer } from '../../../../shared/extra-utils' -import { cleanupTests, createSingleServer } from '../../../../shared/extra-utils/server/servers' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' +import { cleanupTests, createSingleServer, PeerTubeServer } from '@shared/extra-utils' +import { HttpStatusCode } from '@shared/models' describe('Start and stop server without web client routes', function () { let server: PeerTubeServer diff --git a/server/tests/api/server/plugins.ts b/server/tests/api/server/plugins.ts index db03d026a..334adfe9d 100644 --- a/server/tests/api/server/plugins.ts +++ b/server/tests/api/server/plugins.ts @@ -2,7 +2,7 @@ import 'mocha' import * as chai from 'chai' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { cleanupTests, createSingleServer, diff --git a/server/tests/api/server/reverse-proxy.ts b/server/tests/api/server/reverse-proxy.ts index c20b7a5f0..13b22bc0e 100644 --- a/server/tests/api/server/reverse-proxy.ts +++ b/server/tests/api/server/reverse-proxy.ts @@ -1,7 +1,7 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ import { expect } from 'chai' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { cleanupTests, createSingleServer, PeerTubeServer, setAccessTokensToServers, wait } from '@shared/extra-utils' describe('Test application behind a reverse proxy', function () { diff --git a/server/tests/api/users/users-multiple-servers.ts b/server/tests/api/users/users-multiple-servers.ts index e629966bb..e304e5d67 100644 --- a/server/tests/api/users/users-multiple-servers.ts +++ b/server/tests/api/users/users-multiple-servers.ts @@ -131,7 +131,7 @@ describe('Test users with multiple servers', function () { it('Should list account videos', async function () { for (const server of servers) { - const { total, data } = await server.videos.listByAccount({ accountName: 'user1@localhost:' + servers[0].port }) + const { total, data } = await server.videos.listByAccount({ handle: 'user1@localhost:' + servers[0].port }) expect(total).to.equal(1) expect(data).to.be.an('array') @@ -148,7 +148,7 @@ describe('Test users with multiple servers', function () { await waitJobs(servers) for (const server of servers) { - const { total, data } = await server.videos.listByAccount({ accountName: 'user1@localhost:' + servers[0].port, search: 'Kami' }) + const { total, data } = await server.videos.listByAccount({ handle: 'user1@localhost:' + servers[0].port, search: 'Kami' }) expect(total).to.equal(1) expect(data).to.be.an('array') diff --git a/server/tests/api/users/users-verification.ts b/server/tests/api/users/users-verification.ts index 5dbe2af59..56fc25048 100644 --- a/server/tests/api/users/users-verification.ts +++ b/server/tests/api/users/users-verification.ts @@ -2,7 +2,7 @@ import 'mocha' import * as chai from 'chai' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { cleanupTests, createSingleServer, MockSmtpServer, PeerTubeServer, setAccessTokensToServers, waitJobs } from '@shared/extra-utils' const expect = chai.expect diff --git a/server/tests/api/users/users.ts b/server/tests/api/users/users.ts index 6ae5410b3..be80c2616 100644 --- a/server/tests/api/users/users.ts +++ b/server/tests/api/users/users.ts @@ -2,7 +2,7 @@ import 'mocha' import * as chai from 'chai' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { cleanupTests, createSingleServer, @@ -215,7 +215,7 @@ describe('Test users', function () { path: path + videoId, token: 'wrong token', fields: data, - statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 + expectedStatus: HttpStatusCode.UNAUTHORIZED_401 } await makePutBodyRequest(options) }) diff --git a/server/tests/api/videos/multiple-servers.ts b/server/tests/api/videos/multiple-servers.ts index 562079a15..edf2773cd 100644 --- a/server/tests/api/videos/multiple-servers.ts +++ b/server/tests/api/videos/multiple-servers.ts @@ -3,7 +3,7 @@ import 'mocha' import * as chai from 'chai' import * as request from 'supertest' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { buildAbsoluteFixturePath, checkTmpIsEmpty, diff --git a/server/tests/api/videos/resumable-upload.ts b/server/tests/api/videos/resumable-upload.ts index b4fc5ee09..0e62972c2 100644 --- a/server/tests/api/videos/resumable-upload.ts +++ b/server/tests/api/videos/resumable-upload.ts @@ -4,7 +4,7 @@ import 'mocha' import * as chai from 'chai' import { pathExists, readdir, stat } from 'fs-extra' import { join } from 'path' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { buildAbsoluteFixturePath, cleanupTests, diff --git a/server/tests/api/videos/video-change-ownership.ts b/server/tests/api/videos/video-change-ownership.ts index cefddb68e..792550101 100644 --- a/server/tests/api/videos/video-change-ownership.ts +++ b/server/tests/api/videos/video-change-ownership.ts @@ -2,7 +2,7 @@ import 'mocha' import * as chai from 'chai' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { ChangeOwnershipCommand, cleanupTests, diff --git a/server/tests/api/videos/video-channels.ts b/server/tests/api/videos/video-channels.ts index 140fee7fe..eeaec5ad2 100644 --- a/server/tests/api/videos/video-channels.ts +++ b/server/tests/api/videos/video-channels.ts @@ -324,7 +324,7 @@ describe('Test video channels', function () { for (const server of servers) { const channelURI = 'second_video_channel@localhost:' + servers[0].port - const { total, data } = await server.videos.listByChannel({ videoChannelName: channelURI }) + const { total, data } = await server.videos.listByChannel({ handle: channelURI }) expect(total).to.equal(1) expect(data).to.be.an('array') @@ -347,13 +347,13 @@ describe('Test video channels', function () { for (const server of servers) { { const secondChannelURI = 'second_video_channel@localhost:' + servers[0].port - const { total } = await server.videos.listByChannel({ videoChannelName: secondChannelURI }) + const { total } = await server.videos.listByChannel({ handle: secondChannelURI }) expect(total).to.equal(0) } { const channelURI = 'root_channel@localhost:' + servers[0].port - const { total, data } = await server.videos.listByChannel({ videoChannelName: channelURI }) + const { total, data } = await server.videos.listByChannel({ handle: channelURI }) expect(total).to.equal(1) expect(data).to.be.an('array') diff --git a/server/tests/api/videos/video-hls.ts b/server/tests/api/videos/video-hls.ts index 4c4b18887..df030110b 100644 --- a/server/tests/api/videos/video-hls.ts +++ b/server/tests/api/videos/video-hls.ts @@ -3,7 +3,7 @@ import 'mocha' import * as chai from 'chai' import { join } from 'path' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { checkDirectoryIsEmpty, checkResolutionsInMasterPlaylist, diff --git a/server/tests/api/videos/video-nsfw.ts b/server/tests/api/videos/video-nsfw.ts index b25dcda20..0a9e5ce3f 100644 --- a/server/tests/api/videos/video-nsfw.ts +++ b/server/tests/api/videos/video-nsfw.ts @@ -19,8 +19,10 @@ describe('Test video NSFW policy', function () { async function getVideosFunctions (token?: string, query: { nsfw?: BooleanBothQuery } = {}) { const user = await server.users.getMyInfo() - const videoChannelName = user.videoChannels[0].name + + const channelName = user.videoChannels[0].name const accountName = user.account.name + '@' + user.account.host + const hasQuery = Object.keys(query).length !== 0 let promises: Promise>[] @@ -28,8 +30,8 @@ describe('Test video NSFW policy', function () { promises = [ server.search.advancedVideoSearch({ token, search: { search: 'n', sort: '-publishedAt', ...query } }), server.videos.listWithToken({ token, ...query }), - server.videos.listByAccount({ token, accountName, ...query }), - server.videos.listByChannel({ token, videoChannelName, ...query }) + server.videos.listByAccount({ token, handle: channelName, ...query }), + server.videos.listByChannel({ token, handle: accountName, ...query }) ] // Overviews do not support video filters @@ -45,8 +47,8 @@ describe('Test video NSFW policy', function () { promises = [ server.search.searchVideos({ search: 'n', sort: '-publishedAt' }), server.videos.list(), - server.videos.listByAccount({ accountName }), - server.videos.listByChannel({ videoChannelName }) + server.videos.listByAccount({ handle: channelName }), + server.videos.listByChannel({ handle: accountName }) ] // Overviews do not support video filters diff --git a/server/tests/api/videos/video-playlists.ts b/server/tests/api/videos/video-playlists.ts index 71ca3e63a..9a28a421a 100644 --- a/server/tests/api/videos/video-playlists.ts +++ b/server/tests/api/videos/video-playlists.ts @@ -2,7 +2,7 @@ import 'mocha' import * as chai from 'chai' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { checkPlaylistFilesWereRemoved, cleanupTests, diff --git a/server/tests/api/videos/video-privacy.ts b/server/tests/api/videos/video-privacy.ts index 5ec626155..06011082d 100644 --- a/server/tests/api/videos/video-privacy.ts +++ b/server/tests/api/videos/video-privacy.ts @@ -2,7 +2,7 @@ import 'mocha' import * as chai from 'chai' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { cleanupTests, doubleFollow, createSingleServer, PeerTubeServer, setAccessTokensToServers, waitJobs } from '@shared/extra-utils' import { VideoCreateResult, VideoPrivacy } from '@shared/models' diff --git a/server/tests/api/videos/video-transcoder.ts b/server/tests/api/videos/video-transcoder.ts index 2465d2d89..7510472e3 100644 --- a/server/tests/api/videos/video-transcoder.ts +++ b/server/tests/api/videos/video-transcoder.ts @@ -4,7 +4,7 @@ import 'mocha' import * as chai from 'chai' import { omit } from 'lodash' import { join } from 'path' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { buildAbsoluteFixturePath, cleanupTests, @@ -384,8 +384,8 @@ describe('Test video transcoding', function () { expect(videoDetails.files).to.have.lengthOf(1) - await makeGetRequest({ url: server.url, path: videoDetails.thumbnailPath, statusCodeExpected: HttpStatusCode.OK_200 }) - await makeGetRequest({ url: server.url, path: videoDetails.previewPath, statusCodeExpected: HttpStatusCode.OK_200 }) + await makeGetRequest({ url: server.url, path: videoDetails.thumbnailPath, expectedStatus: HttpStatusCode.OK_200 }) + await makeGetRequest({ url: server.url, path: videoDetails.previewPath, expectedStatus: HttpStatusCode.OK_200 }) const magnetUri = videoDetails.files[0].magnetUri expect(magnetUri).to.contain('.mp4') @@ -408,8 +408,8 @@ describe('Test video transcoding', function () { expect(videoDetails.files).to.have.lengthOf(1) - await makeGetRequest({ url: server.url, path: videoDetails.thumbnailPath, statusCodeExpected: HttpStatusCode.OK_200 }) - await makeGetRequest({ url: server.url, path: videoDetails.previewPath, statusCodeExpected: HttpStatusCode.OK_200 }) + await makeGetRequest({ url: server.url, path: videoDetails.thumbnailPath, expectedStatus: HttpStatusCode.OK_200 }) + await makeGetRequest({ url: server.url, path: videoDetails.previewPath, expectedStatus: HttpStatusCode.OK_200 }) const magnetUri = videoDetails.files[0].magnetUri expect(magnetUri).to.contain('.mp4') diff --git a/server/tests/api/videos/videos-filter.ts b/server/tests/api/videos/videos-filter.ts index db9150655..88dff3e7f 100644 --- a/server/tests/api/videos/videos-filter.ts +++ b/server/tests/api/videos/videos-filter.ts @@ -2,7 +2,7 @@ import 'mocha' import { expect } from 'chai' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { cleanupTests, doubleFollow, @@ -13,7 +13,7 @@ import { } from '@shared/extra-utils' import { UserRole, Video, VideoPrivacy } from '@shared/models' -async function getVideosNames (server: PeerTubeServer, token: string, filter: string, statusCodeExpected = HttpStatusCode.OK_200) { +async function getVideosNames (server: PeerTubeServer, token: string, filter: string, expectedStatus = HttpStatusCode.OK_200) { const paths = [ '/api/v1/video-channels/root_channel/videos', '/api/v1/accounts/root/videos', @@ -32,7 +32,7 @@ async function getVideosNames (server: PeerTubeServer, token: string, filter: st sort: 'createdAt', filter }, - statusCodeExpected + expectedStatus }) videosResults.push(res.body.data.map(v => v.name)) diff --git a/server/tests/api/videos/videos-history.ts b/server/tests/api/videos/videos-history.ts index 55e53cb94..acb9d1a46 100644 --- a/server/tests/api/videos/videos-history.ts +++ b/server/tests/api/videos/videos-history.ts @@ -2,7 +2,7 @@ import 'mocha' import * as chai from 'chai' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { cleanupTests, createSingleServer, diff --git a/server/tests/cli/prune-storage.ts b/server/tests/cli/prune-storage.ts index 5bf86462b..2bd4a466b 100644 --- a/server/tests/cli/prune-storage.ts +++ b/server/tests/cli/prune-storage.ts @@ -5,7 +5,7 @@ import * as chai from 'chai' import { createFile, readdir } from 'fs-extra' import { join } from 'path' import { buildUUID } from '@server/helpers/uuid' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { cleanupTests, CLICommand, @@ -91,7 +91,7 @@ describe('Test prune storage scripts', function () { await makeGetRequest({ url: servers[0].url, path: account.avatar.path, - statusCodeExpected: HttpStatusCode.OK_200 + expectedStatus: HttpStatusCode.OK_200 }) } @@ -100,7 +100,7 @@ describe('Test prune storage scripts', function () { await makeGetRequest({ url: servers[1].url, path: account.avatar.path, - statusCodeExpected: HttpStatusCode.OK_200 + expectedStatus: HttpStatusCode.OK_200 }) } diff --git a/server/tests/cli/regenerate-thumbnails.ts b/server/tests/cli/regenerate-thumbnails.ts index d532a5c2b..595d842ef 100644 --- a/server/tests/cli/regenerate-thumbnails.ts +++ b/server/tests/cli/regenerate-thumbnails.ts @@ -2,7 +2,7 @@ import 'mocha' import { expect } from 'chai' import { writeFile } from 'fs-extra' import { basename, join } from 'path' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { Video } from '@shared/models' import { cleanupTests, diff --git a/server/tests/client.ts b/server/tests/client.ts index 959b34653..6255c6961 100644 --- a/server/tests/client.ts +++ b/server/tests/client.ts @@ -3,7 +3,7 @@ import 'mocha' import * as chai from 'chai' import { omit } from 'lodash' -import { HttpStatusCode } from '@shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '@shared/models' import { Account, HTMLServerConfig, ServerConfig, VideoPlaylistCreateResult, VideoPlaylistPrivacy } from '@shared/models' import { cleanupTests, @@ -114,7 +114,7 @@ describe('Test a client controllers', function () { url: servers[0].url, path: basePath + id, accept: 'text/html', - statusCodeExpected: HttpStatusCode.OK_200 + expectedStatus: HttpStatusCode.OK_200 }) const port = servers[0].port @@ -135,7 +135,7 @@ describe('Test a client controllers', function () { url: servers[0].url, path: basePath + id, accept: 'text/html', - statusCodeExpected: HttpStatusCode.OK_200 + expectedStatus: HttpStatusCode.OK_200 }) const port = servers[0].port @@ -153,7 +153,7 @@ describe('Test a client controllers', function () { describe('Open Graph', function () { async function accountPageTest (path: string) { - const res = await makeGetRequest({ url: servers[0].url, path, accept: 'text/html', statusCodeExpected: HttpStatusCode.OK_200 }) + const res = await makeGetRequest({ url: servers[0].url, path, accept: 'text/html', expectedStatus: HttpStatusCode.OK_200 }) const text = res.text expect(text).to.contain(``) @@ -163,7 +163,7 @@ describe('Test a client controllers', function () { } async function channelPageTest (path: string) { - const res = await makeGetRequest({ url: servers[0].url, path, accept: 'text/html', statusCodeExpected: HttpStatusCode.OK_200 }) + const res = await makeGetRequest({ url: servers[0].url, path, accept: 'text/html', expectedStatus: HttpStatusCode.OK_200 }) const text = res.text expect(text).to.contain(``) @@ -173,7 +173,7 @@ describe('Test a client controllers', function () { } async function watchVideoPageTest (path: string) { - const res = await makeGetRequest({ url: servers[0].url, path, accept: 'text/html', statusCodeExpected: HttpStatusCode.OK_200 }) + const res = await makeGetRequest({ url: servers[0].url, path, accept: 'text/html', expectedStatus: HttpStatusCode.OK_200 }) const text = res.text expect(text).to.contain(``) @@ -183,7 +183,7 @@ describe('Test a client controllers', function () { } async function watchPlaylistPageTest (path: string) { - const res = await makeGetRequest({ url: servers[0].url, path, accept: 'text/html', statusCodeExpected: HttpStatusCode.OK_200 }) + const res = await makeGetRequest({ url: servers[0].url, path, accept: 'text/html', expectedStatus: HttpStatusCode.OK_200 }) const text = res.text expect(text).to.contain(``) @@ -226,7 +226,7 @@ describe('Test a client controllers', function () { describe('Not whitelisted', function () { async function accountPageTest (path: string) { - const res = await makeGetRequest({ url: servers[0].url, path, accept: 'text/html', statusCodeExpected: HttpStatusCode.OK_200 }) + const res = await makeGetRequest({ url: servers[0].url, path, accept: 'text/html', expectedStatus: HttpStatusCode.OK_200 }) const text = res.text expect(text).to.contain('') @@ -236,7 +236,7 @@ describe('Test a client controllers', function () { } async function channelPageTest (path: string) { - const res = await makeGetRequest({ url: servers[0].url, path, accept: 'text/html', statusCodeExpected: HttpStatusCode.OK_200 }) + const res = await makeGetRequest({ url: servers[0].url, path, accept: 'text/html', expectedStatus: HttpStatusCode.OK_200 }) const text = res.text expect(text).to.contain('') @@ -246,7 +246,7 @@ describe('Test a client controllers', function () { } async function watchVideoPageTest (path: string) { - const res = await makeGetRequest({ url: servers[0].url, path, accept: 'text/html', statusCodeExpected: HttpStatusCode.OK_200 }) + const res = await makeGetRequest({ url: servers[0].url, path, accept: 'text/html', expectedStatus: HttpStatusCode.OK_200 }) const text = res.text expect(text).to.contain('') @@ -256,7 +256,7 @@ describe('Test a client controllers', function () { } async function watchPlaylistPageTest (path: string) { - const res = await makeGetRequest({ url: servers[0].url, path, accept: 'text/html', statusCodeExpected: HttpStatusCode.OK_200 }) + const res = await makeGetRequest({ url: servers[0].url, path, accept: 'text/html', expectedStatus: HttpStatusCode.OK_200 }) const text = res.text expect(text).to.contain('') @@ -307,7 +307,7 @@ describe('Test a client controllers', function () { }) async function accountPageTest (path: string) { - const res = await makeGetRequest({ url: servers[0].url, path, accept: 'text/html', statusCodeExpected: HttpStatusCode.OK_200 }) + const res = await makeGetRequest({ url: servers[0].url, path, accept: 'text/html', expectedStatus: HttpStatusCode.OK_200 }) const text = res.text expect(text).to.contain('') @@ -315,7 +315,7 @@ describe('Test a client controllers', function () { } async function channelPageTest (path: string) { - const res = await makeGetRequest({ url: servers[0].url, path, accept: 'text/html', statusCodeExpected: HttpStatusCode.OK_200 }) + const res = await makeGetRequest({ url: servers[0].url, path, accept: 'text/html', expectedStatus: HttpStatusCode.OK_200 }) const text = res.text expect(text).to.contain('') @@ -323,7 +323,7 @@ describe('Test a client controllers', function () { } async function watchVideoPageTest (path: string) { - const res = await makeGetRequest({ url: servers[0].url, path, accept: 'text/html', statusCodeExpected: HttpStatusCode.OK_200 }) + const res = await makeGetRequest({ url: servers[0].url, path, accept: 'text/html', expectedStatus: HttpStatusCode.OK_200 }) const text = res.text expect(text).to.contain('') @@ -331,7 +331,7 @@ describe('Test a client controllers', function () { } async function watchPlaylistPageTest (path: string) { - const res = await makeGetRequest({ url: servers[0].url, path, accept: 'text/html', statusCodeExpected: HttpStatusCode.OK_200 }) + const res = await makeGetRequest({ url: servers[0].url, path, accept: 'text/html', expectedStatus: HttpStatusCode.OK_200 }) const text = res.text expect(text).to.contain('') diff --git a/server/tests/external-plugins/auth-ldap.ts b/server/tests/external-plugins/auth-ldap.ts index aaaf23278..12b4a1b8d 100644 --- a/server/tests/external-plugins/auth-ldap.ts +++ b/server/tests/external-plugins/auth-ldap.ts @@ -2,7 +2,7 @@ import 'mocha' import { expect } from 'chai' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { cleanupTests, createSingleServer, PeerTubeServer, setAccessTokensToServers } from '@shared/extra-utils' describe('Official plugin auth-ldap', function () { diff --git a/server/tests/external-plugins/auto-block-videos.ts b/server/tests/external-plugins/auto-block-videos.ts index 9cb86310b..78b13eded 100644 --- a/server/tests/external-plugins/auto-block-videos.ts +++ b/server/tests/external-plugins/auto-block-videos.ts @@ -43,10 +43,10 @@ describe('Official plugin auto-block videos', function () { blocklistServer = new MockBlocklist() port = await blocklistServer.initialize() - await await servers[0].videos.quickUpload({ name: 'video server 1' }) - await await servers[1].videos.quickUpload({ name: 'video server 2' }) - await await servers[1].videos.quickUpload({ name: 'video 2 server 2' }) - await await servers[1].videos.quickUpload({ name: 'video 3 server 2' }) + await servers[0].videos.quickUpload({ name: 'video server 1' }) + await servers[1].videos.quickUpload({ name: 'video server 2' }) + await servers[1].videos.quickUpload({ name: 'video 2 server 2' }) + await servers[1].videos.quickUpload({ name: 'video 3 server 2' }) { const { data } = await servers[0].videos.list() diff --git a/server/tests/external-plugins/auto-mute.ts b/server/tests/external-plugins/auto-mute.ts index 771201505..b2046313b 100644 --- a/server/tests/external-plugins/auto-mute.ts +++ b/server/tests/external-plugins/auto-mute.ts @@ -2,7 +2,7 @@ import 'mocha' import { expect } from 'chai' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { cleanupTests, doubleFollow, @@ -34,8 +34,8 @@ describe('Official plugin auto-mute', function () { blocklistServer = new MockBlocklist() port = await blocklistServer.initialize() - await await servers[0].videos.quickUpload({ name: 'video server 1' }) - await await servers[1].videos.quickUpload({ name: 'video server 2' }) + await servers[0].videos.quickUpload({ name: 'video server 1' }) + await servers[1].videos.quickUpload({ name: 'video server 2' }) await doubleFollow(servers[0], servers[1]) }) @@ -162,7 +162,7 @@ describe('Official plugin auto-mute', function () { await makeGetRequest({ url: servers[0].url, path: '/plugins/auto-mute/router/api/v1/mute-list', - statusCodeExpected: HttpStatusCode.FORBIDDEN_403 + expectedStatus: HttpStatusCode.FORBIDDEN_403 }) }) @@ -179,7 +179,7 @@ describe('Official plugin auto-mute', function () { await makeGetRequest({ url: servers[0].url, path: '/plugins/auto-mute/router/api/v1/mute-list', - statusCodeExpected: HttpStatusCode.OK_200 + expectedStatus: HttpStatusCode.OK_200 }) }) @@ -201,7 +201,7 @@ describe('Official plugin auto-mute', function () { const res = await makeGetRequest({ url: servers[0].url, path: '/plugins/auto-mute/router/api/v1/mute-list', - statusCodeExpected: HttpStatusCode.OK_200 + expectedStatus: HttpStatusCode.OK_200 }) const data = res.body.data diff --git a/server/tests/feeds/feeds.ts b/server/tests/feeds/feeds.ts index 7735299d3..543c431dd 100644 --- a/server/tests/feeds/feeds.ts +++ b/server/tests/feeds/feeds.ts @@ -3,7 +3,7 @@ import 'mocha' import * as chai from 'chai' import * as xmlParser from 'fast-xml-parser' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { cleanupTests, doubleFollow, diff --git a/server/tests/misc-endpoints.ts b/server/tests/misc-endpoints.ts index a4f344fcc..4d9c07f1a 100644 --- a/server/tests/misc-endpoints.ts +++ b/server/tests/misc-endpoints.ts @@ -2,7 +2,7 @@ import 'mocha' import * as chai from 'chai' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { cleanupTests, createSingleServer, makeGetRequest, PeerTubeServer, setAccessTokensToServers } from '@shared/extra-utils' import { VideoPrivacy } from '@shared/models' @@ -24,7 +24,7 @@ describe('Test misc endpoints', function () { const res = await makeGetRequest({ url: server.url, path: '/.well-known/security.txt', - statusCodeExpected: HttpStatusCode.OK_200 + expectedStatus: HttpStatusCode.OK_200 }) expect(res.text).to.contain('security issue') @@ -34,7 +34,7 @@ describe('Test misc endpoints', function () { const res = await makeGetRequest({ url: server.url, path: '/.well-known/nodeinfo', - statusCodeExpected: HttpStatusCode.OK_200 + expectedStatus: HttpStatusCode.OK_200 }) expect(res.body.links).to.be.an('array') @@ -46,7 +46,7 @@ describe('Test misc endpoints', function () { const res = await makeGetRequest({ url: server.url, path: '/.well-known/dnt-policy.txt', - statusCodeExpected: HttpStatusCode.OK_200 + expectedStatus: HttpStatusCode.OK_200 }) expect(res.text).to.contain('http://www.w3.org/TR/tracking-dnt') @@ -56,7 +56,7 @@ describe('Test misc endpoints', function () { const res = await makeGetRequest({ url: server.url, path: '/.well-known/dnt', - statusCodeExpected: HttpStatusCode.OK_200 + expectedStatus: HttpStatusCode.OK_200 }) expect(res.body.tracking).to.equal('N') @@ -66,7 +66,7 @@ describe('Test misc endpoints', function () { const res = await makeGetRequest({ url: server.url, path: '/.well-known/change-password', - statusCodeExpected: HttpStatusCode.FOUND_302 + expectedStatus: HttpStatusCode.FOUND_302 }) expect(res.header.location).to.equal('/my-account/settings') @@ -79,7 +79,7 @@ describe('Test misc endpoints', function () { const res = await makeGetRequest({ url: server.url, path: '/.well-known/webfinger?resource=' + resource, - statusCodeExpected: HttpStatusCode.OK_200 + expectedStatus: HttpStatusCode.OK_200 }) const data = res.body @@ -104,7 +104,7 @@ describe('Test misc endpoints', function () { const res = await makeGetRequest({ url: server.url, path: '/robots.txt', - statusCodeExpected: HttpStatusCode.OK_200 + expectedStatus: HttpStatusCode.OK_200 }) expect(res.text).to.contain('User-agent') @@ -114,7 +114,7 @@ describe('Test misc endpoints', function () { await makeGetRequest({ url: server.url, path: '/security.txt', - statusCodeExpected: HttpStatusCode.MOVED_PERMANENTLY_301 + expectedStatus: HttpStatusCode.MOVED_PERMANENTLY_301 }) }) @@ -122,7 +122,7 @@ describe('Test misc endpoints', function () { const res = await makeGetRequest({ url: server.url, path: '/nodeinfo/2.0.json', - statusCodeExpected: HttpStatusCode.OK_200 + expectedStatus: HttpStatusCode.OK_200 }) expect(res.body.software.name).to.equal('peertube') @@ -137,7 +137,7 @@ describe('Test misc endpoints', function () { const res = await makeGetRequest({ url: server.url, path: '/sitemap.xml', - statusCodeExpected: HttpStatusCode.OK_200 + expectedStatus: HttpStatusCode.OK_200 }) expect(res.text).to.contain('xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"') @@ -148,7 +148,7 @@ describe('Test misc endpoints', function () { const res = await makeGetRequest({ url: server.url, path: '/sitemap.xml', - statusCodeExpected: HttpStatusCode.OK_200 + expectedStatus: HttpStatusCode.OK_200 }) expect(res.text).to.contain('xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"') @@ -171,7 +171,7 @@ describe('Test misc endpoints', function () { const res = await makeGetRequest({ url: server.url, path: '/sitemap.xml?t=1', // avoid using cache - statusCodeExpected: HttpStatusCode.OK_200 + expectedStatus: HttpStatusCode.OK_200 }) expect(res.text).to.contain('xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"') diff --git a/server/tests/plugins/external-auth.ts b/server/tests/plugins/external-auth.ts index c0834a14c..a2828603a 100644 --- a/server/tests/plugins/external-auth.ts +++ b/server/tests/plugins/external-auth.ts @@ -2,7 +2,7 @@ import 'mocha' import { expect } from 'chai' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { cleanupTests, decodeQueryString, @@ -20,15 +20,15 @@ async function loginExternal (options: { authName: string username: string query?: any - statusCodeExpected?: HttpStatusCode - statusCodeExpectedStep2?: HttpStatusCode + expectedStatus?: HttpStatusCode + expectedStatusStep2?: HttpStatusCode }) { const res = await options.server.plugins.getExternalAuth({ npmName: options.npmName, npmVersion: '0.0.1', authName: options.authName, query: options.query, - expectedStatus: options.statusCodeExpected || HttpStatusCode.FOUND_302 + expectedStatus: options.expectedStatus || HttpStatusCode.FOUND_302 }) if (res.status !== HttpStatusCode.FOUND_302) return @@ -39,7 +39,7 @@ async function loginExternal (options: { const resLogin = await options.server.login.loginUsingExternalToken({ username: options.username, externalAuthToken: externalAuthToken as string, - expectedStatus: options.statusCodeExpectedStep2 + expectedStatus: options.expectedStatusStep2 }) return resLogin.body @@ -268,7 +268,7 @@ describe('Test external auth plugins', function () { username: 'kefka' }, username: 'kefka', - statusCodeExpected: HttpStatusCode.NOT_FOUND_404 + expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) @@ -293,7 +293,7 @@ describe('Test external auth plugins', function () { username: 'cyan' }, username: 'cyan', - statusCodeExpected: HttpStatusCode.NOT_FOUND_404 + expectedStatus: HttpStatusCode.NOT_FOUND_404 }) await server.login.login({ user: { username: 'cyan', password: null }, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) @@ -307,7 +307,7 @@ describe('Test external auth plugins', function () { npmName: 'test-external-auth-two', authName: 'external-auth-4', username: 'kefka2', - statusCodeExpectedStep2: HttpStatusCode.BAD_REQUEST_400 + expectedStatusStep2: HttpStatusCode.BAD_REQUEST_400 }) await loginExternal({ @@ -315,7 +315,7 @@ describe('Test external auth plugins', function () { npmName: 'test-external-auth-two', authName: 'external-auth-4', username: 'kefka', - statusCodeExpectedStep2: HttpStatusCode.BAD_REQUEST_400 + expectedStatusStep2: HttpStatusCode.BAD_REQUEST_400 }) }) @@ -327,7 +327,7 @@ describe('Test external auth plugins', function () { npmName: 'test-external-auth-two', authName: 'external-auth-6', username: 'existing_user', - statusCodeExpectedStep2: HttpStatusCode.BAD_REQUEST_400 + expectedStatusStep2: HttpStatusCode.BAD_REQUEST_400 }) }) diff --git a/server/tests/plugins/filter-hooks.ts b/server/tests/plugins/filter-hooks.ts index df52bb3b5..ba84dd27a 100644 --- a/server/tests/plugins/filter-hooks.ts +++ b/server/tests/plugins/filter-hooks.ts @@ -2,7 +2,7 @@ import 'mocha' import * as chai from 'chai' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { cleanupTests, createMultipleServers, @@ -71,28 +71,28 @@ describe('Test plugin filter hooks', function () { }) it('Should run filter:api.accounts.videos.list.params', async function () { - const { data } = await servers[0].videos.listByAccount({ accountName: 'root', start: 0, count: 2 }) + const { data } = await servers[0].videos.listByAccount({ handle: 'root', start: 0, count: 2 }) // 1 plugin do +1 to the count parameter expect(data).to.have.lengthOf(3) }) it('Should run filter:api.accounts.videos.list.result', async function () { - const { total } = await servers[0].videos.listByAccount({ accountName: 'root', start: 0, count: 2 }) + const { total } = await servers[0].videos.listByAccount({ handle: 'root', start: 0, count: 2 }) // Plugin do +2 to the total result expect(total).to.equal(12) }) it('Should run filter:api.video-channels.videos.list.params', async function () { - const { data } = await servers[0].videos.listByChannel({ videoChannelName: 'root_channel', start: 0, count: 2 }) + const { data } = await servers[0].videos.listByChannel({ handle: 'root_channel', start: 0, count: 2 }) // 1 plugin do +3 to the count parameter expect(data).to.have.lengthOf(5) }) it('Should run filter:api.video-channels.videos.list.result', async function () { - const { total } = await servers[0].videos.listByChannel({ videoChannelName: 'root_channel', start: 0, count: 2 }) + const { total } = await servers[0].videos.listByChannel({ handle: 'root_channel', start: 0, count: 2 }) // Plugin do +3 to the total result expect(total).to.equal(13) diff --git a/server/tests/plugins/id-and-pass-auth.ts b/server/tests/plugins/id-and-pass-auth.ts index 981bcad91..a73d76caa 100644 --- a/server/tests/plugins/id-and-pass-auth.ts +++ b/server/tests/plugins/id-and-pass-auth.ts @@ -2,7 +2,7 @@ import 'mocha' import { expect } from 'chai' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { cleanupTests, createSingleServer, PluginsCommand, PeerTubeServer, setAccessTokensToServers, wait } from '@shared/extra-utils' import { UserRole } from '@shared/models' diff --git a/server/tests/plugins/plugin-helpers.ts b/server/tests/plugins/plugin-helpers.ts index 1d87b84ae..5cb664bda 100644 --- a/server/tests/plugins/plugin-helpers.ts +++ b/server/tests/plugins/plugin-helpers.ts @@ -2,7 +2,7 @@ import 'mocha' import { expect } from 'chai' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { checkVideoFilesWereRemoved, cleanupTests, @@ -24,7 +24,7 @@ function postCommand (server: PeerTubeServer, command: string, bodyArg?: object) url: server.url, path: '/plugins/test-four/router/commander', fields: body, - statusCodeExpected: HttpStatusCode.NO_CONTENT_204 + expectedStatus: HttpStatusCode.NO_CONTENT_204 }) } @@ -67,7 +67,7 @@ describe('Test plugin helpers', function () { const res = await makeGetRequest({ url: servers[0].url, path: '/plugins/test-four/router/server-config', - statusCodeExpected: HttpStatusCode.OK_200 + expectedStatus: HttpStatusCode.OK_200 }) expect(res.body.serverConfig).to.exist @@ -88,7 +88,7 @@ describe('Test plugin helpers', function () { const res = await makeGetRequest({ url: servers[0].url, path: '/plugins/test-four/router/static-route', - statusCodeExpected: HttpStatusCode.OK_200 + expectedStatus: HttpStatusCode.OK_200 }) expect(res.body.staticRoute).to.equal('/plugins/test-four/0.0.1/static/') @@ -100,7 +100,7 @@ describe('Test plugin helpers', function () { const res = await makeGetRequest({ url: servers[0].url, path: baseRouter + 'router-route', - statusCodeExpected: HttpStatusCode.OK_200 + expectedStatus: HttpStatusCode.OK_200 }) expect(res.body.routerRoute).to.equal(baseRouter) @@ -113,7 +113,7 @@ describe('Test plugin helpers', function () { await makeGetRequest({ url: servers[0].url, path: '/plugins/test-four/router/user', - statusCodeExpected: HttpStatusCode.NOT_FOUND_404 + expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) @@ -122,7 +122,7 @@ describe('Test plugin helpers', function () { url: servers[0].url, token: servers[0].accessToken, path: '/plugins/test-four/router/user', - statusCodeExpected: HttpStatusCode.OK_200 + expectedStatus: HttpStatusCode.OK_200 }) expect(res.body.username).to.equal('root') @@ -140,12 +140,12 @@ describe('Test plugin helpers', function () { this.timeout(60000) { - const res = await await servers[0].videos.quickUpload({ name: 'video server 1' }) + const res = await servers[0].videos.quickUpload({ name: 'video server 1' }) videoUUIDServer1 = res.uuid } { - await await servers[1].videos.quickUpload({ name: 'video server 2' }) + await servers[1].videos.quickUpload({ name: 'video server 2' }) } await waitJobs(servers) @@ -224,7 +224,7 @@ describe('Test plugin helpers', function () { let videoUUID: string before(async () => { - const res = await await servers[0].videos.quickUpload({ name: 'video1' }) + const res = await servers[0].videos.quickUpload({ name: 'video1' }) videoUUID = res.uuid }) diff --git a/server/tests/plugins/plugin-router.ts b/server/tests/plugins/plugin-router.ts index dec8ca4bb..becb7c47b 100644 --- a/server/tests/plugins/plugin-router.ts +++ b/server/tests/plugins/plugin-router.ts @@ -2,7 +2,7 @@ import 'mocha' import { expect } from 'chai' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { cleanupTests, createSingleServer, @@ -34,7 +34,7 @@ describe('Test plugin helpers', function () { const res = await makeGetRequest({ url: server.url, path: path + 'ping', - statusCodeExpected: HttpStatusCode.OK_200 + expectedStatus: HttpStatusCode.OK_200 }) expect(res.body.message).to.equal('pong') @@ -47,7 +47,7 @@ describe('Test plugin helpers', function () { url: server.url, path: path + 'is-authenticated', token: server.accessToken, - statusCodeExpected: 200 + expectedStatus: 200 }) expect(res.body.isAuthenticated).to.equal(true) @@ -55,7 +55,7 @@ describe('Test plugin helpers', function () { const secRes = await makeGetRequest({ url: server.url, path: path + 'is-authenticated', - statusCodeExpected: 200 + expectedStatus: 200 }) expect(secRes.body.isAuthenticated).to.equal(false) @@ -74,7 +74,7 @@ describe('Test plugin helpers', function () { url: server.url, path: path + 'form/post/mirror', fields: body, - statusCodeExpected: HttpStatusCode.OK_200 + expectedStatus: HttpStatusCode.OK_200 }) expect(res.body).to.deep.equal(body) @@ -88,14 +88,14 @@ describe('Test plugin helpers', function () { await makeGetRequest({ url: server.url, path: path + 'ping', - statusCodeExpected: HttpStatusCode.NOT_FOUND_404 + expectedStatus: HttpStatusCode.NOT_FOUND_404 }) await makePostBodyRequest({ url: server.url, path: path + 'ping', fields: {}, - statusCodeExpected: HttpStatusCode.NOT_FOUND_404 + expectedStatus: HttpStatusCode.NOT_FOUND_404 }) } }) diff --git a/server/tests/plugins/plugin-storage.ts b/server/tests/plugins/plugin-storage.ts index 5745914a5..90dafa3e1 100644 --- a/server/tests/plugins/plugin-storage.ts +++ b/server/tests/plugins/plugin-storage.ts @@ -4,7 +4,7 @@ import 'mocha' import { expect } from 'chai' import { pathExists, readdir, readFile } from 'fs-extra' import { join } from 'path' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { cleanupTests, createSingleServer, @@ -63,7 +63,7 @@ describe('Test plugin storage', function () { url: server.url, token: server.accessToken, path: '/plugins/test-six/router/create-file', - statusCodeExpected: HttpStatusCode.OK_200 + expectedStatus: HttpStatusCode.OK_200 }) const content = await getFileContent() diff --git a/server/tests/plugins/plugin-unloading.ts b/server/tests/plugins/plugin-unloading.ts index 6c405b7f5..faf9cc599 100644 --- a/server/tests/plugins/plugin-unloading.ts +++ b/server/tests/plugins/plugin-unloading.ts @@ -2,7 +2,7 @@ import 'mocha' import { expect } from 'chai' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { cleanupTests, createSingleServer, @@ -30,7 +30,7 @@ describe('Test plugins module unloading', function () { const res = await makeGetRequest({ url: server.url, path: requestPath, - statusCodeExpected: HttpStatusCode.OK_200 + expectedStatus: HttpStatusCode.OK_200 }) expect(res.body.message).to.match(/^\d+$/) @@ -41,7 +41,7 @@ describe('Test plugins module unloading', function () { const res = await makeGetRequest({ url: server.url, path: requestPath, - statusCodeExpected: HttpStatusCode.OK_200 + expectedStatus: HttpStatusCode.OK_200 }) expect(res.body.message).to.be.equal(value) @@ -53,7 +53,7 @@ describe('Test plugins module unloading', function () { await makeGetRequest({ url: server.url, path: requestPath, - statusCodeExpected: HttpStatusCode.NOT_FOUND_404 + expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) @@ -63,7 +63,7 @@ describe('Test plugins module unloading', function () { const res = await makeGetRequest({ url: server.url, path: requestPath, - statusCodeExpected: HttpStatusCode.OK_200 + expectedStatus: HttpStatusCode.OK_200 }) expect(res.body.message).to.match(/^\d+$/) diff --git a/server/tests/plugins/video-constants.ts b/server/tests/plugins/video-constants.ts index 953916e8e..dd3b40225 100644 --- a/server/tests/plugins/video-constants.ts +++ b/server/tests/plugins/video-constants.ts @@ -2,7 +2,7 @@ import 'mocha' import * as chai from 'chai' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { cleanupTests, createSingleServer, PluginsCommand, PeerTubeServer, setAccessTokensToServers } from '@shared/extra-utils' import { VideoPlaylistPrivacy } from '@shared/models' diff --git a/server/tools/peertube-redundancy.ts b/server/tools/peertube-redundancy.ts index 5fda68c8e..bcaae63a3 100644 --- a/server/tools/peertube-redundancy.ts +++ b/server/tools/peertube-redundancy.ts @@ -6,7 +6,7 @@ import { Command, program } from 'commander' import { uniq } from 'lodash' import { URL } from 'url' import validator from 'validator' -import { HttpStatusCode } from '@shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '@shared/models' import { VideoRedundanciesTarget } from '@shared/models' import { assignToken, buildServer, getServerCredentials } from './cli' diff --git a/server/typings/express/index.d.ts b/server/typings/express/index.d.ts index 1a8dc3430..5469f3b83 100644 --- a/server/typings/express/index.d.ts +++ b/server/typings/express/index.d.ts @@ -22,8 +22,7 @@ import { MPlugin, MServer, MServerBlocklist } from '@server/types/models/server' import { MVideoImportDefault } from '@server/types/models/video/video-import' import { MVideoPlaylistElement, MVideoPlaylistElementVideoUrlPlaylistPrivacy } from '@server/types/models/video/video-playlist-element' import { MAccountVideoRateAccountVideo } from '@server/types/models/video/video-rate' -import { HttpMethod } from '@shared/core-utils/miscs/http-methods' -import { PeerTubeProblemDocumentData, ServerErrorCode, VideoCreate } from '@shared/models' +import { HttpMethod, PeerTubeProblemDocumentData, ServerErrorCode, VideoCreate } from '@shared/models' import { File as UploadXFile, Metadata } from '@uploadx/core' import { RegisteredPlugin } from '../../lib/plugins/plugin-manager' import { diff --git a/shared/core-utils/miscs/http-error-codes.ts b/shared/core-utils/miscs/http-error-codes.ts deleted file mode 100644 index b2fbdfc5a..000000000 --- a/shared/core-utils/miscs/http-error-codes.ts +++ /dev/null @@ -1,364 +0,0 @@ -/** - * Hypertext Transfer Protocol (HTTP) response status codes. - * @see {@link https://en.wikipedia.org/wiki/List_of_HTTP_status_codes} - * - * WebDAV and other codes useless with regards to PeerTube are not listed. - */ -export enum HttpStatusCode { - - /** - * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.2.1 - * - * The server has received the request headers and the client should proceed to send the request body - * (in the case of a request for which a body needs to be sent; for example, a POST request). - * Sending a large request body to a server after a request has been rejected for inappropriate headers would be inefficient. - * To have a server check the request's headers, a client must send Expect: 100-continue as a header in its initial request - * and receive a 100 Continue status code in response before sending the body. The response 417 Expectation Failed indicates - * the request should not be continued. - */ - CONTINUE_100 = 100, - - /** - * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.2.2 - * - * This code is sent in response to an Upgrade request header by the client, and indicates the protocol the server is switching too. - */ - SWITCHING_PROTOCOLS_101 = 101, - - /** - * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.1 - * - * Standard response for successful HTTP requests. The actual response will depend on the request method used: - * GET: The resource has been fetched and is transmitted in the message body. - * HEAD: The entity headers are in the message body. - * POST: The resource describing the result of the action is transmitted in the message body. - * TRACE: The message body contains the request message as received by the server - */ - OK_200 = 200, - - /** - * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.2 - * - * The request has been fulfilled, resulting in the creation of a new resource, typically after a PUT. - */ - CREATED_201 = 201, - - /** - * The request has been accepted for processing, but the processing has not been completed. - * The request might or might not be eventually acted upon, and may be disallowed when processing occurs. - */ - ACCEPTED_202 = 202, - - /** - * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.5 - * - * There is no content to send for this request, but the headers may be useful. - * The user-agent may update its cached headers for this resource with the new ones. - */ - NO_CONTENT_204 = 204, - - /** - * The server successfully processed the request, but is not returning any content. - * Unlike a 204 response, this response requires that the requester reset the document view. - */ - RESET_CONTENT_205 = 205, - - /** - * The server is delivering only part of the resource (byte serving) due to a range header sent by the client. - * The range header is used by HTTP clients to enable resuming of interrupted downloads, - * or split a download into multiple simultaneous streams. - */ - PARTIAL_CONTENT_206 = 206, - - /** - * Indicates multiple options for the resource from which the client may choose (via agent-driven content negotiation). - * For example, this code could be used to present multiple video format options, - * to list files with different filename extensions, or to suggest word-sense disambiguation. - */ - MULTIPLE_CHOICES_300 = 300, - - /** - * This and all future requests should be directed to the given URI. - */ - MOVED_PERMANENTLY_301 = 301, - - /** - * This is an example of industry practice contradicting the standard. - * The HTTP/1.0 specification (RFC 1945) required the client to perform a temporary redirect - * (the original describing phrase was "Moved Temporarily"), but popular browsers implemented 302 - * with the functionality of a 303 See Other. Therefore, HTTP/1.1 added status codes 303 and 307 - * to distinguish between the two behaviours. However, some Web applications and frameworks - * use the 302 status code as if it were the 303. - */ - FOUND_302 = 302, - - /** - * SINCE HTTP/1.1 - * The response to the request can be found under another URI using a GET method. - * When received in response to a POST (or PUT/DELETE), the client should presume that - * the server has received the data and should issue a redirect with a separate GET message. - */ - SEE_OTHER_303 = 303, - - /** - * Official Documentation @ https://tools.ietf.org/html/rfc7232#section-4.1 - * - * Indicates that the resource has not been modified since the version specified by the request headers - * `If-Modified-Since` or `If-None-Match`. - * In such case, there is no need to retransmit the resource since the client still has a previously-downloaded copy. - */ - NOT_MODIFIED_304 = 304, - - /** - * SINCE HTTP/1.1 - * In this case, the request should be repeated with another URI; however, future requests should still use the original URI. - * In contrast to how 302 was historically implemented, the request method is not allowed to be changed when reissuing the - * original request. - * For example, a POST request should be repeated using another POST request. - */ - TEMPORARY_REDIRECT_307 = 307, - - /** - * The request and all future requests should be repeated using another URI. - * 307 and 308 parallel the behaviors of 302 and 301, but do not allow the HTTP method to change. - * So, for example, submitting a form to a permanently redirected resource may continue smoothly. - */ - PERMANENT_REDIRECT_308 = 308, - - /** - * The server cannot or will not process the request due to an apparent client error - * (e.g., malformed request syntax, too large size, invalid request message framing, or deceptive request routing). - */ - BAD_REQUEST_400 = 400, - - /** - * Official Documentation @ https://tools.ietf.org/html/rfc7235#section-3.1 - * - * Similar to 403 Forbidden, but specifically for use when authentication is required and has failed or has not yet - * been provided. The response must include a `WWW-Authenticate` header field containing a challenge applicable to the - * requested resource. See Basic access authentication and Digest access authentication. 401 semantically means - * "unauthenticated",i.e. the user does not have the necessary credentials. - */ - UNAUTHORIZED_401 = 401, - - /** - * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.2 - * - * Reserved for future use. The original intention was that this code might be used as part of some form of digital - * cash or micro payment scheme, but that has not happened, and this code is not usually used. - * Google Developers API uses this status if a particular developer has exceeded the daily limit on requests. - */ - PAYMENT_REQUIRED_402 = 402, - - /** - * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.3 - * - * The client does not have access rights to the content, i.e. they are unauthorized, so server is rejecting to - * give proper response. Unlike 401, the client's identity is known to the server. - */ - FORBIDDEN_403 = 403, - - /** - * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.2 - * - * The requested resource could not be found but may be available in the future. - * Subsequent requests by the client are permissible. - */ - NOT_FOUND_404 = 404, - - /** - * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.5 - * - * A request method is not supported for the requested resource; - * for example, a GET request on a form that requires data to be presented via POST, or a PUT request on a read-only resource. - */ - METHOD_NOT_ALLOWED_405 = 405, - - /** - * The requested resource is capable of generating only content not acceptable according to the Accept headers sent in the request. - */ - NOT_ACCEPTABLE_406 = 406, - - /** - * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.7 - * - * This response is sent on an idle connection by some servers, even without any previous request by the client. - * It means that the server would like to shut down this unused connection. This response is used much more since - * some browsers, like Chrome, Firefox 27+, or IE9, use HTTP pre-connection mechanisms to speed up surfing. Also - * note that some servers merely shut down the connection without sending this message. - * - * @ - */ - REQUEST_TIMEOUT_408 = 408, - - /** - * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.8 - * - * Indicates that the request could not be processed because of conflict in the request, - * such as an edit conflict between multiple simultaneous updates. - * - * @see HttpStatusCode.UNPROCESSABLE_ENTITY_422 to denote a disabled feature - */ - CONFLICT_409 = 409, - - /** - * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.9 - * - * Indicates that the resource requested is no longer available and will not be available again. - * This should be used when a resource has been intentionally removed and the resource should be purged. - * Upon receiving a 410 status code, the client should not request the resource in the future. - * Clients such as search engines should remove the resource from their indices. - * Most use cases do not require clients and search engines to purge the resource, and a "404 Not Found" may be used instead. - */ - GONE_410 = 410, - - /** - * The request did not specify the length of its content, which is required by the requested resource. - */ - LENGTH_REQUIRED_411 = 411, - - /** - * The server does not meet one of the preconditions that the requester put on the request. - */ - PRECONDITION_FAILED_412 = 412, - - /** - * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.11 - * - * The request is larger than the server is willing or able to process ; the server might close the connection - * or return an Retry-After header field. - * Previously called "Request Entity Too Large". - */ - PAYLOAD_TOO_LARGE_413 = 413, - - /** - * The URI provided was too long for the server to process. Often the result of too much data being encoded as a - * query-string of a GET request, in which case it should be converted to a POST request. - * Called "Request-URI Too Long" previously. - */ - URI_TOO_LONG_414 = 414, - - /** - * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.13 - * - * The request entity has a media type which the server or resource does not support. - * For example, the client uploads an image as image/svg+xml, but the server requires that images use a different format. - */ - UNSUPPORTED_MEDIA_TYPE_415 = 415, - - /** - * The client has asked for a portion of the file (byte serving), but the server cannot supply that portion. - * For example, if the client asked for a part of the file that lies beyond the end of the file. - * Called "Requested Range Not Satisfiable" previously. - */ - RANGE_NOT_SATISFIABLE_416 = 416, - - /** - * The server cannot meet the requirements of the `Expect` request-header field. - */ - EXPECTATION_FAILED_417 = 417, - - /** - * Official Documentation @ https://tools.ietf.org/html/rfc2324 - * - * This code was defined in 1998 as one of the traditional IETF April Fools' jokes, in RFC 2324, Hyper Text Coffee Pot Control Protocol, - * and is not expected to be implemented by actual HTTP servers. The RFC specifies this code should be returned by - * teapots requested to brew coffee. This HTTP status is used as an Easter egg in some websites, including PeerTube instances ;-). - */ - I_AM_A_TEAPOT_418 = 418, - - /** - * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.3 - * - * The request was well-formed but was unable to be followed due to semantic errors. - * The server understands the content type of the request entity (hence a 415 (Unsupported Media Type) status code is inappropriate), - * and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process - * the contained instructions. For example, this error condition may occur if an JSON request body contains well-formed (i.e., - * syntactically correct), but semantically erroneous, JSON instructions. - * - * Can also be used to denote disabled features (akin to disabled syntax). - * - * @see HttpStatusCode.UNSUPPORTED_MEDIA_TYPE_415 if the `Content-Type` was not supported. - * @see HttpStatusCode.BAD_REQUEST_400 if the request was not parsable (broken JSON, XML) - */ - UNPROCESSABLE_ENTITY_422 = 422, - - /** - * Official Documentation @ https://tools.ietf.org/html/rfc4918#section-11.3 - * - * The resource that is being accessed is locked. WebDAV-specific but used by some HTTP services. - * - * @deprecated use `If-Match` / `If-None-Match` instead - * @see {@link https://evertpot.com/http/423-locked} - */ - LOCKED_423 = 423, - - /** - * Official Documentation @ https://tools.ietf.org/html/rfc6585#section-4 - * - * The user has sent too many requests in a given amount of time. Intended for use with rate-limiting schemes. - */ - TOO_MANY_REQUESTS_429 = 429, - - /** - * Official Documentation @ https://tools.ietf.org/html/rfc6585#section-5 - * - * The server is unwilling to process the request because either an individual header field, - * or all the header fields collectively, are too large. - */ - REQUEST_HEADER_FIELDS_TOO_LARGE_431 = 431, - - /** - * Official Documentation @ https://tools.ietf.org/html/rfc7725 - * - * A server operator has received a legal demand to deny access to a resource or to a set of resources - * that includes the requested resource. The code 451 was chosen as a reference to the novel Fahrenheit 451. - */ - UNAVAILABLE_FOR_LEGAL_REASONS_451 = 451, - - /** - * A generic error message, given when an unexpected condition was encountered and no more specific message is suitable. - */ - INTERNAL_SERVER_ERROR_500 = 500, - - /** - * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.2 - * - * The server either does not recognize the request method, or it lacks the ability to fulfill the request. - * Usually this implies future availability (e.g., a new feature of a web-service API). - */ - NOT_IMPLEMENTED_501 = 501, - - /** - * The server was acting as a gateway or proxy and received an invalid response from the upstream server. - */ - BAD_GATEWAY_502 = 502, - - /** - * The server is currently unavailable (because it is overloaded or down for maintenance). - * Generally, this is a temporary state. - */ - SERVICE_UNAVAILABLE_503 = 503, - - /** - * The server was acting as a gateway or proxy and did not receive a timely response from the upstream server. - */ - GATEWAY_TIMEOUT_504 = 504, - - /** - * The server does not support the HTTP protocol version used in the request - */ - HTTP_VERSION_NOT_SUPPORTED_505 = 505, - - /** - * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.6 - * - * The 507 (Insufficient Storage) status code means the method could not be performed on the resource because the - * server is unable to store the representation needed to successfully complete the request. This condition is - * considered to be temporary. If the request which received this status code was the result of a user action, - * the request MUST NOT be repeated until it is requested by a separate user action. - * - * @see HttpStatusCode.PAYLOAD_TOO_LARGE_413 for quota errors - */ - INSUFFICIENT_STORAGE_507 = 507, -} diff --git a/shared/core-utils/miscs/http-methods.ts b/shared/core-utils/miscs/http-methods.ts deleted file mode 100644 index 1cfa458b9..000000000 --- a/shared/core-utils/miscs/http-methods.ts +++ /dev/null @@ -1,21 +0,0 @@ -/** HTTP request method to indicate the desired action to be performed for a given resource. */ -export enum HttpMethod { - /** The CONNECT method establishes a tunnel to the server identified by the target resource. */ - CONNECT = 'CONNECT', - /** The DELETE method deletes the specified resource. */ - DELETE = 'DELETE', - /** The GET method requests a representation of the specified resource. Requests using GET should only retrieve data. */ - GET = 'GET', - /** The HEAD method asks for a response identical to that of a GET request, but without the response body. */ - HEAD = 'HEAD', - /** The OPTIONS method is used to describe the communication options for the target resource. */ - OPTIONS = 'OPTIONS', - /** The PATCH method is used to apply partial modifications to a resource. */ - PATCH = 'PATCH', - /** The POST method is used to submit an entity to the specified resource */ - POST = 'POST', - /** The PUT method replaces all current representations of the target resource with the request payload. */ - PUT = 'PUT', - /** The TRACE method performs a message loop-back test along the path to the target resource. */ - TRACE = 'TRACE' -} diff --git a/shared/core-utils/miscs/index.ts b/shared/core-utils/miscs/index.ts index 251df1de2..afd147f24 100644 --- a/shared/core-utils/miscs/index.ts +++ b/shared/core-utils/miscs/index.ts @@ -1,5 +1,3 @@ export * from './date' export * from './miscs' export * from './types' -export * from './http-error-codes' -export * from './http-methods' diff --git a/shared/extra-utils/bulk/bulk-command.ts b/shared/extra-utils/bulk/bulk-command.ts index 6dac6034f..b5c5673ce 100644 --- a/shared/extra-utils/bulk/bulk-command.ts +++ b/shared/extra-utils/bulk/bulk-command.ts @@ -1,6 +1,4 @@ - -import { BulkRemoveCommentsOfBody } from '@shared/models/bulk/bulk-remove-comments-of-body.model' -import { HttpStatusCode } from '../../core-utils/miscs/http-error-codes' +import { BulkRemoveCommentsOfBody, HttpStatusCode } from '@shared/models' import { AbstractCommand, OverrideCommandOptions } from '../shared' export class BulkCommand extends AbstractCommand { diff --git a/shared/extra-utils/custom-pages/custom-pages-command.ts b/shared/extra-utils/custom-pages/custom-pages-command.ts index 0dd77503e..6042233d4 100644 --- a/shared/extra-utils/custom-pages/custom-pages-command.ts +++ b/shared/extra-utils/custom-pages/custom-pages-command.ts @@ -1,5 +1,5 @@ import { CustomPage } from '@shared/models' -import { HttpStatusCode } from '../../core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '@shared/models' import { AbstractCommand, OverrideCommandOptions } from '../shared' export class CustomPagesCommand extends AbstractCommand { diff --git a/shared/extra-utils/feeds/feeds-command.ts b/shared/extra-utils/feeds/feeds-command.ts index 2da4110a7..3c95f9536 100644 --- a/shared/extra-utils/feeds/feeds-command.ts +++ b/shared/extra-utils/feeds/feeds-command.ts @@ -1,5 +1,5 @@ -import { HttpStatusCode } from '../../core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '@shared/models' import { AbstractCommand, OverrideCommandOptions } from '../shared' type FeedType = 'videos' | 'video-comments' | 'subscriptions' diff --git a/shared/extra-utils/logs/logs-command.ts b/shared/extra-utils/logs/logs-command.ts index f34c58c47..5912e814f 100644 --- a/shared/extra-utils/logs/logs-command.ts +++ b/shared/extra-utils/logs/logs-command.ts @@ -1,4 +1,4 @@ -import { HttpStatusCode } from '../../core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '@shared/models' import { LogLevel } from '../../models/server/log-level.type' import { AbstractCommand, OverrideCommandOptions } from '../shared' diff --git a/shared/extra-utils/miscs/checks.ts b/shared/extra-utils/miscs/checks.ts index c81460330..7fc92f804 100644 --- a/shared/extra-utils/miscs/checks.ts +++ b/shared/extra-utils/miscs/checks.ts @@ -4,7 +4,7 @@ import { expect } from 'chai' import { pathExists, readFile } from 'fs-extra' import { join } from 'path' import { root } from '@server/helpers/core-utils' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { makeGetRequest } from '../requests' import { PeerTubeServer } from '../server' @@ -20,7 +20,7 @@ async function testImage (url: string, imageName: string, imagePath: string, ext const res = await makeGetRequest({ url, path: imagePath, - statusCodeExpected: HttpStatusCode.OK_200 + expectedStatus: HttpStatusCode.OK_200 }) const body = res.body diff --git a/shared/extra-utils/moderation/abuses-command.ts b/shared/extra-utils/moderation/abuses-command.ts index 03da0c85a..72f2c9951 100644 --- a/shared/extra-utils/moderation/abuses-command.ts +++ b/shared/extra-utils/moderation/abuses-command.ts @@ -10,7 +10,7 @@ import { ResultList, UserAbuse } from '@shared/models' -import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '@shared/models' import { AbstractCommand, OverrideCommandOptions } from '../shared' import { unwrapBody } from '../requests/requests' diff --git a/shared/extra-utils/overviews/overviews-command.ts b/shared/extra-utils/overviews/overviews-command.ts index e15644d94..d4a2ac254 100644 --- a/shared/extra-utils/overviews/overviews-command.ts +++ b/shared/extra-utils/overviews/overviews-command.ts @@ -1,4 +1,4 @@ -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { VideosOverview } from '@shared/models' import { AbstractCommand, OverrideCommandOptions } from '../shared' diff --git a/shared/extra-utils/requests/check-api-params.ts b/shared/extra-utils/requests/check-api-params.ts index 7df63b004..26ba1e913 100644 --- a/shared/extra-utils/requests/check-api-params.ts +++ b/shared/extra-utils/requests/check-api-params.ts @@ -1,4 +1,4 @@ -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { makeGetRequest } from './requests' function checkBadStartPagination (url: string, path: string, token?: string, query = {}) { @@ -7,7 +7,7 @@ function checkBadStartPagination (url: string, path: string, token?: string, que path, token, query: { ...query, start: 'hello' }, - statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 + expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) } @@ -17,7 +17,7 @@ async function checkBadCountPagination (url: string, path: string, token?: strin path, token, query: { ...query, count: 'hello' }, - statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 + expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) await makeGetRequest({ @@ -25,7 +25,7 @@ async function checkBadCountPagination (url: string, path: string, token?: strin path, token, query: { ...query, count: 2000 }, - statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 + expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) } @@ -35,7 +35,7 @@ function checkBadSortPagination (url: string, path: string, token?: string, quer path, token, query: { ...query, sort: 'hello' }, - statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 + expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) } diff --git a/shared/extra-utils/requests/requests.ts b/shared/extra-utils/requests/requests.ts index 60c9b938b..70f790222 100644 --- a/shared/extra-utils/requests/requests.ts +++ b/shared/extra-utils/requests/requests.ts @@ -1,111 +1,82 @@ -/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/no-floating-promises */ +/* eslint-disable @typescript-eslint/no-floating-promises */ -import { isAbsolute, join } from 'path' import { decode } from 'querystring' import * as request from 'supertest' import { URL } from 'url' -import { HttpStatusCode } from '@shared/core-utils' -import { buildAbsoluteFixturePath, root } from '../miscs/tests' +import { HttpStatusCode } from '@shared/models' +import { buildAbsoluteFixturePath } from '../miscs/tests' -function makeRawRequest (url: string, statusCodeExpected?: HttpStatusCode, range?: string) { - const { host, protocol, pathname } = new URL(url) - - return makeGetRequest({ url: `${protocol}//${host}`, path: pathname, statusCodeExpected, range }) -} - -function makeGetRequest (options: { +export type CommonRequestParams = { url: string path?: string - query?: any - token?: string - statusCodeExpected?: HttpStatusCode contentType?: string range?: string redirects?: number accept?: string host?: string -}) { - if (!options.statusCodeExpected) options.statusCodeExpected = HttpStatusCode.BAD_REQUEST_400 - if (options.contentType === undefined) options.contentType = 'application/json' - - const req = request(options.url).get(options.path) + token?: string + headers?: { [ name: string ]: string } + type?: string + xForwardedFor?: string + expectedStatus?: HttpStatusCode +} - if (options.contentType) req.set('Accept', options.contentType) - if (options.token) req.set('Authorization', 'Bearer ' + options.token) - if (options.query) req.query(options.query) - if (options.range) req.set('Range', options.range) - if (options.accept) req.set('Accept', options.accept) - if (options.host) req.set('Host', options.host) - if (options.redirects) req.redirects(options.redirects) +function makeRawRequest (url: string, expectedStatus?: HttpStatusCode, range?: string) { + const { host, protocol, pathname } = new URL(url) - return req.expect(options.statusCodeExpected) + return makeGetRequest({ url: `${protocol}//${host}`, path: pathname, expectedStatus, range }) } -function makeDeleteRequest (options: { - url: string - path: string - token?: string - statusCodeExpected?: HttpStatusCode +function makeGetRequest (options: CommonRequestParams & { + query?: any }) { - if (!options.statusCodeExpected) options.statusCodeExpected = HttpStatusCode.BAD_REQUEST_400 + const req = request(options.url).get(options.path) + .query(options.query) - const req = request(options.url) - .delete(options.path) - .set('Accept', 'application/json') + return buildRequest(req, { contentType: 'application/json', expectedStatus: HttpStatusCode.BAD_REQUEST_400, ...options }) +} - if (options.token) req.set('Authorization', 'Bearer ' + options.token) +function makeHTMLRequest (url: string, path: string) { + return makeGetRequest({ + url, + path, + accept: 'text/html', + expectedStatus: HttpStatusCode.OK_200 + }) +} - return req.expect(options.statusCodeExpected) +function makeActivityPubGetRequest (url: string, path: string, expectedStatus = HttpStatusCode.OK_200) { + return makeGetRequest({ + url, + path, + expectedStatus: expectedStatus, + accept: 'application/activity+json,text/html;q=0.9,\\*/\\*;q=0.8' + }) } -function makeUploadRequest (options: { - url: string +function makeDeleteRequest (options: CommonRequestParams) { + const req = request(options.url).delete(options.path) + + return buildRequest(req, { accept: 'application/json', expectedStatus: HttpStatusCode.BAD_REQUEST_400, ...options }) +} + +function makeUploadRequest (options: CommonRequestParams & { method?: 'POST' | 'PUT' - path: string - token?: string fields: { [ fieldName: string ]: any } attaches?: { [ attachName: string ]: any | any[] } - - headers?: { [ name: string ]: string } - - statusCodeExpected?: HttpStatusCode }) { - if (options.statusCodeExpected === undefined) { - options.statusCodeExpected = HttpStatusCode.BAD_REQUEST_400 - } + let req = options.method === 'PUT' + ? request(options.url).put(options.path) + : request(options.url).post(options.path) - let req: request.Test - if (options.method === 'PUT') { - req = request(options.url).put(options.path) - } else { - req = request(options.url).post(options.path) - } + req = buildRequest(req, { accept: 'application/json', expectedStatus: HttpStatusCode.BAD_REQUEST_400, ...options }) - req.set('Accept', 'application/json') - - if (options.token) req.set('Authorization', 'Bearer ' + options.token) - - Object.keys(options.headers || {}).forEach(name => { - req.set(name, options.headers[name]) - }) - - Object.keys(options.fields).forEach(field => { - const value = options.fields[field] - - if (value === undefined) return - - if (Array.isArray(value)) { - for (let i = 0; i < value.length; i++) { - req.field(field + '[' + i + ']', value[i]) - } - } else { - req.field(field, value) - } - }) + buildFields(req, options.fields) Object.keys(options.attaches || {}).forEach(attach => { const value = options.attaches[attach] + if (Array.isArray(value)) { req.attach(attach, buildAbsoluteFixturePath(value[0]), value[1]) } else { @@ -113,40 +84,16 @@ function makeUploadRequest (options: { } }) - if (options.statusCodeExpected) { - req.expect(options.statusCodeExpected) - } - return req } -function makePostBodyRequest (options: { - url: string - path: string - token?: string +function makePostBodyRequest (options: CommonRequestParams & { fields?: { [ fieldName: string ]: any } - headers?: { [ name: string ]: string } - type?: string - xForwardedFor?: string - statusCodeExpected?: HttpStatusCode }) { - if (!options.fields) options.fields = {} - if (!options.statusCodeExpected) options.statusCodeExpected = HttpStatusCode.BAD_REQUEST_400 - - const req = request(options.url) - .post(options.path) - .set('Accept', 'application/json') + const req = request(options.url).post(options.path) + .send(options.fields) - if (options.token) req.set('Authorization', 'Bearer ' + options.token) - if (options.xForwardedFor) req.set('X-Forwarded-For', options.xForwardedFor) - if (options.type) req.type(options.type) - - Object.keys(options.headers || {}).forEach(name => { - req.set(name, options.headers[name]) - }) - - return req.send(options.fields) - .expect(options.statusCodeExpected) + return buildRequest(req, { accept: 'application/json', expectedStatus: HttpStatusCode.BAD_REQUEST_400, ...options }) } function makePutBodyRequest (options: { @@ -154,58 +101,12 @@ function makePutBodyRequest (options: { path: string token?: string fields: { [ fieldName: string ]: any } - statusCodeExpected?: HttpStatusCode -}) { - if (!options.statusCodeExpected) options.statusCodeExpected = HttpStatusCode.BAD_REQUEST_400 - - const req = request(options.url) - .put(options.path) - .set('Accept', 'application/json') - - if (options.token) req.set('Authorization', 'Bearer ' + options.token) - - return req.send(options.fields) - .expect(options.statusCodeExpected) -} - -function makeHTMLRequest (url: string, path: string) { - return request(url) - .get(path) - .set('Accept', 'text/html') - .expect(HttpStatusCode.OK_200) -} - -function makeActivityPubGetRequest (url: string, path: string, expectedStatus = HttpStatusCode.OK_200) { - return makeGetRequest({ - url, - path, - statusCodeExpected: expectedStatus, - accept: 'application/activity+json,text/html;q=0.9,\\*/\\*;q=0.8' - }) -} - -function updateImageRequest (options: { - url: string - path: string - accessToken: string - fixture: string - fieldname: string + expectedStatus?: HttpStatusCode }) { - let filePath = '' - if (isAbsolute(options.fixture)) { - filePath = options.fixture - } else { - filePath = join(root(), 'server', 'tests', 'fixtures', options.fixture) - } + const req = request(options.url).put(options.path) + .send(options.fields) - return makeUploadRequest({ - url: options.url, - path: options.path, - token: options.accessToken, - fields: {}, - attaches: { [options.fieldname]: filePath }, - statusCodeExpected: HttpStatusCode.OK_200 - }) + return buildRequest(req, { accept: 'application/json', expectedStatus: HttpStatusCode.BAD_REQUEST_400, ...options }) } function decodeQueryString (path: string) { @@ -233,6 +134,49 @@ export { makeRawRequest, makeActivityPubGetRequest, unwrapBody, - unwrapText, - updateImageRequest + unwrapText +} + +// --------------------------------------------------------------------------- + +function buildRequest (req: request.Test, options: CommonRequestParams) { + if (options.contentType) req.set('Accept', options.contentType) + if (options.token) req.set('Authorization', 'Bearer ' + options.token) + if (options.range) req.set('Range', options.range) + if (options.accept) req.set('Accept', options.accept) + if (options.host) req.set('Host', options.host) + if (options.redirects) req.redirects(options.redirects) + if (options.expectedStatus) req.expect(options.expectedStatus) + if (options.xForwardedFor) req.set('X-Forwarded-For', options.xForwardedFor) + if (options.type) req.type(options.type) + + Object.keys(options.headers || {}).forEach(name => { + req.set(name, options.headers[name]) + }) + + return req +} + +function buildFields (req: request.Test, fields: { [ fieldName: string ]: any }, namespace?: string) { + if (!fields) return + + let formKey: string + + for (const key of Object.keys(fields)) { + if (namespace) formKey = `${namespace}[${key}]` + else formKey = key + + if (fields[key] === undefined) continue + + if (Array.isArray(fields[key]) && fields[key].length === 0) { + req.field(key, null) + continue + } + + if (fields[key] !== null && typeof fields[key] === 'object') { + buildFields(req, fields[key], formKey) + } else { + req.field(formKey, fields[key]) + } + } } diff --git a/shared/extra-utils/search/search-command.ts b/shared/extra-utils/search/search-command.ts index 7539a21ec..09f5d3f1d 100644 --- a/shared/extra-utils/search/search-command.ts +++ b/shared/extra-utils/search/search-command.ts @@ -7,7 +7,7 @@ import { VideoPlaylistsSearchQuery, VideosSearchQuery } from '@shared/models' -import { HttpStatusCode } from '../../core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '@shared/models' import { AbstractCommand, OverrideCommandOptions } from '../shared' export class SearchCommand extends AbstractCommand { diff --git a/shared/extra-utils/server/config-command.ts b/shared/extra-utils/server/config-command.ts index f5d7fc5e3..6e875fdf6 100644 --- a/shared/extra-utils/server/config-command.ts +++ b/shared/extra-utils/server/config-command.ts @@ -1,6 +1,6 @@ import { merge } from 'lodash' -import { DeepPartial, HttpStatusCode } from '@shared/core-utils' -import { About, ServerConfig } from '@shared/models' +import { DeepPartial } from '@shared/core-utils' +import { About, ServerConfig, HttpStatusCode } from '@shared/models' import { CustomConfig } from '../../models/server/custom-config.model' import { AbstractCommand, OverrideCommandOptions } from '../shared' diff --git a/shared/extra-utils/server/contact-form-command.ts b/shared/extra-utils/server/contact-form-command.ts index 8d034552b..0e8fd6d84 100644 --- a/shared/extra-utils/server/contact-form-command.ts +++ b/shared/extra-utils/server/contact-form-command.ts @@ -1,4 +1,4 @@ -import { HttpStatusCode } from '../../core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '@shared/models' import { ContactForm } from '../../models/server' import { AbstractCommand, OverrideCommandOptions } from '../shared' diff --git a/shared/extra-utils/server/debug-command.ts b/shared/extra-utils/server/debug-command.ts index 8b24b3067..36704836d 100644 --- a/shared/extra-utils/server/debug-command.ts +++ b/shared/extra-utils/server/debug-command.ts @@ -1,5 +1,5 @@ import { Debug, SendDebugCommand } from '@shared/models' -import { HttpStatusCode } from '../../core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '@shared/models' import { AbstractCommand, OverrideCommandOptions } from '../shared' export class DebugCommand extends AbstractCommand { diff --git a/shared/extra-utils/server/follows-command.ts b/shared/extra-utils/server/follows-command.ts index 4e9ed9494..694f5ea24 100644 --- a/shared/extra-utils/server/follows-command.ts +++ b/shared/extra-utils/server/follows-command.ts @@ -1,6 +1,6 @@ import { pick } from 'lodash' import { ActivityPubActorType, ActorFollow, FollowState, ResultList } from '@shared/models' -import { HttpStatusCode } from '../../core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '@shared/models' import { AbstractCommand, OverrideCommandOptions } from '../shared' import { PeerTubeServer } from './server' diff --git a/shared/extra-utils/server/jobs-command.ts b/shared/extra-utils/server/jobs-command.ts index 392b868c1..09a299e5b 100644 --- a/shared/extra-utils/server/jobs-command.ts +++ b/shared/extra-utils/server/jobs-command.ts @@ -1,5 +1,5 @@ import { pick } from 'lodash' -import { HttpStatusCode } from '../../core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '@shared/models' import { Job, JobState, JobType, ResultList } from '../../models' import { AbstractCommand, OverrideCommandOptions } from '../shared' diff --git a/shared/extra-utils/server/plugins-command.ts b/shared/extra-utils/server/plugins-command.ts index 98049ce19..59bc79b3d 100644 --- a/shared/extra-utils/server/plugins-command.ts +++ b/shared/extra-utils/server/plugins-command.ts @@ -3,7 +3,7 @@ import { readJSON, writeJSON } from 'fs-extra' import { join } from 'path' import { root } from '@server/helpers/core-utils' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { PeerTubePlugin, PeerTubePluginIndex, diff --git a/shared/extra-utils/server/redundancy-command.ts b/shared/extra-utils/server/redundancy-command.ts index 728332fdd..137d7f01c 100644 --- a/shared/extra-utils/server/redundancy-command.ts +++ b/shared/extra-utils/server/redundancy-command.ts @@ -1,5 +1,5 @@ import { ResultList, VideoRedundanciesTarget, VideoRedundancy } from '@shared/models' -import { HttpStatusCode } from '../../core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '@shared/models' import { AbstractCommand, OverrideCommandOptions } from '../shared' export class RedundancyCommand extends AbstractCommand { diff --git a/shared/extra-utils/server/server.ts b/shared/extra-utils/server/server.ts index cc6df2efe..b33bb9d1e 100644 --- a/shared/extra-utils/server/server.ts +++ b/shared/extra-utils/server/server.ts @@ -254,7 +254,7 @@ export class PeerTubeServer { process.on('exit', () => { try { - process.kill(self.server.app.pid) + process.kill(self.app.pid) } catch { /* empty */ } }) diff --git a/shared/extra-utils/server/servers-command.ts b/shared/extra-utils/server/servers-command.ts index 1a7b2aade..107e2b4ad 100644 --- a/shared/extra-utils/server/servers-command.ts +++ b/shared/extra-utils/server/servers-command.ts @@ -2,7 +2,7 @@ import { exec } from 'child_process' import { copy, ensureDir, readFile, remove } from 'fs-extra' import { join } from 'path' import { root } from '@server/helpers/core-utils' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { getFileSize } from '@uploadx/core' import { isGithubCI, wait } from '../miscs' import { AbstractCommand, OverrideCommandOptions } from '../shared' diff --git a/shared/extra-utils/server/stats-command.ts b/shared/extra-utils/server/stats-command.ts index f0f02ca08..6db473588 100644 --- a/shared/extra-utils/server/stats-command.ts +++ b/shared/extra-utils/server/stats-command.ts @@ -1,5 +1,5 @@ import { ServerStats } from '@shared/models' -import { HttpStatusCode } from '../../core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '@shared/models' import { AbstractCommand, OverrideCommandOptions } from '../shared' export class StatsCommand extends AbstractCommand { diff --git a/shared/extra-utils/shared/abstract-command.ts b/shared/extra-utils/shared/abstract-command.ts index 967f8f2ac..021045e49 100644 --- a/shared/extra-utils/shared/abstract-command.ts +++ b/shared/extra-utils/shared/abstract-command.ts @@ -24,15 +24,20 @@ interface InternalCommonCommandOptions extends OverrideCommandOptions { // If we automatically send the server token if the token is not provided implicitToken: boolean defaultExpectedStatus: number -} -interface InternalGetCommandOptions extends InternalCommonCommandOptions { - query?: { [ id: string ]: any } + // Common optional request parameters contentType?: string accept?: string redirects?: number range?: string host?: string + headers?: { [ name: string ]: string } + requestType?: string + xForwardedFor?: string +} + +interface InternalGetCommandOptions extends InternalCommonCommandOptions { + query?: { [ id: string ]: any } } abstract class AbstractCommand { @@ -59,7 +64,7 @@ abstract class AbstractCommand { ...options, token: this.buildCommonRequestToken(options), - defaultExpectedStatus: this.buildStatusCodeExpected(options), + defaultExpectedStatus: this.buildExpectedStatus(options), url: `${protocol}//${host}`, path: pathname, @@ -68,17 +73,12 @@ abstract class AbstractCommand { } protected getRequest (options: InternalGetCommandOptions) { - const { redirects, query, contentType, accept, range, host } = options + const { query } = options return makeGetRequest({ ...this.buildCommonRequestOptions(options), - redirects, - query, - contentType, - range, - host, - accept + query }) } @@ -100,51 +100,41 @@ abstract class AbstractCommand { protected postBodyRequest (options: InternalCommonCommandOptions & { fields?: { [ fieldName: string ]: any } - headers?: { [ name: string ]: string } - type?: string - xForwardedFor?: string }) { - const { type, fields, xForwardedFor, headers } = options + const { fields } = options return makePostBodyRequest({ ...this.buildCommonRequestOptions(options), - fields, - xForwardedFor, - type, - headers + fields }) } protected postUploadRequest (options: InternalCommonCommandOptions & { fields?: { [ fieldName: string ]: any } attaches?: { [ fieldName: string ]: any } - headers?: { [ name: string ]: string } }) { - const { fields, attaches, headers } = options + const { fields, attaches } = options return makeUploadRequest({ ...this.buildCommonRequestOptions(options), method: 'POST', fields, - attaches, - headers + attaches }) } protected putUploadRequest (options: InternalCommonCommandOptions & { fields?: { [ fieldName: string ]: any } attaches?: { [ fieldName: string ]: any } - headers?: { [ name: string ]: string } }) { - const { fields, attaches, headers } = options + const { fields, attaches } = options return makeUploadRequest({ ...this.buildCommonRequestOptions(options), method: 'PUT', - headers, fields, attaches }) @@ -154,12 +144,9 @@ abstract class AbstractCommand { fixture: string fieldname: string }) { - let filePath = '' - if (isAbsolute(options.fixture)) { - filePath = options.fixture - } else { - filePath = join(root(), 'server', 'tests', 'fixtures', options.fixture) - } + const filePath = isAbsolute(options.fixture) + ? options.fixture + : join(root(), 'server', 'tests', 'fixtures', options.fixture) return this.postUploadRequest({ ...options, @@ -170,14 +157,23 @@ abstract class AbstractCommand { } protected buildCommonRequestOptions (options: InternalCommonCommandOptions) { - const { url, path } = options + const { url, path, redirects, contentType, accept, range, host, headers, requestType, xForwardedFor } = options return { url: url ?? this.server.url, path, token: this.buildCommonRequestToken(options), - statusCodeExpected: this.buildStatusCodeExpected(options) + expectedStatus: this.buildExpectedStatus(options), + + redirects, + contentType, + range, + host, + accept, + headers, + type: requestType, + xForwardedFor } } @@ -191,7 +187,7 @@ abstract class AbstractCommand { return token !== undefined ? token : fallbackToken } - protected buildStatusCodeExpected (options: Pick) { + protected buildExpectedStatus (options: Pick) { const { expectedStatus, defaultExpectedStatus } = options return expectedStatus !== undefined ? expectedStatus : defaultExpectedStatus diff --git a/shared/extra-utils/users/accounts-command.ts b/shared/extra-utils/users/accounts-command.ts index 4cd1d2158..08977e58b 100644 --- a/shared/extra-utils/users/accounts-command.ts +++ b/shared/extra-utils/users/accounts-command.ts @@ -1,5 +1,5 @@ import { ResultList } from '@shared/models' -import { HttpStatusCode } from '../../core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '@shared/models' import { Account } from '../../models/actors' import { AccountVideoRate, VideoRateType } from '../../models/videos' import { AbstractCommand, OverrideCommandOptions } from '../shared' diff --git a/shared/extra-utils/users/blocklist-command.ts b/shared/extra-utils/users/blocklist-command.ts index 089b5a579..a9431acf3 100644 --- a/shared/extra-utils/users/blocklist-command.ts +++ b/shared/extra-utils/users/blocklist-command.ts @@ -1,6 +1,6 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { AccountBlock, ResultList, ServerBlock } from '@shared/models' import { AbstractCommand, OverrideCommandOptions } from '../shared' diff --git a/shared/extra-utils/users/index.ts b/shared/extra-utils/users/index.ts index e6107afa5..fbb454e8f 100644 --- a/shared/extra-utils/users/index.ts +++ b/shared/extra-utils/users/index.ts @@ -7,4 +7,3 @@ export * from './notifications' export * from './notifications-command' export * from './subscriptions-command' export * from './users-command' -export * from './users' diff --git a/shared/extra-utils/users/login-command.ts b/shared/extra-utils/users/login-command.ts index 10c3db851..b39577260 100644 --- a/shared/extra-utils/users/login-command.ts +++ b/shared/extra-utils/users/login-command.ts @@ -1,4 +1,4 @@ -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { PeerTubeProblemDocument } from '@shared/models' import { unwrapBody } from '../requests' import { AbstractCommand, OverrideCommandOptions } from '../shared' @@ -26,7 +26,7 @@ export class LoginCommand extends AbstractCommand { ...options, path, - type: 'form', + requestType: 'form', fields: body, implicitToken: false, defaultExpectedStatus: HttpStatusCode.OK_200 @@ -72,7 +72,7 @@ export class LoginCommand extends AbstractCommand { ...options, path, - type: 'form', + requestType: 'form', fields: body, implicitToken: false, defaultExpectedStatus: HttpStatusCode.OK_200 @@ -88,7 +88,7 @@ export class LoginCommand extends AbstractCommand { ...options, path, - type: 'form', + requestType: 'form', implicitToken: false, defaultExpectedStatus: HttpStatusCode.OK_200 })) @@ -111,7 +111,7 @@ export class LoginCommand extends AbstractCommand { ...options, path, - type: 'form', + requestType: 'form', fields: body, implicitToken: false, defaultExpectedStatus: HttpStatusCode.OK_200 diff --git a/shared/extra-utils/users/notifications-command.ts b/shared/extra-utils/users/notifications-command.ts index dfe574ca1..a51fcc3af 100644 --- a/shared/extra-utils/users/notifications-command.ts +++ b/shared/extra-utils/users/notifications-command.ts @@ -1,5 +1,5 @@ import { ResultList } from '@shared/models' -import { HttpStatusCode } from '../../core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '@shared/models' import { UserNotification, UserNotificationSetting } from '../../models/users' import { AbstractCommand, OverrideCommandOptions } from '../shared' diff --git a/shared/extra-utils/users/subscriptions-command.ts b/shared/extra-utils/users/subscriptions-command.ts index e998eb426..a69d2a194 100644 --- a/shared/extra-utils/users/subscriptions-command.ts +++ b/shared/extra-utils/users/subscriptions-command.ts @@ -1,5 +1,5 @@ import { ResultList, Video, VideoChannel } from '@shared/models' -import { HttpStatusCode } from '../../core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '@shared/models' import { AbstractCommand, OverrideCommandOptions } from '../shared' export class SubscriptionsCommand extends AbstractCommand { diff --git a/shared/extra-utils/users/users-command.ts b/shared/extra-utils/users/users-command.ts index 59dc6d018..f3a251e65 100644 --- a/shared/extra-utils/users/users-command.ts +++ b/shared/extra-utils/users/users-command.ts @@ -1,5 +1,5 @@ import { omit, pick } from 'lodash' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { MyUser, ResultList, diff --git a/shared/extra-utils/users/users.ts b/shared/extra-utils/users/users.ts deleted file mode 100644 index 6cf61d60e..000000000 --- a/shared/extra-utils/users/users.ts +++ /dev/null @@ -1,20 +0,0 @@ -import * as request from 'supertest' -import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' - -// FIXME: delete once videos does not use it anymore -function xxxgetMyUserInformation (url: string, accessToken: string, specialStatus = HttpStatusCode.OK_200) { - const path = '/api/v1/users/me' - - return request(url) - .get(path) - .set('Accept', 'application/json') - .set('Authorization', 'Bearer ' + accessToken) - .expect(specialStatus) - .expect('Content-Type', /json/) -} - -// --------------------------------------------------------------------------- - -export { - xxxgetMyUserInformation -} diff --git a/shared/extra-utils/videos/blacklist-command.ts b/shared/extra-utils/videos/blacklist-command.ts index fdae6b469..9404d4c08 100644 --- a/shared/extra-utils/videos/blacklist-command.ts +++ b/shared/extra-utils/videos/blacklist-command.ts @@ -1,6 +1,6 @@ import { ResultList } from '@shared/models' -import { HttpStatusCode } from '../../core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '@shared/models' import { VideoBlacklist, VideoBlacklistType } from '../../models/videos' import { AbstractCommand, OverrideCommandOptions } from '../shared' diff --git a/shared/extra-utils/videos/captions-command.ts b/shared/extra-utils/videos/captions-command.ts index ac3bde7a9..04dd32f84 100644 --- a/shared/extra-utils/videos/captions-command.ts +++ b/shared/extra-utils/videos/captions-command.ts @@ -1,4 +1,4 @@ -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { ResultList, VideoCaption } from '@shared/models' import { buildAbsoluteFixturePath } from '../miscs' import { AbstractCommand, OverrideCommandOptions } from '../shared' diff --git a/shared/extra-utils/videos/captions.ts b/shared/extra-utils/videos/captions.ts index 2246bd133..ff8a43366 100644 --- a/shared/extra-utils/videos/captions.ts +++ b/shared/extra-utils/videos/captions.ts @@ -1,6 +1,6 @@ import { expect } from 'chai' import * as request from 'supertest' -import { HttpStatusCode } from '../../core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '@shared/models' async function testCaptionFile (url: string, captionPath: string, containsString: string) { const res = await request(url) diff --git a/shared/extra-utils/videos/change-ownership-command.ts b/shared/extra-utils/videos/change-ownership-command.ts index 03f77a95f..ef6f07536 100644 --- a/shared/extra-utils/videos/change-ownership-command.ts +++ b/shared/extra-utils/videos/change-ownership-command.ts @@ -1,6 +1,6 @@ import { ResultList, VideoChangeOwnership } from '@shared/models' -import { HttpStatusCode } from '../../core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '@shared/models' import { AbstractCommand, OverrideCommandOptions } from '../shared' export class ChangeOwnershipCommand extends AbstractCommand { diff --git a/shared/extra-utils/videos/channels-command.ts b/shared/extra-utils/videos/channels-command.ts index a98c5cc93..e5393ff56 100644 --- a/shared/extra-utils/videos/channels-command.ts +++ b/shared/extra-utils/videos/channels-command.ts @@ -1,6 +1,6 @@ import { pick } from 'lodash' import { ResultList, VideoChannel, VideoChannelCreateResult } from '@shared/models' -import { HttpStatusCode } from '../../core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '@shared/models' import { VideoChannelCreate } from '../../models/videos/channel/video-channel-create.model' import { VideoChannelUpdate } from '../../models/videos/channel/video-channel-update.model' import { unwrapBody } from '../requests' diff --git a/shared/extra-utils/videos/comments-command.ts b/shared/extra-utils/videos/comments-command.ts index b31f3e2dd..7368f3ea2 100644 --- a/shared/extra-utils/videos/comments-command.ts +++ b/shared/extra-utils/videos/comments-command.ts @@ -1,6 +1,6 @@ import { pick } from 'lodash' +import { HttpStatusCode } from '@shared/models' import { ResultList, VideoComment, VideoCommentThreads, VideoCommentThreadTree } from '@shared/models' -import { HttpStatusCode } from '../../core-utils/miscs/http-error-codes' import { unwrapBody } from '../requests' import { AbstractCommand, OverrideCommandOptions } from '../shared' diff --git a/shared/extra-utils/videos/history-command.ts b/shared/extra-utils/videos/history-command.ts index 8a144a312..41afc6bc6 100644 --- a/shared/extra-utils/videos/history-command.ts +++ b/shared/extra-utils/videos/history-command.ts @@ -1,5 +1,5 @@ +import { HttpStatusCode } from '@shared/models' import { ResultList, Video } from '@shared/models' -import { HttpStatusCode } from '../../core-utils/miscs/http-error-codes' import { AbstractCommand, OverrideCommandOptions } from '../shared' export class HistoryCommand extends AbstractCommand { diff --git a/shared/extra-utils/videos/imports-command.ts b/shared/extra-utils/videos/imports-command.ts index de8b65829..d30f9745b 100644 --- a/shared/extra-utils/videos/imports-command.ts +++ b/shared/extra-utils/videos/imports-command.ts @@ -1,6 +1,6 @@ +import { HttpStatusCode } from '@shared/models' import { ResultList } from '@shared/models' -import { HttpStatusCode } from '../../core-utils/miscs/http-error-codes' import { VideoImport, VideoImportCreate } from '../../models/videos' import { unwrapBody } from '../requests' import { AbstractCommand, OverrideCommandOptions } from '../shared' diff --git a/shared/extra-utils/videos/live-command.ts b/shared/extra-utils/videos/live-command.ts index fd66c9924..9dfe3087e 100644 --- a/shared/extra-utils/videos/live-command.ts +++ b/shared/extra-utils/videos/live-command.ts @@ -3,8 +3,8 @@ import { readdir } from 'fs-extra' import { omit } from 'lodash' import { join } from 'path' +import { HttpStatusCode } from '@shared/models' import { LiveVideo, LiveVideoCreate, LiveVideoUpdate, VideoCreateResult, VideoDetails, VideoState } from '@shared/models' -import { HttpStatusCode } from '../../core-utils/miscs/http-error-codes' import { wait } from '../miscs' import { unwrapBody } from '../requests' import { AbstractCommand, OverrideCommandOptions } from '../shared' diff --git a/shared/extra-utils/videos/playlists-command.ts b/shared/extra-utils/videos/playlists-command.ts index cbfc7e10f..40162c30d 100644 --- a/shared/extra-utils/videos/playlists-command.ts +++ b/shared/extra-utils/videos/playlists-command.ts @@ -1,5 +1,5 @@ import { omit, pick } from 'lodash' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { BooleanBothQuery, ResultList, diff --git a/shared/extra-utils/videos/services-command.ts b/shared/extra-utils/videos/services-command.ts index 313b7878c..06760df42 100644 --- a/shared/extra-utils/videos/services-command.ts +++ b/shared/extra-utils/videos/services-command.ts @@ -1,4 +1,4 @@ -import { HttpStatusCode } from '../../core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '@shared/models' import { AbstractCommand, OverrideCommandOptions } from '../shared' export class ServicesCommand extends AbstractCommand { diff --git a/shared/extra-utils/videos/streaming-playlists-command.ts b/shared/extra-utils/videos/streaming-playlists-command.ts index fab3eb556..9662685da 100644 --- a/shared/extra-utils/videos/streaming-playlists-command.ts +++ b/shared/extra-utils/videos/streaming-playlists-command.ts @@ -1,5 +1,4 @@ - -import { HttpStatusCode } from '../../core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '@shared/models' import { unwrapBody, unwrapText } from '../requests' import { AbstractCommand, OverrideCommandOptions } from '../shared' diff --git a/shared/extra-utils/videos/streaming-playlists.ts b/shared/extra-utils/videos/streaming-playlists.ts index 002ae08b2..007d3d98d 100644 --- a/shared/extra-utils/videos/streaming-playlists.ts +++ b/shared/extra-utils/videos/streaming-playlists.ts @@ -1,6 +1,6 @@ import { expect } from 'chai' import { sha256 } from '@server/helpers/core-utils' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { VideoStreamingPlaylist } from '@shared/models' import { PeerTubeServer } from '../server' diff --git a/shared/extra-utils/videos/videos-command.ts b/shared/extra-utils/videos/videos-command.ts index feef5a771..f46d386f4 100644 --- a/shared/extra-utils/videos/videos-command.ts +++ b/shared/extra-utils/videos/videos-command.ts @@ -7,7 +7,7 @@ import { omit, pick } from 'lodash' import validator from 'validator' import { buildUUID } from '@server/helpers/uuid' import { loadLanguages } from '@server/initializers/constants' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { ResultList, UserVideoRateType, @@ -234,10 +234,10 @@ export class VideosCommand extends AbstractCommand { } listByAccount (options: OverrideCommandOptions & VideosWithSearchCommonQuery & { - accountName: string + handle: string }) { - const { accountName, search } = options - const path = '/api/v1/accounts/' + accountName + '/videos' + const { handle, search } = options + const path = '/api/v1/accounts/' + handle + '/videos' return this.getRequestBody>({ ...options, @@ -250,10 +250,10 @@ export class VideosCommand extends AbstractCommand { } listByChannel (options: OverrideCommandOptions & VideosWithSearchCommonQuery & { - videoChannelName: string + handle: string }) { - const { videoChannelName } = options - const path = '/api/v1/video-channels/' + videoChannelName + '/videos' + const { handle } = options + const path = '/api/v1/video-channels/' + handle + '/videos' return this.getRequestBody>({ ...options, @@ -309,13 +309,13 @@ export class VideosCommand extends AbstractCommand { }) { const path = '/api/v1/videos/' + options.id - return this.deleteRequest({ + return unwrapBody(this.deleteRequest({ ...options, path, implicitToken: true, defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 - }) + })) } async removeAll () { @@ -396,7 +396,7 @@ export class VideosCommand extends AbstractCommand { async buildResumeUpload (options: OverrideCommandOptions & { attributes: VideoEdit - }) { + }): Promise { const { attributes, expectedStatus } = options let size = 0 @@ -414,7 +414,8 @@ export class VideosCommand extends AbstractCommand { } } - const initializeSessionRes = await this.prepareResumableUpload({ ...options, attributes, size, mimetype }) + // Do not check status automatically, we'll check it manually + const initializeSessionRes = await this.prepareResumableUpload({ ...options, expectedStatus: null, attributes, size, mimetype }) const initStatus = initializeSessionRes.status if (videoFilePath && initStatus === HttpStatusCode.CREATED_201) { @@ -425,7 +426,7 @@ export class VideosCommand extends AbstractCommand { const result = await this.sendResumableChunks({ ...options, pathUploadId, videoFilePath, size }) - return result.body.video + return result.body?.video || result.body as any } const expectedInitStatus = expectedStatus === HttpStatusCode.OK_200 @@ -434,7 +435,7 @@ export class VideosCommand extends AbstractCommand { expect(initStatus).to.equal(expectedInitStatus) - return initializeSessionRes.body.video as VideoCreateResult + return initializeSessionRes.body.video || initializeSessionRes.body } async prepareResumableUpload (options: OverrideCommandOptions & { @@ -455,7 +456,10 @@ export class VideosCommand extends AbstractCommand { 'X-Upload-Content-Length': size.toString() }, fields: { filename: attributes.fixture, ...this.buildUploadFields(options.attributes) }, + // Fixture will be sent later + attaches: this.buildUploadAttaches(omit(options.attributes, 'fixture')), implicitToken: true, + defaultExpectedStatus: null }) } @@ -539,10 +543,10 @@ export class VideosCommand extends AbstractCommand { const attributes = { name, additionalParams } - if (wait) await waitJobs([ this.server ]) - const result = await this.upload({ ...options, attributes }) + if (wait) await waitJobs([ this.server ]) + return { ...result, name } } @@ -566,7 +570,7 @@ export class VideosCommand extends AbstractCommand { } private buildUploadFields (attributes: VideoEdit) { - return omit(attributes, [ 'thumbnailfile', 'previewfile' ]) + return omit(attributes, [ 'fixture', 'thumbnailfile', 'previewfile' ]) } private buildUploadAttaches (attributes: VideoEdit) { diff --git a/shared/extra-utils/videos/videos.ts b/shared/extra-utils/videos/videos.ts index b41533808..a96073c56 100644 --- a/shared/extra-utils/videos/videos.ts +++ b/shared/extra-utils/videos/videos.ts @@ -4,7 +4,7 @@ import { expect } from 'chai' import { pathExists, readdir } from 'fs-extra' import { join } from 'path' import { getLowercaseExtension } from '@server/helpers/core-utils' -import { HttpStatusCode } from '@shared/core-utils' +import { HttpStatusCode } from '@shared/models' import { VIDEO_CATEGORIES, VIDEO_LANGUAGES, VIDEO_LICENCES, VIDEO_PRIVACIES } from '../../../server/initializers/constants' import { dateIsValid, testImage, webtorrentAdd } from '../miscs' import { makeRawRequest } from '../requests/requests' diff --git a/shared/models/http/http-error-codes.ts b/shared/models/http/http-error-codes.ts new file mode 100644 index 000000000..b2fbdfc5a --- /dev/null +++ b/shared/models/http/http-error-codes.ts @@ -0,0 +1,364 @@ +/** + * Hypertext Transfer Protocol (HTTP) response status codes. + * @see {@link https://en.wikipedia.org/wiki/List_of_HTTP_status_codes} + * + * WebDAV and other codes useless with regards to PeerTube are not listed. + */ +export enum HttpStatusCode { + + /** + * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.2.1 + * + * The server has received the request headers and the client should proceed to send the request body + * (in the case of a request for which a body needs to be sent; for example, a POST request). + * Sending a large request body to a server after a request has been rejected for inappropriate headers would be inefficient. + * To have a server check the request's headers, a client must send Expect: 100-continue as a header in its initial request + * and receive a 100 Continue status code in response before sending the body. The response 417 Expectation Failed indicates + * the request should not be continued. + */ + CONTINUE_100 = 100, + + /** + * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.2.2 + * + * This code is sent in response to an Upgrade request header by the client, and indicates the protocol the server is switching too. + */ + SWITCHING_PROTOCOLS_101 = 101, + + /** + * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.1 + * + * Standard response for successful HTTP requests. The actual response will depend on the request method used: + * GET: The resource has been fetched and is transmitted in the message body. + * HEAD: The entity headers are in the message body. + * POST: The resource describing the result of the action is transmitted in the message body. + * TRACE: The message body contains the request message as received by the server + */ + OK_200 = 200, + + /** + * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.2 + * + * The request has been fulfilled, resulting in the creation of a new resource, typically after a PUT. + */ + CREATED_201 = 201, + + /** + * The request has been accepted for processing, but the processing has not been completed. + * The request might or might not be eventually acted upon, and may be disallowed when processing occurs. + */ + ACCEPTED_202 = 202, + + /** + * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.5 + * + * There is no content to send for this request, but the headers may be useful. + * The user-agent may update its cached headers for this resource with the new ones. + */ + NO_CONTENT_204 = 204, + + /** + * The server successfully processed the request, but is not returning any content. + * Unlike a 204 response, this response requires that the requester reset the document view. + */ + RESET_CONTENT_205 = 205, + + /** + * The server is delivering only part of the resource (byte serving) due to a range header sent by the client. + * The range header is used by HTTP clients to enable resuming of interrupted downloads, + * or split a download into multiple simultaneous streams. + */ + PARTIAL_CONTENT_206 = 206, + + /** + * Indicates multiple options for the resource from which the client may choose (via agent-driven content negotiation). + * For example, this code could be used to present multiple video format options, + * to list files with different filename extensions, or to suggest word-sense disambiguation. + */ + MULTIPLE_CHOICES_300 = 300, + + /** + * This and all future requests should be directed to the given URI. + */ + MOVED_PERMANENTLY_301 = 301, + + /** + * This is an example of industry practice contradicting the standard. + * The HTTP/1.0 specification (RFC 1945) required the client to perform a temporary redirect + * (the original describing phrase was "Moved Temporarily"), but popular browsers implemented 302 + * with the functionality of a 303 See Other. Therefore, HTTP/1.1 added status codes 303 and 307 + * to distinguish between the two behaviours. However, some Web applications and frameworks + * use the 302 status code as if it were the 303. + */ + FOUND_302 = 302, + + /** + * SINCE HTTP/1.1 + * The response to the request can be found under another URI using a GET method. + * When received in response to a POST (or PUT/DELETE), the client should presume that + * the server has received the data and should issue a redirect with a separate GET message. + */ + SEE_OTHER_303 = 303, + + /** + * Official Documentation @ https://tools.ietf.org/html/rfc7232#section-4.1 + * + * Indicates that the resource has not been modified since the version specified by the request headers + * `If-Modified-Since` or `If-None-Match`. + * In such case, there is no need to retransmit the resource since the client still has a previously-downloaded copy. + */ + NOT_MODIFIED_304 = 304, + + /** + * SINCE HTTP/1.1 + * In this case, the request should be repeated with another URI; however, future requests should still use the original URI. + * In contrast to how 302 was historically implemented, the request method is not allowed to be changed when reissuing the + * original request. + * For example, a POST request should be repeated using another POST request. + */ + TEMPORARY_REDIRECT_307 = 307, + + /** + * The request and all future requests should be repeated using another URI. + * 307 and 308 parallel the behaviors of 302 and 301, but do not allow the HTTP method to change. + * So, for example, submitting a form to a permanently redirected resource may continue smoothly. + */ + PERMANENT_REDIRECT_308 = 308, + + /** + * The server cannot or will not process the request due to an apparent client error + * (e.g., malformed request syntax, too large size, invalid request message framing, or deceptive request routing). + */ + BAD_REQUEST_400 = 400, + + /** + * Official Documentation @ https://tools.ietf.org/html/rfc7235#section-3.1 + * + * Similar to 403 Forbidden, but specifically for use when authentication is required and has failed or has not yet + * been provided. The response must include a `WWW-Authenticate` header field containing a challenge applicable to the + * requested resource. See Basic access authentication and Digest access authentication. 401 semantically means + * "unauthenticated",i.e. the user does not have the necessary credentials. + */ + UNAUTHORIZED_401 = 401, + + /** + * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.2 + * + * Reserved for future use. The original intention was that this code might be used as part of some form of digital + * cash or micro payment scheme, but that has not happened, and this code is not usually used. + * Google Developers API uses this status if a particular developer has exceeded the daily limit on requests. + */ + PAYMENT_REQUIRED_402 = 402, + + /** + * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.3 + * + * The client does not have access rights to the content, i.e. they are unauthorized, so server is rejecting to + * give proper response. Unlike 401, the client's identity is known to the server. + */ + FORBIDDEN_403 = 403, + + /** + * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.2 + * + * The requested resource could not be found but may be available in the future. + * Subsequent requests by the client are permissible. + */ + NOT_FOUND_404 = 404, + + /** + * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.5 + * + * A request method is not supported for the requested resource; + * for example, a GET request on a form that requires data to be presented via POST, or a PUT request on a read-only resource. + */ + METHOD_NOT_ALLOWED_405 = 405, + + /** + * The requested resource is capable of generating only content not acceptable according to the Accept headers sent in the request. + */ + NOT_ACCEPTABLE_406 = 406, + + /** + * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.7 + * + * This response is sent on an idle connection by some servers, even without any previous request by the client. + * It means that the server would like to shut down this unused connection. This response is used much more since + * some browsers, like Chrome, Firefox 27+, or IE9, use HTTP pre-connection mechanisms to speed up surfing. Also + * note that some servers merely shut down the connection without sending this message. + * + * @ + */ + REQUEST_TIMEOUT_408 = 408, + + /** + * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.8 + * + * Indicates that the request could not be processed because of conflict in the request, + * such as an edit conflict between multiple simultaneous updates. + * + * @see HttpStatusCode.UNPROCESSABLE_ENTITY_422 to denote a disabled feature + */ + CONFLICT_409 = 409, + + /** + * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.9 + * + * Indicates that the resource requested is no longer available and will not be available again. + * This should be used when a resource has been intentionally removed and the resource should be purged. + * Upon receiving a 410 status code, the client should not request the resource in the future. + * Clients such as search engines should remove the resource from their indices. + * Most use cases do not require clients and search engines to purge the resource, and a "404 Not Found" may be used instead. + */ + GONE_410 = 410, + + /** + * The request did not specify the length of its content, which is required by the requested resource. + */ + LENGTH_REQUIRED_411 = 411, + + /** + * The server does not meet one of the preconditions that the requester put on the request. + */ + PRECONDITION_FAILED_412 = 412, + + /** + * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.11 + * + * The request is larger than the server is willing or able to process ; the server might close the connection + * or return an Retry-After header field. + * Previously called "Request Entity Too Large". + */ + PAYLOAD_TOO_LARGE_413 = 413, + + /** + * The URI provided was too long for the server to process. Often the result of too much data being encoded as a + * query-string of a GET request, in which case it should be converted to a POST request. + * Called "Request-URI Too Long" previously. + */ + URI_TOO_LONG_414 = 414, + + /** + * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.13 + * + * The request entity has a media type which the server or resource does not support. + * For example, the client uploads an image as image/svg+xml, but the server requires that images use a different format. + */ + UNSUPPORTED_MEDIA_TYPE_415 = 415, + + /** + * The client has asked for a portion of the file (byte serving), but the server cannot supply that portion. + * For example, if the client asked for a part of the file that lies beyond the end of the file. + * Called "Requested Range Not Satisfiable" previously. + */ + RANGE_NOT_SATISFIABLE_416 = 416, + + /** + * The server cannot meet the requirements of the `Expect` request-header field. + */ + EXPECTATION_FAILED_417 = 417, + + /** + * Official Documentation @ https://tools.ietf.org/html/rfc2324 + * + * This code was defined in 1998 as one of the traditional IETF April Fools' jokes, in RFC 2324, Hyper Text Coffee Pot Control Protocol, + * and is not expected to be implemented by actual HTTP servers. The RFC specifies this code should be returned by + * teapots requested to brew coffee. This HTTP status is used as an Easter egg in some websites, including PeerTube instances ;-). + */ + I_AM_A_TEAPOT_418 = 418, + + /** + * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.3 + * + * The request was well-formed but was unable to be followed due to semantic errors. + * The server understands the content type of the request entity (hence a 415 (Unsupported Media Type) status code is inappropriate), + * and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process + * the contained instructions. For example, this error condition may occur if an JSON request body contains well-formed (i.e., + * syntactically correct), but semantically erroneous, JSON instructions. + * + * Can also be used to denote disabled features (akin to disabled syntax). + * + * @see HttpStatusCode.UNSUPPORTED_MEDIA_TYPE_415 if the `Content-Type` was not supported. + * @see HttpStatusCode.BAD_REQUEST_400 if the request was not parsable (broken JSON, XML) + */ + UNPROCESSABLE_ENTITY_422 = 422, + + /** + * Official Documentation @ https://tools.ietf.org/html/rfc4918#section-11.3 + * + * The resource that is being accessed is locked. WebDAV-specific but used by some HTTP services. + * + * @deprecated use `If-Match` / `If-None-Match` instead + * @see {@link https://evertpot.com/http/423-locked} + */ + LOCKED_423 = 423, + + /** + * Official Documentation @ https://tools.ietf.org/html/rfc6585#section-4 + * + * The user has sent too many requests in a given amount of time. Intended for use with rate-limiting schemes. + */ + TOO_MANY_REQUESTS_429 = 429, + + /** + * Official Documentation @ https://tools.ietf.org/html/rfc6585#section-5 + * + * The server is unwilling to process the request because either an individual header field, + * or all the header fields collectively, are too large. + */ + REQUEST_HEADER_FIELDS_TOO_LARGE_431 = 431, + + /** + * Official Documentation @ https://tools.ietf.org/html/rfc7725 + * + * A server operator has received a legal demand to deny access to a resource or to a set of resources + * that includes the requested resource. The code 451 was chosen as a reference to the novel Fahrenheit 451. + */ + UNAVAILABLE_FOR_LEGAL_REASONS_451 = 451, + + /** + * A generic error message, given when an unexpected condition was encountered and no more specific message is suitable. + */ + INTERNAL_SERVER_ERROR_500 = 500, + + /** + * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.2 + * + * The server either does not recognize the request method, or it lacks the ability to fulfill the request. + * Usually this implies future availability (e.g., a new feature of a web-service API). + */ + NOT_IMPLEMENTED_501 = 501, + + /** + * The server was acting as a gateway or proxy and received an invalid response from the upstream server. + */ + BAD_GATEWAY_502 = 502, + + /** + * The server is currently unavailable (because it is overloaded or down for maintenance). + * Generally, this is a temporary state. + */ + SERVICE_UNAVAILABLE_503 = 503, + + /** + * The server was acting as a gateway or proxy and did not receive a timely response from the upstream server. + */ + GATEWAY_TIMEOUT_504 = 504, + + /** + * The server does not support the HTTP protocol version used in the request + */ + HTTP_VERSION_NOT_SUPPORTED_505 = 505, + + /** + * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.6 + * + * The 507 (Insufficient Storage) status code means the method could not be performed on the resource because the + * server is unable to store the representation needed to successfully complete the request. This condition is + * considered to be temporary. If the request which received this status code was the result of a user action, + * the request MUST NOT be repeated until it is requested by a separate user action. + * + * @see HttpStatusCode.PAYLOAD_TOO_LARGE_413 for quota errors + */ + INSUFFICIENT_STORAGE_507 = 507, +} diff --git a/shared/models/http/http-methods.ts b/shared/models/http/http-methods.ts new file mode 100644 index 000000000..1cfa458b9 --- /dev/null +++ b/shared/models/http/http-methods.ts @@ -0,0 +1,21 @@ +/** HTTP request method to indicate the desired action to be performed for a given resource. */ +export enum HttpMethod { + /** The CONNECT method establishes a tunnel to the server identified by the target resource. */ + CONNECT = 'CONNECT', + /** The DELETE method deletes the specified resource. */ + DELETE = 'DELETE', + /** The GET method requests a representation of the specified resource. Requests using GET should only retrieve data. */ + GET = 'GET', + /** The HEAD method asks for a response identical to that of a GET request, but without the response body. */ + HEAD = 'HEAD', + /** The OPTIONS method is used to describe the communication options for the target resource. */ + OPTIONS = 'OPTIONS', + /** The PATCH method is used to apply partial modifications to a resource. */ + PATCH = 'PATCH', + /** The POST method is used to submit an entity to the specified resource */ + POST = 'POST', + /** The PUT method replaces all current representations of the target resource with the request payload. */ + PUT = 'PUT', + /** The TRACE method performs a message loop-back test along the path to the target resource. */ + TRACE = 'TRACE' +} diff --git a/shared/models/http/index.ts b/shared/models/http/index.ts new file mode 100644 index 000000000..ec991afe0 --- /dev/null +++ b/shared/models/http/index.ts @@ -0,0 +1,2 @@ +export * from './http-error-codes' +export * from './http-methods' diff --git a/shared/models/index.ts b/shared/models/index.ts index 5c2bc480e..78723d830 100644 --- a/shared/models/index.ts +++ b/shared/models/index.ts @@ -4,6 +4,7 @@ export * from './bulk' export * from './common' export * from './custom-markup' export * from './feeds' +export * from './http' export * from './joinpeertube' export * from './moderation' export * from './overviews' diff --git a/shared/models/server/peertube-problem-document.model.ts b/shared/models/server/peertube-problem-document.model.ts index e391d5aad..8dd96f7a3 100644 --- a/shared/models/server/peertube-problem-document.model.ts +++ b/shared/models/server/peertube-problem-document.model.ts @@ -1,4 +1,4 @@ -import { HttpStatusCode } from '../../core-utils' +import { HttpStatusCode } from '../../models' import { OAuth2ErrorCode, ServerErrorCode } from './server-error-code.enum' export interface PeerTubeProblemDocumentData { -- cgit v1.2.3 From 4c7e60bc17ee5830399bac4aa273356903421b4c Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Fri, 16 Jul 2021 14:27:30 +0200 Subject: Reorganize imports --- server/controllers/api/bulk.ts | 6 +++--- server/controllers/api/config.ts | 2 +- server/controllers/api/custom-page.ts | 3 +-- server/controllers/api/overviews.ts | 10 +++++----- server/controllers/api/plugins.ts | 2 +- server/controllers/api/search/search-video-channels.ts | 3 +-- server/controllers/api/search/search-video-playlists.ts | 5 ++--- server/controllers/api/search/search-videos.ts | 3 +-- server/controllers/api/server/contact.ts | 8 ++++---- server/controllers/api/server/index.ts | 8 ++++---- server/controllers/api/server/logs.ts | 12 ++++++------ server/controllers/api/users/me.ts | 2 +- server/controllers/api/users/my-blocklist.ts | 10 +++++----- server/controllers/api/users/my-history.ts | 6 +++--- server/controllers/api/users/my-video-playlists.ts | 2 +- server/controllers/api/videos/blacklist.ts | 2 +- server/controllers/api/videos/comment.ts | 2 +- server/controllers/api/videos/ownership.ts | 14 +++++++------- server/controllers/api/videos/rate.ts | 4 ++-- server/controllers/api/videos/watching.ts | 2 +- server/controllers/download.ts | 3 +-- server/middlewares/cache.ts | 2 +- server/middlewares/servers.ts | 2 +- server/middlewares/user-right.ts | 2 +- server/middlewares/validators/activitypub/activity.ts | 4 ++-- server/middlewares/validators/bulk.ts | 3 +-- server/middlewares/validators/feeds.ts | 1 - server/middlewares/validators/shared/videos.ts | 3 +-- server/middlewares/validators/videos/video-live.ts | 3 +-- .../validators/videos/video-ownership-changes.ts | 10 ++++++++-- server/tests/api/activitypub/cleaner.ts | 2 +- server/tests/api/activitypub/client.ts | 5 ++--- server/tests/api/activitypub/fetch.ts | 2 +- server/tests/api/activitypub/refresher.ts | 5 ++--- server/tests/api/check-params/abuses.ts | 5 ++--- server/tests/api/check-params/accounts.ts | 2 +- server/tests/api/check-params/config.ts | 3 +-- server/tests/api/check-params/contact-form.ts | 2 +- server/tests/api/check-params/live.ts | 5 ++--- server/tests/api/check-params/plugins.ts | 3 +-- server/tests/api/check-params/search.ts | 2 +- server/tests/api/check-params/services.ts | 3 +-- server/tests/api/check-params/user-notifications.ts | 3 +-- server/tests/api/check-params/users.ts | 3 +-- server/tests/api/check-params/video-blacklist.ts | 5 ++--- server/tests/api/check-params/video-captions.ts | 3 +-- server/tests/api/check-params/video-channels.ts | 3 +-- server/tests/api/check-params/video-comments.ts | 3 +-- server/tests/api/check-params/video-imports.ts | 3 +-- server/tests/api/check-params/video-playlists.ts | 4 ++-- server/tests/api/check-params/videos-filter.ts | 3 +-- server/tests/api/check-params/videos-history.ts | 2 +- server/tests/api/live/live-constraints.ts | 2 +- server/tests/api/live/live-permanent.ts | 2 +- server/tests/api/live/live-save-replay.ts | 5 ++--- server/tests/api/live/live-socket-messages.ts | 2 +- server/tests/api/live/live-views.ts | 2 +- server/tests/api/live/live.ts | 15 +++++++++++---- server/tests/api/moderation/blocklist-notification.ts | 2 +- server/tests/api/moderation/blocklist.ts | 2 +- server/tests/api/notifications/admin-notifications.ts | 2 +- server/tests/api/notifications/comments-notifications.ts | 2 +- .../tests/api/notifications/moderation-notifications.ts | 2 +- server/tests/api/notifications/notifications-api.ts | 2 +- server/tests/api/redundancy/manage-redundancy.ts | 4 ++-- server/tests/api/redundancy/redundancy-constraints.ts | 9 +-------- server/tests/api/redundancy/redundancy.ts | 7 +++---- .../tests/api/search/search-activitypub-video-channels.ts | 2 +- .../api/search/search-activitypub-video-playlists.ts | 2 +- server/tests/api/search/search-activitypub-videos.ts | 2 +- server/tests/api/search/search-channels.ts | 2 +- server/tests/api/search/search-index.ts | 2 +- server/tests/api/search/search-playlists.ts | 2 +- server/tests/api/search/search-videos.ts | 2 +- server/tests/api/server/bulk.ts | 2 +- server/tests/api/server/config.ts | 3 +-- server/tests/api/server/contact-form.ts | 2 +- server/tests/api/server/email.ts | 2 +- server/tests/api/server/follow-constraints.ts | 13 ++++++------- server/tests/api/server/follows.ts | 2 +- server/tests/api/server/handle-down.ts | 3 +-- server/tests/api/server/homepage.ts | 2 +- server/tests/api/server/jobs.ts | 2 +- server/tests/api/server/plugins.ts | 5 ++--- server/tests/api/server/reverse-proxy.ts | 2 +- server/tests/api/server/stats.ts | 2 +- server/tests/api/users/user-subscriptions.ts | 5 +++-- server/tests/api/users/users-multiple-servers.ts | 2 +- server/tests/api/users/users-verification.ts | 2 +- server/tests/api/users/users.ts | 3 +-- server/tests/api/videos/audio-only.ts | 2 +- server/tests/api/videos/multiple-servers.ts | 5 ++--- server/tests/api/videos/resumable-upload.ts | 3 +-- server/tests/api/videos/video-captions.ts | 2 +- server/tests/api/videos/video-change-ownership.ts | 5 ++--- server/tests/api/videos/video-channels.ts | 2 +- server/tests/api/videos/video-comments.ts | 2 +- server/tests/api/videos/video-description.ts | 2 +- server/tests/api/videos/video-hls.ts | 5 ++--- server/tests/api/videos/video-nsfw.ts | 9 +++++---- server/tests/api/videos/video-playlist-thumbnails.ts | 2 +- server/tests/api/videos/video-playlists.ts | 6 +++--- server/tests/api/videos/video-privacy.ts | 7 +++---- server/tests/api/videos/video-schedule-update.ts | 2 +- server/tests/api/videos/video-transcoder.ts | 5 ++--- server/tests/api/videos/videos-filter.ts | 5 ++--- server/tests/api/videos/videos-history.ts | 3 +-- server/tests/api/videos/videos-views-cleaner.ts | 2 +- server/tests/cli/create-import-video-file-job.ts | 2 +- server/tests/cli/create-transcoding-job.ts | 2 +- server/tests/cli/optimize-old-videos.ts | 2 +- server/tests/cli/plugins.ts | 2 +- server/tests/cli/prune-storage.ts | 5 ++--- server/tests/cli/regenerate-thumbnails.ts | 5 ++--- server/tests/client.ts | 5 ++--- server/tests/external-plugins/auth-ldap.ts | 2 +- server/tests/external-plugins/auto-block-videos.ts | 2 +- server/tests/external-plugins/auto-mute.ts | 4 ++-- server/tests/feeds/feeds.ts | 5 ++--- server/tests/helpers/comment-model.ts | 2 +- server/tests/helpers/core-utils.ts | 4 ++-- server/tests/helpers/image.ts | 2 +- server/tests/misc-endpoints.ts | 3 +-- server/tests/plugins/action-hooks.ts | 2 +- server/tests/plugins/external-auth.ts | 7 +++---- server/tests/plugins/filter-hooks.ts | 3 +-- server/tests/plugins/html-injection.ts | 2 +- server/tests/plugins/id-and-pass-auth.ts | 5 ++--- server/tests/plugins/plugin-helpers.ts | 6 +++--- server/tests/plugins/plugin-router.ts | 4 ++-- server/tests/plugins/plugin-storage.ts | 2 +- server/tests/plugins/plugin-transcoding.ts | 2 +- server/tests/plugins/plugin-unloading.ts | 2 +- server/tests/plugins/video-constants.ts | 5 ++--- server/tools/peertube-redundancy.ts | 3 +-- shared/extra-utils/custom-pages/custom-pages-command.ts | 3 +-- shared/extra-utils/miscs/generate.ts | 2 +- shared/extra-utils/moderation/abuses-command.ts | 4 ++-- shared/extra-utils/overviews/overviews-command.ts | 3 +-- shared/extra-utils/requests/activitypub.ts | 2 +- shared/extra-utils/search/search-command.ts | 2 +- shared/extra-utils/server/config-command.ts | 2 +- shared/extra-utils/server/debug-command.ts | 3 +-- shared/extra-utils/server/follows-command.ts | 3 +-- shared/extra-utils/server/plugins-command.ts | 2 +- shared/extra-utils/server/redundancy-command.ts | 3 +-- shared/extra-utils/server/stats-command.ts | 3 +-- shared/extra-utils/users/accounts-command.ts | 3 +-- shared/extra-utils/users/blocklist-command.ts | 3 +-- shared/extra-utils/users/login-command.ts | 3 +-- shared/extra-utils/users/notifications-command.ts | 3 +-- shared/extra-utils/users/subscriptions-command.ts | 3 +-- shared/extra-utils/users/users-command.ts | 2 +- shared/extra-utils/videos/blacklist-command.ts | 3 +-- shared/extra-utils/videos/captions-command.ts | 3 +-- shared/extra-utils/videos/change-ownership-command.ts | 3 +-- shared/extra-utils/videos/channels-command.ts | 3 +-- shared/extra-utils/videos/comments-command.ts | 3 +-- shared/extra-utils/videos/history-command.ts | 3 +-- shared/extra-utils/videos/imports-command.ts | 3 +-- shared/extra-utils/videos/live-command.ts | 3 +-- shared/extra-utils/videos/playlists-command.ts | 2 +- shared/extra-utils/videos/streaming-playlists.ts | 3 +-- shared/extra-utils/videos/videos-command.ts | 15 ++++++++------- shared/extra-utils/videos/videos.ts | 2 +- 165 files changed, 265 insertions(+), 325 deletions(-) diff --git a/server/controllers/api/bulk.ts b/server/controllers/api/bulk.ts index 10d83571d..62121ece5 100644 --- a/server/controllers/api/bulk.ts +++ b/server/controllers/api/bulk.ts @@ -1,10 +1,10 @@ import * as express from 'express' -import { asyncMiddleware, authenticate } from '../../middlewares' +import { removeComment } from '@server/lib/video-comment' import { bulkRemoveCommentsOfValidator } from '@server/middlewares/validators/bulk' import { VideoCommentModel } from '@server/models/video/video-comment' -import { removeComment } from '@server/lib/video-comment' -import { BulkRemoveCommentsOfBody } from '@shared/models/bulk/bulk-remove-comments-of-body.model' import { HttpStatusCode } from '@shared/models' +import { BulkRemoveCommentsOfBody } from '@shared/models/bulk/bulk-remove-comments-of-body.model' +import { asyncMiddleware, authenticate } from '../../middlewares' const bulkRouter = express.Router() diff --git a/server/controllers/api/config.ts b/server/controllers/api/config.ts index 9bd8c21c5..ee733a38c 100644 --- a/server/controllers/api/config.ts +++ b/server/controllers/api/config.ts @@ -1,8 +1,8 @@ -import { ServerConfigManager } from '@server/lib/server-config-manager' import * as express from 'express' import { remove, writeJSON } from 'fs-extra' import { snakeCase } from 'lodash' import validator from 'validator' +import { ServerConfigManager } from '@server/lib/server-config-manager' import { UserRight } from '../../../shared' import { About } from '../../../shared/models/server/about.model' import { CustomConfig } from '../../../shared/models/server/custom-config.model' diff --git a/server/controllers/api/custom-page.ts b/server/controllers/api/custom-page.ts index cc1aa8427..68d8c2ea4 100644 --- a/server/controllers/api/custom-page.ts +++ b/server/controllers/api/custom-page.ts @@ -1,8 +1,7 @@ import * as express from 'express' import { ServerConfigManager } from '@server/lib/server-config-manager' import { ActorCustomPageModel } from '@server/models/account/actor-custom-page' -import { HttpStatusCode } from '@shared/models' -import { UserRight } from '@shared/models' +import { HttpStatusCode, UserRight } from '@shared/models' import { asyncMiddleware, authenticate, ensureUserHasRight } from '../../middlewares' const customPageRouter = express.Router() diff --git a/server/controllers/api/overviews.ts b/server/controllers/api/overviews.ts index ad879aad6..aaa341d54 100644 --- a/server/controllers/api/overviews.ts +++ b/server/controllers/api/overviews.ts @@ -1,12 +1,12 @@ import * as express from 'express' +import * as memoizee from 'memoizee' +import { logger } from '@server/helpers/logger' +import { CategoryOverview, ChannelOverview, TagOverview, VideosOverview } from '../../../shared/models/overviews' import { buildNSFWFilter } from '../../helpers/express-utils' -import { VideoModel } from '../../models/video/video' +import { MEMOIZE_TTL, OVERVIEWS } from '../../initializers/constants' import { asyncMiddleware, optionalAuthenticate, videosOverviewValidator } from '../../middlewares' import { TagModel } from '../../models/video/tag' -import { CategoryOverview, ChannelOverview, TagOverview, VideosOverview } from '../../../shared/models/overviews' -import { MEMOIZE_TTL, OVERVIEWS } from '../../initializers/constants' -import * as memoizee from 'memoizee' -import { logger } from '@server/helpers/logger' +import { VideoModel } from '../../models/video/video' const overviewsRouter = express.Router() diff --git a/server/controllers/api/plugins.ts b/server/controllers/api/plugins.ts index 4b213c246..3a9ef34e8 100644 --- a/server/controllers/api/plugins.ts +++ b/server/controllers/api/plugins.ts @@ -23,8 +23,8 @@ import { updatePluginSettingsValidator } from '@server/middlewares/validators/plugins' import { PluginModel } from '@server/models/server/plugin' -import { HttpStatusCode } from '@shared/models' import { + HttpStatusCode, InstallOrUpdatePlugin, ManagePlugin, PeertubePluginIndexList, diff --git a/server/controllers/api/search/search-video-channels.ts b/server/controllers/api/search/search-video-channels.ts index fe9178e69..c8f0a0a0b 100644 --- a/server/controllers/api/search/search-video-channels.ts +++ b/server/controllers/api/search/search-video-channels.ts @@ -6,8 +6,7 @@ import { WEBSERVER } from '@server/initializers/constants' import { Hooks } from '@server/lib/plugins/hooks' import { buildMutedForSearchIndex, isSearchIndexSearch, isURISearch } from '@server/lib/search' import { getServerActor } from '@server/models/application/application' -import { HttpStatusCode } from '@shared/models' -import { ResultList, VideoChannel } from '@shared/models' +import { HttpStatusCode, ResultList, VideoChannel } from '@shared/models' import { VideoChannelsSearchQuery } from '../../../../shared/models/search' import { isUserAbleToSearchRemoteURI } from '../../../helpers/express-utils' import { logger } from '../../../helpers/logger' diff --git a/server/controllers/api/search/search-video-playlists.ts b/server/controllers/api/search/search-video-playlists.ts index a0e2c1747..f55b1fba3 100644 --- a/server/controllers/api/search/search-video-playlists.ts +++ b/server/controllers/api/search/search-video-playlists.ts @@ -5,14 +5,14 @@ import { logger } from '@server/helpers/logger' import { doJSONRequest } from '@server/helpers/requests' import { getFormattedObjects } from '@server/helpers/utils' import { CONFIG } from '@server/initializers/config' +import { WEBSERVER } from '@server/initializers/constants' import { getOrCreateAPVideoPlaylist } from '@server/lib/activitypub/playlists/get' import { Hooks } from '@server/lib/plugins/hooks' import { buildMutedForSearchIndex, isSearchIndexSearch, isURISearch } from '@server/lib/search' import { getServerActor } from '@server/models/application/application' import { VideoPlaylistModel } from '@server/models/video/video-playlist' import { MVideoPlaylistFullSummary } from '@server/types/models' -import { HttpStatusCode } from '@shared/models' -import { ResultList, VideoPlaylist, VideoPlaylistsSearchQuery } from '@shared/models' +import { HttpStatusCode, ResultList, VideoPlaylist, VideoPlaylistsSearchQuery } from '@shared/models' import { asyncMiddleware, openapiOperationDoc, @@ -23,7 +23,6 @@ import { videoPlaylistsListSearchValidator, videoPlaylistsSearchSortValidator } from '../../../middlewares' -import { WEBSERVER } from '@server/initializers/constants' const searchPlaylistsRouter = express.Router() diff --git a/server/controllers/api/search/search-videos.ts b/server/controllers/api/search/search-videos.ts index 0e6fd9c72..a4153f3f8 100644 --- a/server/controllers/api/search/search-videos.ts +++ b/server/controllers/api/search/search-videos.ts @@ -6,8 +6,7 @@ import { WEBSERVER } from '@server/initializers/constants' import { getOrCreateAPVideo } from '@server/lib/activitypub/videos' import { Hooks } from '@server/lib/plugins/hooks' import { buildMutedForSearchIndex, isSearchIndexSearch, isURISearch } from '@server/lib/search' -import { HttpStatusCode } from '@shared/models' -import { ResultList, Video } from '@shared/models' +import { HttpStatusCode, ResultList, Video } from '@shared/models' import { VideosSearchQuery } from '../../../../shared/models/search' import { buildNSFWFilter, isUserAbleToSearchRemoteURI } from '../../../helpers/express-utils' import { logger } from '../../../helpers/logger' diff --git a/server/controllers/api/server/contact.ts b/server/controllers/api/server/contact.ts index ae36dd599..b315e99cf 100644 --- a/server/controllers/api/server/contact.ts +++ b/server/controllers/api/server/contact.ts @@ -1,9 +1,9 @@ import * as express from 'express' -import { asyncMiddleware, contactAdministratorValidator } from '../../../middlewares' -import { Redis } from '../../../lib/redis' -import { Emailer } from '../../../lib/emailer' -import { ContactForm } from '../../../../shared/models/server' import { HttpStatusCode } from '../../../../shared/models/http/http-error-codes' +import { ContactForm } from '../../../../shared/models/server' +import { Emailer } from '../../../lib/emailer' +import { Redis } from '../../../lib/redis' +import { asyncMiddleware, contactAdministratorValidator } from '../../../middlewares' const contactRouter = express.Router() diff --git a/server/controllers/api/server/index.ts b/server/controllers/api/server/index.ts index 6b8793a19..32fefefc0 100644 --- a/server/controllers/api/server/index.ts +++ b/server/controllers/api/server/index.ts @@ -1,11 +1,11 @@ import * as express from 'express' +import { contactRouter } from './contact' +import { debugRouter } from './debug' import { serverFollowsRouter } from './follows' -import { statsRouter } from './stats' +import { logsRouter } from './logs' import { serverRedundancyRouter } from './redundancy' import { serverBlocklistRouter } from './server-blocklist' -import { contactRouter } from './contact' -import { logsRouter } from './logs' -import { debugRouter } from './debug' +import { statsRouter } from './stats' const serverRouter = express.Router() diff --git a/server/controllers/api/server/logs.ts b/server/controllers/api/server/logs.ts index 4b543d686..f78607d35 100644 --- a/server/controllers/api/server/logs.ts +++ b/server/controllers/api/server/logs.ts @@ -1,14 +1,14 @@ import * as express from 'express' -import { UserRight } from '../../../../shared/models/users' -import { asyncMiddleware, authenticate, ensureUserHasRight } from '../../../middlewares' -import { mtimeSortFilesDesc } from '../../../../shared/core-utils/logs/logs' import { readdir, readFile } from 'fs-extra' -import { AUDIT_LOG_FILENAME, MAX_LOGS_OUTPUT_CHARACTERS, LOG_FILENAME } from '../../../initializers/constants' import { join } from 'path' -import { getAuditLogsValidator, getLogsValidator } from '../../../middlewares/validators/logs' +import { logger } from '@server/helpers/logger' +import { mtimeSortFilesDesc } from '../../../../shared/core-utils/logs/logs' import { LogLevel } from '../../../../shared/models/server/log-level.type' +import { UserRight } from '../../../../shared/models/users' import { CONFIG } from '../../../initializers/config' -import { logger } from '@server/helpers/logger' +import { AUDIT_LOG_FILENAME, LOG_FILENAME, MAX_LOGS_OUTPUT_CHARACTERS } from '../../../initializers/constants' +import { asyncMiddleware, authenticate, ensureUserHasRight } from '../../../middlewares' +import { getAuditLogsValidator, getLogsValidator } from '../../../middlewares/validators/logs' const logsRouter = express.Router() diff --git a/server/controllers/api/users/me.ts b/server/controllers/api/users/me.ts index c9610c59f..ac6faca9c 100644 --- a/server/controllers/api/users/me.ts +++ b/server/controllers/api/users/me.ts @@ -2,6 +2,7 @@ import 'multer' import * as express from 'express' import { auditLoggerFactory, getAuditIdFromRes, UserAuditView } from '@server/helpers/audit-logger' import { Hooks } from '@server/lib/plugins/hooks' +import { AttributesOnly } from '@shared/core-utils' import { ActorImageType, UserUpdateMe, UserVideoRate as FormattedUserVideoRate } from '../../../../shared' import { HttpStatusCode } from '../../../../shared/models/http/http-error-codes' import { UserVideoQuota } from '../../../../shared/models/users/user-video-quota.model' @@ -31,7 +32,6 @@ import { AccountVideoRateModel } from '../../../models/account/account-video-rat import { UserModel } from '../../../models/user/user' import { VideoModel } from '../../../models/video/video' import { VideoImportModel } from '../../../models/video/video-import' -import { AttributesOnly } from '@shared/core-utils' const auditLogger = auditLoggerFactory('users') diff --git a/server/controllers/api/users/my-blocklist.ts b/server/controllers/api/users/my-blocklist.ts index fe11b6e77..24fff83e3 100644 --- a/server/controllers/api/users/my-blocklist.ts +++ b/server/controllers/api/users/my-blocklist.ts @@ -1,6 +1,10 @@ -import * as express from 'express' import 'multer' +import * as express from 'express' +import { logger } from '@server/helpers/logger' +import { UserNotificationModel } from '@server/models/user/user-notification' +import { HttpStatusCode } from '../../../../shared/models/http/http-error-codes' import { getFormattedObjects } from '../../../helpers/utils' +import { addAccountInBlocklist, addServerInBlocklist, removeAccountFromBlocklist, removeServerFromBlocklist } from '../../../lib/blocklist' import { asyncMiddleware, asyncRetryTransactionMiddleware, @@ -18,11 +22,7 @@ import { unblockServerByAccountValidator } from '../../../middlewares/validators' import { AccountBlocklistModel } from '../../../models/account/account-blocklist' -import { addAccountInBlocklist, addServerInBlocklist, removeAccountFromBlocklist, removeServerFromBlocklist } from '../../../lib/blocklist' import { ServerBlocklistModel } from '../../../models/server/server-blocklist' -import { UserNotificationModel } from '@server/models/user/user-notification' -import { logger } from '@server/helpers/logger' -import { HttpStatusCode } from '../../../../shared/models/http/http-error-codes' const myBlocklistRouter = express.Router() diff --git a/server/controllers/api/users/my-history.ts b/server/controllers/api/users/my-history.ts index 85e04925e..a6e723103 100644 --- a/server/controllers/api/users/my-history.ts +++ b/server/controllers/api/users/my-history.ts @@ -1,4 +1,7 @@ import * as express from 'express' +import { HttpStatusCode } from '../../../../shared/models/http/http-error-codes' +import { getFormattedObjects } from '../../../helpers/utils' +import { sequelizeTypescript } from '../../../initializers/database' import { asyncMiddleware, asyncRetryTransactionMiddleware, @@ -8,10 +11,7 @@ import { userHistoryListValidator, userHistoryRemoveValidator } from '../../../middlewares' -import { getFormattedObjects } from '../../../helpers/utils' import { UserVideoHistoryModel } from '../../../models/user/user-video-history' -import { sequelizeTypescript } from '../../../initializers/database' -import { HttpStatusCode } from '../../../../shared/models/http/http-error-codes' const myVideosHistoryRouter = express.Router() diff --git a/server/controllers/api/users/my-video-playlists.ts b/server/controllers/api/users/my-video-playlists.ts index d0bd99463..76e741ba5 100644 --- a/server/controllers/api/users/my-video-playlists.ts +++ b/server/controllers/api/users/my-video-playlists.ts @@ -1,8 +1,8 @@ import * as express from 'express' +import { VideosExistInPlaylists } from '../../../../shared/models/videos/playlist/video-exist-in-playlist.model' import { asyncMiddleware, authenticate } from '../../../middlewares' import { doVideosInPlaylistExistValidator } from '../../../middlewares/validators/videos/video-playlists' import { VideoPlaylistModel } from '../../../models/video/video-playlist' -import { VideosExistInPlaylists } from '../../../../shared/models/videos/playlist/video-exist-in-playlist.model' const myVideoPlaylistsRouter = express.Router() diff --git a/server/controllers/api/videos/blacklist.ts b/server/controllers/api/videos/blacklist.ts index a7f5f53d8..6bc768471 100644 --- a/server/controllers/api/videos/blacklist.ts +++ b/server/controllers/api/videos/blacklist.ts @@ -1,6 +1,7 @@ import * as express from 'express' import { blacklistVideo, unblacklistVideo } from '@server/lib/video-blacklist' import { UserRight, VideoBlacklistCreate } from '../../../../shared' +import { HttpStatusCode } from '../../../../shared/models/http/http-error-codes' import { logger } from '../../../helpers/logger' import { getFormattedObjects } from '../../../helpers/utils' import { sequelizeTypescript } from '../../../initializers/database' @@ -19,7 +20,6 @@ import { videosBlacklistUpdateValidator } from '../../../middlewares' import { VideoBlacklistModel } from '../../../models/video/video-blacklist' -import { HttpStatusCode } from '../../../../shared/models/http/http-error-codes' const blacklistRouter = express.Router() diff --git a/server/controllers/api/videos/comment.ts b/server/controllers/api/videos/comment.ts index 90b633bb5..cb696f652 100644 --- a/server/controllers/api/videos/comment.ts +++ b/server/controllers/api/videos/comment.ts @@ -1,6 +1,6 @@ import * as express from 'express' -import { HttpStatusCode } from '../../../../shared/models/http/http-error-codes' import { ResultList, ThreadsResultList, UserRight, VideoCommentCreate } from '../../../../shared/models' +import { HttpStatusCode } from '../../../../shared/models/http/http-error-codes' import { VideoCommentThreads } from '../../../../shared/models/videos/comment/video-comment.model' import { auditLoggerFactory, CommentAuditView, getAuditIdFromRes } from '../../../helpers/audit-logger' import { getFormattedObjects } from '../../../helpers/utils' diff --git a/server/controllers/api/videos/ownership.ts b/server/controllers/api/videos/ownership.ts index e6c94a45a..f48acbc68 100644 --- a/server/controllers/api/videos/ownership.ts +++ b/server/controllers/api/videos/ownership.ts @@ -1,6 +1,12 @@ import * as express from 'express' +import { MVideoFullLight } from '@server/types/models' +import { HttpStatusCode } from '../../../../shared/models/http/http-error-codes' +import { VideoChangeOwnershipStatus, VideoState } from '../../../../shared/models/videos' import { logger } from '../../../helpers/logger' +import { getFormattedObjects } from '../../../helpers/utils' import { sequelizeTypescript } from '../../../initializers/database' +import { sendUpdateVideo } from '../../../lib/activitypub/send' +import { changeVideoChannelShare } from '../../../lib/activitypub/share' import { asyncMiddleware, asyncRetryTransactionMiddleware, @@ -11,15 +17,9 @@ import { videosChangeOwnershipValidator, videosTerminateChangeOwnershipValidator } from '../../../middlewares' +import { VideoModel } from '../../../models/video/video' import { VideoChangeOwnershipModel } from '../../../models/video/video-change-ownership' -import { VideoChangeOwnershipStatus, VideoState } from '../../../../shared/models/videos' import { VideoChannelModel } from '../../../models/video/video-channel' -import { getFormattedObjects } from '../../../helpers/utils' -import { changeVideoChannelShare } from '../../../lib/activitypub/share' -import { sendUpdateVideo } from '../../../lib/activitypub/send' -import { VideoModel } from '../../../models/video/video' -import { MVideoFullLight } from '@server/types/models' -import { HttpStatusCode } from '../../../../shared/models/http/http-error-codes' const ownershipVideoRouter = express.Router() diff --git a/server/controllers/api/videos/rate.ts b/server/controllers/api/videos/rate.ts index 134c9e5ca..96f6cd886 100644 --- a/server/controllers/api/videos/rate.ts +++ b/server/controllers/api/videos/rate.ts @@ -1,13 +1,13 @@ import * as express from 'express' import { UserVideoRateUpdate } from '../../../../shared' +import { HttpStatusCode } from '../../../../shared/models/http/http-error-codes' import { logger } from '../../../helpers/logger' import { VIDEO_RATE_TYPES } from '../../../initializers/constants' +import { sequelizeTypescript } from '../../../initializers/database' import { getLocalRateUrl, sendVideoRateChange } from '../../../lib/activitypub/video-rates' import { asyncMiddleware, asyncRetryTransactionMiddleware, authenticate, videoUpdateRateValidator } from '../../../middlewares' import { AccountModel } from '../../../models/account/account' import { AccountVideoRateModel } from '../../../models/account/account-video-rate' -import { sequelizeTypescript } from '../../../initializers/database' -import { HttpStatusCode } from '../../../../shared/models/http/http-error-codes' const rateVideoRouter = express.Router() diff --git a/server/controllers/api/videos/watching.ts b/server/controllers/api/videos/watching.ts index 2899dbd9c..05c75e543 100644 --- a/server/controllers/api/videos/watching.ts +++ b/server/controllers/api/videos/watching.ts @@ -1,5 +1,6 @@ import * as express from 'express' import { UserWatchingVideo } from '../../../../shared' +import { HttpStatusCode } from '../../../../shared/models/http/http-error-codes' import { asyncMiddleware, asyncRetryTransactionMiddleware, @@ -8,7 +9,6 @@ import { videoWatchingValidator } from '../../../middlewares' import { UserVideoHistoryModel } from '../../../models/user/user-video-history' -import { HttpStatusCode } from '../../../../shared/models/http/http-error-codes' const watchingRouter = express.Router() diff --git a/server/controllers/download.ts b/server/controllers/download.ts index 13bc66900..ddacc1b68 100644 --- a/server/controllers/download.ts +++ b/server/controllers/download.ts @@ -5,8 +5,7 @@ import { VideosTorrentCache } from '@server/lib/files-cache/videos-torrent-cache import { Hooks } from '@server/lib/plugins/hooks' import { getVideoFilePath } from '@server/lib/video-paths' import { MStreamingPlaylist, MVideo, MVideoFile, MVideoFullLight } from '@server/types/models' -import { HttpStatusCode } from '@shared/models' -import { VideoStreamingPlaylistType } from '@shared/models' +import { HttpStatusCode, VideoStreamingPlaylistType } from '@shared/models' import { STATIC_DOWNLOAD_PATHS } from '../initializers/constants' import { asyncMiddleware, videosDownloadValidator } from '../middlewares' diff --git a/server/middlewares/cache.ts b/server/middlewares/cache.ts index 1ced06042..e508b22a6 100644 --- a/server/middlewares/cache.ts +++ b/server/middlewares/cache.ts @@ -1,6 +1,6 @@ -import { Redis } from '../lib/redis' import * as apicache from 'apicache' import { HttpStatusCode } from '../../shared/models/http/http-error-codes' +import { Redis } from '../lib/redis' // Ensure Redis is initialized Redis.Instance.init() diff --git a/server/middlewares/servers.ts b/server/middlewares/servers.ts index 49a2241b3..cf70d901e 100644 --- a/server/middlewares/servers.ts +++ b/server/middlewares/servers.ts @@ -1,6 +1,6 @@ import * as express from 'express' -import { getHostWithPort } from '../helpers/express-utils' import { HttpStatusCode } from '../../shared/models/http/http-error-codes' +import { getHostWithPort } from '../helpers/express-utils' function setBodyHostsPort (req: express.Request, res: express.Response, next: express.NextFunction) { if (!req.body.hosts) return next() diff --git a/server/middlewares/user-right.ts b/server/middlewares/user-right.ts index 87a1766cf..c8c694f05 100644 --- a/server/middlewares/user-right.ts +++ b/server/middlewares/user-right.ts @@ -1,7 +1,7 @@ import * as express from 'express' import { UserRight } from '../../shared' -import { logger } from '../helpers/logger' import { HttpStatusCode } from '../../shared/models/http/http-error-codes' +import { logger } from '../helpers/logger' function ensureUserHasRight (userRight: UserRight) { return function (req: express.Request, res: express.Response, next: express.NextFunction) { diff --git a/server/middlewares/validators/activitypub/activity.ts b/server/middlewares/validators/activitypub/activity.ts index d65a8e455..d24e4427b 100644 --- a/server/middlewares/validators/activitypub/activity.ts +++ b/server/middlewares/validators/activitypub/activity.ts @@ -1,8 +1,8 @@ import * as express from 'express' -import { isRootActivityValid } from '../../../helpers/custom-validators/activitypub/activity' -import { logger } from '../../../helpers/logger' import { getServerActor } from '@server/models/application/application' import { HttpStatusCode } from '../../../../shared/models/http/http-error-codes' +import { isRootActivityValid } from '../../../helpers/custom-validators/activitypub/activity' +import { logger } from '../../../helpers/logger' async function activityPubValidator (req: express.Request, res: express.Response, next: express.NextFunction) { logger.debug('Checking activity pub parameters') diff --git a/server/middlewares/validators/bulk.ts b/server/middlewares/validators/bulk.ts index 4057b1e01..6fec58149 100644 --- a/server/middlewares/validators/bulk.ts +++ b/server/middlewares/validators/bulk.ts @@ -1,8 +1,7 @@ import * as express from 'express' import { body } from 'express-validator' import { isBulkRemoveCommentsOfScopeValid } from '@server/helpers/custom-validators/bulk' -import { HttpStatusCode } from '@shared/models' -import { UserRight } from '@shared/models' +import { HttpStatusCode, UserRight } from '@shared/models' import { BulkRemoveCommentsOfBody } from '@shared/models/bulk/bulk-remove-comments-of-body.model' import { logger } from '../../helpers/logger' import { areValidationErrors, doesAccountNameWithHostExist } from './shared' diff --git a/server/middlewares/validators/feeds.ts b/server/middlewares/validators/feeds.ts index 1a5a8ffa0..d29bebf64 100644 --- a/server/middlewares/validators/feeds.ts +++ b/server/middlewares/validators/feeds.ts @@ -1,6 +1,5 @@ import * as express from 'express' import { param, query } from 'express-validator' - import { HttpStatusCode } from '../../../shared/models/http/http-error-codes' import { isValidRSSFeed } from '../../helpers/custom-validators/feeds' import { exists, isIdOrUUIDValid, isIdValid, toCompleteUUID } from '../../helpers/custom-validators/misc' diff --git a/server/middlewares/validators/shared/videos.ts b/server/middlewares/validators/shared/videos.ts index 7f42a4893..71b81654f 100644 --- a/server/middlewares/validators/shared/videos.ts +++ b/server/middlewares/validators/shared/videos.ts @@ -12,8 +12,7 @@ import { MVideoImmutable, MVideoThumbnail } from '@server/types/models' -import { HttpStatusCode } from '@shared/models' -import { UserRight } from '@shared/models' +import { HttpStatusCode, UserRight } from '@shared/models' async function doesVideoExist (id: number | string, res: Response, fetchType: VideoLoadType = 'all') { const userId = res.locals.oauth ? res.locals.oauth.token.User.id : undefined diff --git a/server/middlewares/validators/videos/video-live.ts b/server/middlewares/validators/videos/video-live.ts index 5c8a4269d..97e8b4510 100644 --- a/server/middlewares/validators/videos/video-live.ts +++ b/server/middlewares/validators/videos/video-live.ts @@ -5,8 +5,7 @@ import { isLocalLiveVideoAccepted } from '@server/lib/moderation' import { Hooks } from '@server/lib/plugins/hooks' import { VideoModel } from '@server/models/video/video' import { VideoLiveModel } from '@server/models/video/video-live' -import { HttpStatusCode } from '@shared/models' -import { ServerErrorCode, UserRight, VideoState } from '@shared/models' +import { HttpStatusCode, ServerErrorCode, UserRight, VideoState } from '@shared/models' import { isBooleanValid, isIdValid, toBooleanOrNull, toIntOrNull } from '../../../helpers/custom-validators/misc' import { isVideoNameValid } from '../../../helpers/custom-validators/videos' import { cleanUpReqFiles } from '../../../helpers/express-utils' diff --git a/server/middlewares/validators/videos/video-ownership-changes.ts b/server/middlewares/validators/videos/video-ownership-changes.ts index 06f86a4c8..a7f0b72c3 100644 --- a/server/middlewares/validators/videos/video-ownership-changes.ts +++ b/server/middlewares/validators/videos/video-ownership-changes.ts @@ -6,8 +6,14 @@ import { logger } from '@server/helpers/logger' import { isAbleToUploadVideo } from '@server/lib/user' import { AccountModel } from '@server/models/account/account' import { MVideoWithAllFiles } from '@server/types/models' -import { HttpStatusCode } from '@shared/models' -import { ServerErrorCode, UserRight, VideoChangeOwnershipAccept, VideoChangeOwnershipStatus, VideoState } from '@shared/models' +import { + HttpStatusCode, + ServerErrorCode, + UserRight, + VideoChangeOwnershipAccept, + VideoChangeOwnershipStatus, + VideoState +} from '@shared/models' import { areValidationErrors, checkUserCanManageVideo, diff --git a/server/tests/api/activitypub/cleaner.ts b/server/tests/api/activitypub/cleaner.ts index a5ce449f3..51cf6e599 100644 --- a/server/tests/api/activitypub/cleaner.ts +++ b/server/tests/api/activitypub/cleaner.ts @@ -4,8 +4,8 @@ import 'mocha' import * as chai from 'chai' import { cleanupTests, - doubleFollow, createMultipleServers, + doubleFollow, PeerTubeServer, setAccessTokensToServers, wait, diff --git a/server/tests/api/activitypub/client.ts b/server/tests/api/activitypub/client.ts index 53cc40663..c3e4b7f74 100644 --- a/server/tests/api/activitypub/client.ts +++ b/server/tests/api/activitypub/client.ts @@ -2,17 +2,16 @@ import 'mocha' import * as chai from 'chai' -import { HttpStatusCode } from '@shared/models' import { cleanupTests, - doubleFollow, createMultipleServers, + doubleFollow, makeActivityPubGetRequest, PeerTubeServer, setAccessTokensToServers, setDefaultVideoChannel } from '@shared/extra-utils' -import { VideoPlaylistPrivacy } from '@shared/models' +import { HttpStatusCode, VideoPlaylistPrivacy } from '@shared/models' const expect = chai.expect diff --git a/server/tests/api/activitypub/fetch.ts b/server/tests/api/activitypub/fetch.ts index ddfe6cfe0..422a75d6e 100644 --- a/server/tests/api/activitypub/fetch.ts +++ b/server/tests/api/activitypub/fetch.ts @@ -2,7 +2,7 @@ import 'mocha' import * as chai from 'chai' -import { cleanupTests, doubleFollow, createMultipleServers, PeerTubeServer, setAccessTokensToServers, waitJobs } from '@shared/extra-utils' +import { cleanupTests, createMultipleServers, doubleFollow, PeerTubeServer, setAccessTokensToServers, waitJobs } from '@shared/extra-utils' const expect = chai.expect diff --git a/server/tests/api/activitypub/refresher.ts b/server/tests/api/activitypub/refresher.ts index a0b72c7e6..81fee0044 100644 --- a/server/tests/api/activitypub/refresher.ts +++ b/server/tests/api/activitypub/refresher.ts @@ -1,11 +1,10 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ import 'mocha' -import { HttpStatusCode } from '@shared/models' import { cleanupTests, - doubleFollow, createMultipleServers, + doubleFollow, killallServers, PeerTubeServer, setAccessTokensToServers, @@ -13,7 +12,7 @@ import { wait, waitJobs } from '@shared/extra-utils' -import { VideoPlaylistPrivacy } from '@shared/models' +import { HttpStatusCode, VideoPlaylistPrivacy } from '@shared/models' describe('Test AP refresher', function () { let servers: PeerTubeServer[] = [] diff --git a/server/tests/api/check-params/abuses.ts b/server/tests/api/check-params/abuses.ts index 87d93195c..72f2cbd8f 100644 --- a/server/tests/api/check-params/abuses.ts +++ b/server/tests/api/check-params/abuses.ts @@ -1,22 +1,21 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ import 'mocha' -import { HttpStatusCode } from '@shared/models' import { AbusesCommand, checkBadCountPagination, checkBadSortPagination, checkBadStartPagination, cleanupTests, - doubleFollow, createSingleServer, + doubleFollow, makeGetRequest, makePostBodyRequest, PeerTubeServer, setAccessTokensToServers, waitJobs } from '@shared/extra-utils' -import { AbuseCreate, AbuseState } from '@shared/models' +import { AbuseCreate, AbuseState, HttpStatusCode } from '@shared/models' describe('Test abuses API validators', function () { const basePath = '/api/v1/abuses/' diff --git a/server/tests/api/check-params/accounts.ts b/server/tests/api/check-params/accounts.ts index 0cae485d9..141d869b7 100644 --- a/server/tests/api/check-params/accounts.ts +++ b/server/tests/api/check-params/accounts.ts @@ -1,7 +1,6 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ import 'mocha' -import { HttpStatusCode } from '@shared/models' import { checkBadCountPagination, checkBadSortPagination, @@ -10,6 +9,7 @@ import { createSingleServer, PeerTubeServer } from '@shared/extra-utils' +import { HttpStatusCode } from '@shared/models' describe('Test accounts API validators', function () { const path = '/api/v1/accounts/' diff --git a/server/tests/api/check-params/config.ts b/server/tests/api/check-params/config.ts index c3438917e..87cb2287e 100644 --- a/server/tests/api/check-params/config.ts +++ b/server/tests/api/check-params/config.ts @@ -2,7 +2,6 @@ import 'mocha' import { omit } from 'lodash' -import { HttpStatusCode } from '@shared/models' import { cleanupTests, createSingleServer, @@ -12,7 +11,7 @@ import { PeerTubeServer, setAccessTokensToServers } from '@shared/extra-utils' -import { CustomConfig } from '@shared/models' +import { CustomConfig, HttpStatusCode } from '@shared/models' describe('Test config API validators', function () { const path = '/api/v1/config/custom' diff --git a/server/tests/api/check-params/contact-form.ts b/server/tests/api/check-params/contact-form.ts index 8e755c69b..1df9993da 100644 --- a/server/tests/api/check-params/contact-form.ts +++ b/server/tests/api/check-params/contact-form.ts @@ -1,9 +1,9 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ import 'mocha' -import { HttpStatusCode } from '@shared/models' import { cleanupTests, createSingleServer, killallServers, MockSmtpServer, PeerTubeServer } from '@shared/extra-utils' import { ContactFormCommand } from '@shared/extra-utils/server' +import { HttpStatusCode } from '@shared/models' describe('Test contact form API validators', function () { let server: PeerTubeServer diff --git a/server/tests/api/check-params/live.ts b/server/tests/api/check-params/live.ts index 0ef86a538..700b4724d 100644 --- a/server/tests/api/check-params/live.ts +++ b/server/tests/api/check-params/live.ts @@ -2,7 +2,6 @@ import 'mocha' import { omit } from 'lodash' -import { HttpStatusCode } from '@shared/models' import { buildAbsoluteFixturePath, cleanupTests, @@ -10,12 +9,12 @@ import { LiveCommand, makePostBodyRequest, makeUploadRequest, - sendRTMPStream, PeerTubeServer, + sendRTMPStream, setAccessTokensToServers, stopFfmpeg } from '@shared/extra-utils' -import { VideoCreateResult, VideoPrivacy } from '@shared/models' +import { HttpStatusCode, VideoCreateResult, VideoPrivacy } from '@shared/models' describe('Test video lives API validator', function () { const path = '/api/v1/videos/live' diff --git a/server/tests/api/check-params/plugins.ts b/server/tests/api/check-params/plugins.ts index d3dda7fce..33f84ecbc 100644 --- a/server/tests/api/check-params/plugins.ts +++ b/server/tests/api/check-params/plugins.ts @@ -1,7 +1,6 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ import 'mocha' -import { HttpStatusCode } from '@shared/models' import { checkBadCountPagination, checkBadSortPagination, @@ -14,7 +13,7 @@ import { PeerTubeServer, setAccessTokensToServers } from '@shared/extra-utils' -import { PeerTubePlugin, PluginType } from '@shared/models' +import { HttpStatusCode, PeerTubePlugin, PluginType } from '@shared/models' describe('Test server plugins API validators', function () { let server: PeerTubeServer diff --git a/server/tests/api/check-params/search.ts b/server/tests/api/check-params/search.ts index b49169e38..a3da54e1f 100644 --- a/server/tests/api/check-params/search.ts +++ b/server/tests/api/check-params/search.ts @@ -1,7 +1,6 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ import 'mocha' -import { HttpStatusCode } from '@shared/models' import { checkBadCountPagination, checkBadSortPagination, @@ -12,6 +11,7 @@ import { PeerTubeServer, setAccessTokensToServers } from '@shared/extra-utils' +import { HttpStatusCode } from '@shared/models' function updateSearchIndex (server: PeerTubeServer, enabled: boolean, disableLocalSearch = false) { return server.config.updateCustomSubConfig({ diff --git a/server/tests/api/check-params/services.ts b/server/tests/api/check-params/services.ts index 973b25598..4c4a5cade 100644 --- a/server/tests/api/check-params/services.ts +++ b/server/tests/api/check-params/services.ts @@ -1,7 +1,6 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ import 'mocha' -import { HttpStatusCode } from '@shared/models' import { cleanupTests, createSingleServer, @@ -10,7 +9,7 @@ import { setAccessTokensToServers, setDefaultVideoChannel } from '@shared/extra-utils' -import { VideoPlaylistPrivacy } from '@shared/models' +import { HttpStatusCode, VideoPlaylistPrivacy } from '@shared/models' describe('Test services API validators', function () { let server: PeerTubeServer diff --git a/server/tests/api/check-params/user-notifications.ts b/server/tests/api/check-params/user-notifications.ts index 3b709ee5a..17edf5aa1 100644 --- a/server/tests/api/check-params/user-notifications.ts +++ b/server/tests/api/check-params/user-notifications.ts @@ -2,7 +2,6 @@ import 'mocha' import { io } from 'socket.io-client' -import { HttpStatusCode } from '@shared/models' import { checkBadCountPagination, checkBadSortPagination, @@ -16,7 +15,7 @@ import { setAccessTokensToServers, wait } from '@shared/extra-utils' -import { UserNotificationSetting, UserNotificationSettingValue } from '@shared/models' +import { HttpStatusCode, UserNotificationSetting, UserNotificationSettingValue } from '@shared/models' describe('Test user notifications API validators', function () { let server: PeerTubeServer diff --git a/server/tests/api/check-params/users.ts b/server/tests/api/check-params/users.ts index 34fe309f9..9d8f933db 100644 --- a/server/tests/api/check-params/users.ts +++ b/server/tests/api/check-params/users.ts @@ -2,7 +2,6 @@ import 'mocha' import { omit } from 'lodash' -import { HttpStatusCode } from '@shared/models' import { buildAbsoluteFixturePath, checkBadCountPagination, @@ -20,7 +19,7 @@ import { setAccessTokensToServers, UsersCommand } from '@shared/extra-utils' -import { UserAdminFlag, UserRole, VideoCreateResult } from '@shared/models' +import { HttpStatusCode, UserAdminFlag, UserRole, VideoCreateResult } from '@shared/models' describe('Test users API validators', function () { const path = '/api/v1/users/' diff --git a/server/tests/api/check-params/video-blacklist.ts b/server/tests/api/check-params/video-blacklist.ts index 2072df4b6..d28c6a952 100644 --- a/server/tests/api/check-params/video-blacklist.ts +++ b/server/tests/api/check-params/video-blacklist.ts @@ -2,22 +2,21 @@ import 'mocha' import { expect } from 'chai' -import { HttpStatusCode } from '@shared/models' import { BlacklistCommand, checkBadCountPagination, checkBadSortPagination, checkBadStartPagination, cleanupTests, - doubleFollow, createMultipleServers, + doubleFollow, makePostBodyRequest, makePutBodyRequest, PeerTubeServer, setAccessTokensToServers, waitJobs } from '@shared/extra-utils' -import { VideoBlacklistType } from '@shared/models' +import { HttpStatusCode, VideoBlacklistType } from '@shared/models' describe('Test video blacklist API validators', function () { let servers: PeerTubeServer[] diff --git a/server/tests/api/check-params/video-captions.ts b/server/tests/api/check-params/video-captions.ts index 1b3d1aa95..5aaeb27fe 100644 --- a/server/tests/api/check-params/video-captions.ts +++ b/server/tests/api/check-params/video-captions.ts @@ -1,7 +1,6 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ import 'mocha' -import { HttpStatusCode } from '@shared/models' import { buildAbsoluteFixturePath, cleanupTests, @@ -12,7 +11,7 @@ import { PeerTubeServer, setAccessTokensToServers } from '@shared/extra-utils' -import { VideoCreateResult } from '@shared/models' +import { HttpStatusCode, VideoCreateResult } from '@shared/models' describe('Test video captions API validator', function () { const path = '/api/v1/videos/' diff --git a/server/tests/api/check-params/video-channels.ts b/server/tests/api/check-params/video-channels.ts index bbe42e43d..2e63916d4 100644 --- a/server/tests/api/check-params/video-channels.ts +++ b/server/tests/api/check-params/video-channels.ts @@ -3,7 +3,6 @@ import 'mocha' import * as chai from 'chai' import { omit } from 'lodash' -import { HttpStatusCode } from '@shared/models' import { buildAbsoluteFixturePath, ChannelsCommand, @@ -19,7 +18,7 @@ import { PeerTubeServer, setAccessTokensToServers } from '@shared/extra-utils' -import { VideoChannelUpdate } from '@shared/models' +import { HttpStatusCode, VideoChannelUpdate } from '@shared/models' const expect = chai.expect diff --git a/server/tests/api/check-params/video-comments.ts b/server/tests/api/check-params/video-comments.ts index bfd9e0172..2d9ee1e0d 100644 --- a/server/tests/api/check-params/video-comments.ts +++ b/server/tests/api/check-params/video-comments.ts @@ -2,7 +2,6 @@ import 'mocha' import * as chai from 'chai' -import { HttpStatusCode } from '@shared/models' import { checkBadCountPagination, checkBadSortPagination, @@ -15,7 +14,7 @@ import { PeerTubeServer, setAccessTokensToServers } from '@shared/extra-utils' -import { VideoCreateResult } from '@shared/models' +import { HttpStatusCode, VideoCreateResult } from '@shared/models' const expect = chai.expect diff --git a/server/tests/api/check-params/video-imports.ts b/server/tests/api/check-params/video-imports.ts index 957556c9b..d6d745488 100644 --- a/server/tests/api/check-params/video-imports.ts +++ b/server/tests/api/check-params/video-imports.ts @@ -2,7 +2,6 @@ import 'mocha' import { omit } from 'lodash' -import { HttpStatusCode } from '@shared/models' import { buildAbsoluteFixturePath, checkBadCountPagination, @@ -17,7 +16,7 @@ import { PeerTubeServer, setAccessTokensToServers } from '@shared/extra-utils' -import { VideoPrivacy } from '@shared/models' +import { HttpStatusCode, VideoPrivacy } from '@shared/models' describe('Test video imports API validator', function () { const path = '/api/v1/videos/imports' diff --git a/server/tests/api/check-params/video-playlists.ts b/server/tests/api/check-params/video-playlists.ts index 7dcb4935a..e4d541b48 100644 --- a/server/tests/api/check-params/video-playlists.ts +++ b/server/tests/api/check-params/video-playlists.ts @@ -1,7 +1,6 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ import 'mocha' -import { HttpStatusCode } from '@shared/models' import { checkBadCountPagination, checkBadSortPagination, @@ -9,12 +8,13 @@ import { cleanupTests, createSingleServer, makeGetRequest, - PlaylistsCommand, PeerTubeServer, + PlaylistsCommand, setAccessTokensToServers, setDefaultVideoChannel } from '@shared/extra-utils' import { + HttpStatusCode, VideoPlaylistCreate, VideoPlaylistCreateResult, VideoPlaylistElementCreate, diff --git a/server/tests/api/check-params/videos-filter.ts b/server/tests/api/check-params/videos-filter.ts index c2c69904f..d08570bbe 100644 --- a/server/tests/api/check-params/videos-filter.ts +++ b/server/tests/api/check-params/videos-filter.ts @@ -1,7 +1,6 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ import 'mocha' -import { HttpStatusCode } from '@shared/models' import { cleanupTests, createSingleServer, @@ -10,7 +9,7 @@ import { setAccessTokensToServers, setDefaultVideoChannel } from '@shared/extra-utils' -import { UserRole } from '@shared/models' +import { HttpStatusCode, UserRole } from '@shared/models' async function testEndpoints (server: PeerTubeServer, token: string, filter: string, expectedStatus: HttpStatusCode) { const paths = [ diff --git a/server/tests/api/check-params/videos-history.ts b/server/tests/api/check-params/videos-history.ts index 7283a4d28..c3c309ed2 100644 --- a/server/tests/api/check-params/videos-history.ts +++ b/server/tests/api/check-params/videos-history.ts @@ -1,7 +1,6 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ import 'mocha' -import { HttpStatusCode } from '@shared/models' import { checkBadCountPagination, checkBadStartPagination, @@ -13,6 +12,7 @@ import { PeerTubeServer, setAccessTokensToServers } from '@shared/extra-utils' +import { HttpStatusCode } from '@shared/models' describe('Test videos history API validator', function () { const myHistoryPath = '/api/v1/users/me/history/videos' diff --git a/server/tests/api/live/live-constraints.ts b/server/tests/api/live/live-constraints.ts index a00833569..20346113d 100644 --- a/server/tests/api/live/live-constraints.ts +++ b/server/tests/api/live/live-constraints.ts @@ -7,8 +7,8 @@ import { checkLiveCleanup, cleanupTests, ConfigCommand, - doubleFollow, createMultipleServers, + doubleFollow, PeerTubeServer, setAccessTokensToServers, setDefaultVideoChannel, diff --git a/server/tests/api/live/live-permanent.ts b/server/tests/api/live/live-permanent.ts index 30d499e20..f07d4cfec 100644 --- a/server/tests/api/live/live-permanent.ts +++ b/server/tests/api/live/live-permanent.ts @@ -6,8 +6,8 @@ import { LiveVideoCreate, VideoPrivacy, VideoState } from '@shared/models' import { cleanupTests, ConfigCommand, - doubleFollow, createMultipleServers, + doubleFollow, PeerTubeServer, setAccessTokensToServers, setDefaultVideoChannel, diff --git a/server/tests/api/live/live-save-replay.ts b/server/tests/api/live/live-save-replay.ts index 095c51b97..bd15396ec 100644 --- a/server/tests/api/live/live-save-replay.ts +++ b/server/tests/api/live/live-save-replay.ts @@ -3,13 +3,12 @@ import 'mocha' import * as chai from 'chai' import { FfmpegCommand } from 'fluent-ffmpeg' -import { HttpStatusCode } from '@shared/models' import { checkLiveCleanup, cleanupTests, ConfigCommand, - doubleFollow, createMultipleServers, + doubleFollow, PeerTubeServer, setAccessTokensToServers, setDefaultVideoChannel, @@ -18,7 +17,7 @@ import { wait, waitJobs } from '@shared/extra-utils' -import { LiveVideoCreate, VideoPrivacy, VideoState } from '@shared/models' +import { HttpStatusCode, LiveVideoCreate, VideoPrivacy, VideoState } from '@shared/models' const expect = chai.expect diff --git a/server/tests/api/live/live-socket-messages.ts b/server/tests/api/live/live-socket-messages.ts index 3808964d1..2a1f9f108 100644 --- a/server/tests/api/live/live-socket-messages.ts +++ b/server/tests/api/live/live-socket-messages.ts @@ -5,8 +5,8 @@ import * as chai from 'chai' import { VideoPrivacy, VideoState } from '@shared/models' import { cleanupTests, - doubleFollow, createMultipleServers, + doubleFollow, PeerTubeServer, setAccessTokensToServers, setDefaultVideoChannel, diff --git a/server/tests/api/live/live-views.ts b/server/tests/api/live/live-views.ts index 4a137b185..5e3a79c64 100644 --- a/server/tests/api/live/live-views.ts +++ b/server/tests/api/live/live-views.ts @@ -6,8 +6,8 @@ import { FfmpegCommand } from 'fluent-ffmpeg' import { VideoPrivacy } from '@shared/models' import { cleanupTests, - doubleFollow, createMultipleServers, + doubleFollow, PeerTubeServer, setAccessTokensToServers, setDefaultVideoChannel, diff --git a/server/tests/api/live/live.ts b/server/tests/api/live/live.ts index 88995910c..4676a840a 100644 --- a/server/tests/api/live/live.ts +++ b/server/tests/api/live/live.ts @@ -4,19 +4,18 @@ import 'mocha' import * as chai from 'chai' import { join } from 'path' import { ffprobePromise, getVideoStreamFromFile } from '@server/helpers/ffprobe-utils' -import { HttpStatusCode } from '@shared/models' import { checkLiveCleanup, checkLiveSegmentHash, checkResolutionsInMasterPlaylist, cleanupTests, - doubleFollow, createMultipleServers, + doubleFollow, killallServers, LiveCommand, makeRawRequest, - sendRTMPStream, PeerTubeServer, + sendRTMPStream, setAccessTokensToServers, setDefaultVideoChannel, stopFfmpeg, @@ -26,7 +25,15 @@ import { waitJobs, waitUntilLivePublishedOnAllServers } from '@shared/extra-utils' -import { LiveVideo, LiveVideoCreate, VideoDetails, VideoPrivacy, VideoState, VideoStreamingPlaylistType } from '@shared/models' +import { + HttpStatusCode, + LiveVideo, + LiveVideoCreate, + VideoDetails, + VideoPrivacy, + VideoState, + VideoStreamingPlaylistType +} from '@shared/models' const expect = chai.expect diff --git a/server/tests/api/moderation/blocklist-notification.ts b/server/tests/api/moderation/blocklist-notification.ts index fdfbcbced..75b15c298 100644 --- a/server/tests/api/moderation/blocklist-notification.ts +++ b/server/tests/api/moderation/blocklist-notification.ts @@ -2,7 +2,7 @@ import 'mocha' import * as chai from 'chai' -import { cleanupTests, doubleFollow, createMultipleServers, PeerTubeServer, setAccessTokensToServers, waitJobs } from '@shared/extra-utils' +import { cleanupTests, createMultipleServers, doubleFollow, PeerTubeServer, setAccessTokensToServers, waitJobs } from '@shared/extra-utils' import { UserNotificationType } from '@shared/models' const expect = chai.expect diff --git a/server/tests/api/moderation/blocklist.ts b/server/tests/api/moderation/blocklist.ts index 593291e87..8ed5ad9e5 100644 --- a/server/tests/api/moderation/blocklist.ts +++ b/server/tests/api/moderation/blocklist.ts @@ -6,8 +6,8 @@ import { BlocklistCommand, cleanupTests, CommentsCommand, - doubleFollow, createMultipleServers, + doubleFollow, PeerTubeServer, setAccessTokensToServers, waitJobs diff --git a/server/tests/api/notifications/admin-notifications.ts b/server/tests/api/notifications/admin-notifications.ts index d65551f0a..b36ba11a9 100644 --- a/server/tests/api/notifications/admin-notifications.ts +++ b/server/tests/api/notifications/admin-notifications.ts @@ -9,8 +9,8 @@ import { cleanupTests, MockJoinPeerTubeVersions, MockSmtpServer, - prepareNotificationsTest, PeerTubeServer, + prepareNotificationsTest, wait } from '@shared/extra-utils' import { PluginType, UserNotification, UserNotificationType } from '@shared/models' diff --git a/server/tests/api/notifications/comments-notifications.ts b/server/tests/api/notifications/comments-notifications.ts index d54819aaa..cbb46e510 100644 --- a/server/tests/api/notifications/comments-notifications.ts +++ b/server/tests/api/notifications/comments-notifications.ts @@ -8,8 +8,8 @@ import { checkNewCommentOnMyVideo, cleanupTests, MockSmtpServer, - prepareNotificationsTest, PeerTubeServer, + prepareNotificationsTest, waitJobs } from '@shared/extra-utils' import { UserNotification } from '@shared/models' diff --git a/server/tests/api/notifications/moderation-notifications.ts b/server/tests/api/notifications/moderation-notifications.ts index 3a294192b..6e8f8a2b4 100644 --- a/server/tests/api/notifications/moderation-notifications.ts +++ b/server/tests/api/notifications/moderation-notifications.ts @@ -19,8 +19,8 @@ import { cleanupTests, MockInstancesIndex, MockSmtpServer, - prepareNotificationsTest, PeerTubeServer, + prepareNotificationsTest, wait, waitJobs } from '@shared/extra-utils' diff --git a/server/tests/api/notifications/notifications-api.ts b/server/tests/api/notifications/notifications-api.ts index 178b20687..fa4b53db6 100644 --- a/server/tests/api/notifications/notifications-api.ts +++ b/server/tests/api/notifications/notifications-api.ts @@ -8,8 +8,8 @@ import { cleanupTests, getAllNotificationsSettings, MockSmtpServer, - prepareNotificationsTest, PeerTubeServer, + prepareNotificationsTest, waitJobs } from '@shared/extra-utils' import { UserNotification, UserNotificationSettingValue } from '@shared/models' diff --git a/server/tests/api/redundancy/manage-redundancy.ts b/server/tests/api/redundancy/manage-redundancy.ts index aff64e2eb..5fd464ded 100644 --- a/server/tests/api/redundancy/manage-redundancy.ts +++ b/server/tests/api/redundancy/manage-redundancy.ts @@ -4,10 +4,10 @@ import 'mocha' import * as chai from 'chai' import { cleanupTests, - doubleFollow, createMultipleServers, - RedundancyCommand, + doubleFollow, PeerTubeServer, + RedundancyCommand, setAccessTokensToServers, waitJobs } from '@shared/extra-utils' diff --git a/server/tests/api/redundancy/redundancy-constraints.ts b/server/tests/api/redundancy/redundancy-constraints.ts index 71b93901e..25cd11658 100644 --- a/server/tests/api/redundancy/redundancy-constraints.ts +++ b/server/tests/api/redundancy/redundancy-constraints.ts @@ -2,14 +2,7 @@ import 'mocha' import { expect } from 'chai' -import { - cleanupTests, - createSingleServer, - killallServers, - PeerTubeServer, - setAccessTokensToServers, - waitJobs -} from '@shared/extra-utils' +import { cleanupTests, createSingleServer, killallServers, PeerTubeServer, setAccessTokensToServers, waitJobs } from '@shared/extra-utils' import { VideoPrivacy } from '@shared/models' describe('Test redundancy constraints', function () { diff --git a/server/tests/api/redundancy/redundancy.ts b/server/tests/api/redundancy/redundancy.ts index 921a48856..a6559d304 100644 --- a/server/tests/api/redundancy/redundancy.ts +++ b/server/tests/api/redundancy/redundancy.ts @@ -5,22 +5,21 @@ import * as chai from 'chai' import { readdir } from 'fs-extra' import * as magnetUtil from 'magnet-uri' import { join } from 'path' -import { HttpStatusCode } from '@shared/models' import { checkSegmentHash, checkVideoFilesWereRemoved, cleanupTests, - doubleFollow, createMultipleServers, + doubleFollow, killallServers, makeGetRequest, - root, PeerTubeServer, + root, setAccessTokensToServers, wait, waitJobs } from '@shared/extra-utils' -import { VideoPrivacy, VideoRedundancyStrategy, VideoRedundancyStrategyWithManual } from '@shared/models' +import { HttpStatusCode, VideoPrivacy, VideoRedundancyStrategy, VideoRedundancyStrategyWithManual } from '@shared/models' const expect = chai.expect diff --git a/server/tests/api/search/search-activitypub-video-channels.ts b/server/tests/api/search/search-activitypub-video-channels.ts index b33f28266..426cbc8e1 100644 --- a/server/tests/api/search/search-activitypub-video-channels.ts +++ b/server/tests/api/search/search-activitypub-video-channels.ts @@ -5,8 +5,8 @@ import * as chai from 'chai' import { cleanupTests, createMultipleServers, - SearchCommand, PeerTubeServer, + SearchCommand, setAccessTokensToServers, wait, waitJobs diff --git a/server/tests/api/search/search-activitypub-video-playlists.ts b/server/tests/api/search/search-activitypub-video-playlists.ts index ada2d3d6c..33ca7be12 100644 --- a/server/tests/api/search/search-activitypub-video-playlists.ts +++ b/server/tests/api/search/search-activitypub-video-playlists.ts @@ -5,8 +5,8 @@ import * as chai from 'chai' import { cleanupTests, createMultipleServers, - SearchCommand, PeerTubeServer, + SearchCommand, setAccessTokensToServers, setDefaultVideoChannel, wait, diff --git a/server/tests/api/search/search-activitypub-videos.ts b/server/tests/api/search/search-activitypub-videos.ts index a015b72a7..b3cfcacca 100644 --- a/server/tests/api/search/search-activitypub-videos.ts +++ b/server/tests/api/search/search-activitypub-videos.ts @@ -5,8 +5,8 @@ import * as chai from 'chai' import { cleanupTests, createMultipleServers, - SearchCommand, PeerTubeServer, + SearchCommand, setAccessTokensToServers, wait, waitJobs diff --git a/server/tests/api/search/search-channels.ts b/server/tests/api/search/search-channels.ts index 07e00a214..4da2d0ece 100644 --- a/server/tests/api/search/search-channels.ts +++ b/server/tests/api/search/search-channels.ts @@ -2,7 +2,7 @@ import 'mocha' import * as chai from 'chai' -import { cleanupTests, createSingleServer, SearchCommand, PeerTubeServer, setAccessTokensToServers } from '@shared/extra-utils' +import { cleanupTests, createSingleServer, PeerTubeServer, SearchCommand, setAccessTokensToServers } from '@shared/extra-utils' import { VideoChannel } from '@shared/models' const expect = chai.expect diff --git a/server/tests/api/search/search-index.ts b/server/tests/api/search/search-index.ts index 38edcf7c6..feb35411f 100644 --- a/server/tests/api/search/search-index.ts +++ b/server/tests/api/search/search-index.ts @@ -2,7 +2,7 @@ import 'mocha' import * as chai from 'chai' -import { cleanupTests, createSingleServer, SearchCommand, PeerTubeServer, setAccessTokensToServers } from '@shared/extra-utils' +import { cleanupTests, createSingleServer, PeerTubeServer, SearchCommand, setAccessTokensToServers } from '@shared/extra-utils' import { BooleanBothQuery, VideoPlaylistPrivacy, VideoPlaylistType, VideosSearchQuery } from '@shared/models' const expect = chai.expect diff --git a/server/tests/api/search/search-playlists.ts b/server/tests/api/search/search-playlists.ts index b29c2d127..22e9b8fca 100644 --- a/server/tests/api/search/search-playlists.ts +++ b/server/tests/api/search/search-playlists.ts @@ -5,8 +5,8 @@ import * as chai from 'chai' import { cleanupTests, createSingleServer, - SearchCommand, PeerTubeServer, + SearchCommand, setAccessTokensToServers, setDefaultVideoChannel } from '@shared/extra-utils' diff --git a/server/tests/api/search/search-videos.ts b/server/tests/api/search/search-videos.ts index a9b0a4fcd..f834c7f36 100644 --- a/server/tests/api/search/search-videos.ts +++ b/server/tests/api/search/search-videos.ts @@ -5,8 +5,8 @@ import * as chai from 'chai' import { cleanupTests, createSingleServer, - SearchCommand, PeerTubeServer, + SearchCommand, setAccessTokensToServers, setDefaultVideoChannel, stopFfmpeg, diff --git a/server/tests/api/server/bulk.ts b/server/tests/api/server/bulk.ts index 5d8c87983..16cbcd5c3 100644 --- a/server/tests/api/server/bulk.ts +++ b/server/tests/api/server/bulk.ts @@ -5,8 +5,8 @@ import * as chai from 'chai' import { BulkCommand, cleanupTests, - doubleFollow, createMultipleServers, + doubleFollow, PeerTubeServer, setAccessTokensToServers, waitJobs diff --git a/server/tests/api/server/config.ts b/server/tests/api/server/config.ts index a1c2f0f39..fd61e95df 100644 --- a/server/tests/api/server/config.ts +++ b/server/tests/api/server/config.ts @@ -2,7 +2,6 @@ import 'mocha' import * as chai from 'chai' -import { HttpStatusCode } from '@shared/models' import { cleanupTests, createSingleServer, @@ -12,7 +11,7 @@ import { PeerTubeServer, setAccessTokensToServers } from '@shared/extra-utils' -import { CustomConfig } from '@shared/models' +import { CustomConfig, HttpStatusCode } from '@shared/models' const expect = chai.expect diff --git a/server/tests/api/server/contact-form.ts b/server/tests/api/server/contact-form.ts index fc5d0ad6a..c555661ad 100644 --- a/server/tests/api/server/contact-form.ts +++ b/server/tests/api/server/contact-form.ts @@ -2,7 +2,6 @@ import 'mocha' import * as chai from 'chai' -import { HttpStatusCode } from '@shared/models' import { cleanupTests, ContactFormCommand, @@ -13,6 +12,7 @@ import { wait, waitJobs } from '@shared/extra-utils' +import { HttpStatusCode } from '@shared/models' const expect = chai.expect diff --git a/server/tests/api/server/email.ts b/server/tests/api/server/email.ts index 4c5b296ee..ae86b380f 100644 --- a/server/tests/api/server/email.ts +++ b/server/tests/api/server/email.ts @@ -2,8 +2,8 @@ import 'mocha' import * as chai from 'chai' -import { HttpStatusCode } from '@shared/models' import { cleanupTests, createSingleServer, MockSmtpServer, PeerTubeServer, setAccessTokensToServers, waitJobs } from '@shared/extra-utils' +import { HttpStatusCode } from '@shared/models' const expect = chai.expect diff --git a/server/tests/api/server/follow-constraints.ts b/server/tests/api/server/follow-constraints.ts index bd7b215db..471f5d8d0 100644 --- a/server/tests/api/server/follow-constraints.ts +++ b/server/tests/api/server/follow-constraints.ts @@ -2,9 +2,8 @@ import 'mocha' import * as chai from 'chai' -import { HttpStatusCode } from '@shared/models' -import { cleanupTests, doubleFollow, createMultipleServers, PeerTubeServer, setAccessTokensToServers } from '@shared/extra-utils' -import { PeerTubeProblemDocument, ServerErrorCode } from '@shared/models' +import { cleanupTests, createMultipleServers, doubleFollow, PeerTubeServer, setAccessTokensToServers } from '@shared/extra-utils' +import { HttpStatusCode, PeerTubeProblemDocument, ServerErrorCode } from '@shared/models' const expect = chai.expect @@ -157,7 +156,7 @@ describe('Test follow constraints', function () { it('Should list local account videos', async function () { const { total, data } = await servers[0].videos.listByAccount({ - token: undefined, + token: null, handle: 'root@localhost:' + servers[0].port }) @@ -167,7 +166,7 @@ describe('Test follow constraints', function () { it('Should not list remote account videos', async function () { const { total, data } = await servers[0].videos.listByAccount({ - token: undefined, + token: null, handle: 'root@localhost:' + servers[1].port }) @@ -177,7 +176,7 @@ describe('Test follow constraints', function () { it('Should list local channel videos', async function () { const handle = 'root_channel@localhost:' + servers[0].port - const { total, data } = await servers[0].videos.listByChannel({ token: undefined, handle }) + const { total, data } = await servers[0].videos.listByChannel({ token: null, handle }) expect(total).to.equal(1) expect(data).to.have.lengthOf(1) @@ -185,7 +184,7 @@ describe('Test follow constraints', function () { it('Should not list remote channel videos', async function () { const handle = 'root_channel@localhost:' + servers[1].port - const { total, data } = await servers[0].videos.listByChannel({ token: undefined, handle }) + const { total, data } = await servers[0].videos.listByChannel({ token: null, handle }) expect(total).to.equal(0) expect(data).to.have.lengthOf(0) diff --git a/server/tests/api/server/follows.ts b/server/tests/api/server/follows.ts index 8856177b8..ff8f880a6 100644 --- a/server/tests/api/server/follows.ts +++ b/server/tests/api/server/follows.ts @@ -5,9 +5,9 @@ import * as chai from 'chai' import { cleanupTests, completeVideoCheck, + createMultipleServers, dateIsValid, expectAccountFollows, - createMultipleServers, FollowsCommand, PeerTubeServer, setAccessTokensToServers, diff --git a/server/tests/api/server/handle-down.ts b/server/tests/api/server/handle-down.ts index d22e843e0..1f751c957 100644 --- a/server/tests/api/server/handle-down.ts +++ b/server/tests/api/server/handle-down.ts @@ -2,7 +2,6 @@ import 'mocha' import * as chai from 'chai' -import { HttpStatusCode } from '@shared/models' import { cleanupTests, CommentsCommand, @@ -14,7 +13,7 @@ import { wait, waitJobs } from '@shared/extra-utils' -import { JobState, VideoCreateResult, VideoPrivacy } from '@shared/models' +import { HttpStatusCode, JobState, VideoCreateResult, VideoPrivacy } from '@shared/models' const expect = chai.expect diff --git a/server/tests/api/server/homepage.ts b/server/tests/api/server/homepage.ts index 7eae3df20..cb3ba5677 100644 --- a/server/tests/api/server/homepage.ts +++ b/server/tests/api/server/homepage.ts @@ -5,8 +5,8 @@ import * as chai from 'chai' import { HttpStatusCode } from '@shared/models' import { cleanupTests, - CustomPagesCommand, createSingleServer, + CustomPagesCommand, killallServers, PeerTubeServer, setAccessTokensToServers diff --git a/server/tests/api/server/jobs.ts b/server/tests/api/server/jobs.ts index 376cd10d0..c10c154c2 100644 --- a/server/tests/api/server/jobs.ts +++ b/server/tests/api/server/jobs.ts @@ -4,9 +4,9 @@ import 'mocha' import * as chai from 'chai' import { cleanupTests, + createMultipleServers, dateIsValid, doubleFollow, - createMultipleServers, PeerTubeServer, setAccessTokensToServers, waitJobs diff --git a/server/tests/api/server/plugins.ts b/server/tests/api/server/plugins.ts index 334adfe9d..5f9f4ffdd 100644 --- a/server/tests/api/server/plugins.ts +++ b/server/tests/api/server/plugins.ts @@ -2,18 +2,17 @@ import 'mocha' import * as chai from 'chai' -import { HttpStatusCode } from '@shared/models' import { cleanupTests, createSingleServer, killallServers, - PluginsCommand, PeerTubeServer, + PluginsCommand, setAccessTokensToServers, testHelloWorldRegisteredSettings, wait } from '@shared/extra-utils' -import { PluginType } from '@shared/models' +import { HttpStatusCode, PluginType } from '@shared/models' const expect = chai.expect diff --git a/server/tests/api/server/reverse-proxy.ts b/server/tests/api/server/reverse-proxy.ts index 13b22bc0e..484f88d67 100644 --- a/server/tests/api/server/reverse-proxy.ts +++ b/server/tests/api/server/reverse-proxy.ts @@ -1,8 +1,8 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ import { expect } from 'chai' -import { HttpStatusCode } from '@shared/models' import { cleanupTests, createSingleServer, PeerTubeServer, setAccessTokensToServers, wait } from '@shared/extra-utils' +import { HttpStatusCode } from '@shared/models' describe('Test application behind a reverse proxy', function () { let server: PeerTubeServer diff --git a/server/tests/api/server/stats.ts b/server/tests/api/server/stats.ts index f07d0fd39..942602b70 100644 --- a/server/tests/api/server/stats.ts +++ b/server/tests/api/server/stats.ts @@ -4,8 +4,8 @@ import 'mocha' import * as chai from 'chai' import { cleanupTests, - doubleFollow, createMultipleServers, + doubleFollow, PeerTubeServer, setAccessTokensToServers, wait, diff --git a/server/tests/api/users/user-subscriptions.ts b/server/tests/api/users/user-subscriptions.ts index d2bb9c387..565b4bd77 100644 --- a/server/tests/api/users/user-subscriptions.ts +++ b/server/tests/api/users/user-subscriptions.ts @@ -4,8 +4,8 @@ import 'mocha' import * as chai from 'chai' import { cleanupTests, - doubleFollow, createMultipleServers, + doubleFollow, PeerTubeServer, setAccessTokensToServers, SubscriptionsCommand, @@ -67,7 +67,8 @@ describe('Test users subscriptions', function () { await waitJobs(servers) - const { uuid } = await servers[2].videos.upload({ attributes: { name: 'video server 3 added after follow' } }) + const attributes = { name: 'video server 3 added after follow' } + const { uuid } = await servers[2].videos.upload({ token: users[2].accessToken, attributes }) video3UUID = uuid await waitJobs(servers) diff --git a/server/tests/api/users/users-multiple-servers.ts b/server/tests/api/users/users-multiple-servers.ts index e304e5d67..225145957 100644 --- a/server/tests/api/users/users-multiple-servers.ts +++ b/server/tests/api/users/users-multiple-servers.ts @@ -7,8 +7,8 @@ import { checkTmpIsEmpty, checkVideoFilesWereRemoved, cleanupTests, - doubleFollow, createMultipleServers, + doubleFollow, PeerTubeServer, setAccessTokensToServers, testImage, diff --git a/server/tests/api/users/users-verification.ts b/server/tests/api/users/users-verification.ts index 56fc25048..f54463359 100644 --- a/server/tests/api/users/users-verification.ts +++ b/server/tests/api/users/users-verification.ts @@ -2,8 +2,8 @@ import 'mocha' import * as chai from 'chai' -import { HttpStatusCode } from '@shared/models' import { cleanupTests, createSingleServer, MockSmtpServer, PeerTubeServer, setAccessTokensToServers, waitJobs } from '@shared/extra-utils' +import { HttpStatusCode } from '@shared/models' const expect = chai.expect diff --git a/server/tests/api/users/users.ts b/server/tests/api/users/users.ts index be80c2616..066da88ee 100644 --- a/server/tests/api/users/users.ts +++ b/server/tests/api/users/users.ts @@ -2,7 +2,6 @@ import 'mocha' import * as chai from 'chai' -import { HttpStatusCode } from '@shared/models' import { cleanupTests, createSingleServer, @@ -13,7 +12,7 @@ import { testImage, waitJobs } from '@shared/extra-utils' -import { AbuseState, OAuth2ErrorCode, UserAdminFlag, UserRole, Video, VideoPlaylistType } from '@shared/models' +import { AbuseState, HttpStatusCode, OAuth2ErrorCode, UserAdminFlag, UserRole, Video, VideoPlaylistType } from '@shared/models' const expect = chai.expect diff --git a/server/tests/api/videos/audio-only.ts b/server/tests/api/videos/audio-only.ts index b9bf96650..15c3ae6d6 100644 --- a/server/tests/api/videos/audio-only.ts +++ b/server/tests/api/videos/audio-only.ts @@ -4,7 +4,7 @@ import 'mocha' import * as chai from 'chai' import { join } from 'path' import { getAudioStream, getVideoStreamSize } from '@server/helpers/ffprobe-utils' -import { cleanupTests, doubleFollow, createMultipleServers, PeerTubeServer, setAccessTokensToServers, waitJobs } from '@shared/extra-utils' +import { cleanupTests, createMultipleServers, doubleFollow, PeerTubeServer, setAccessTokensToServers, waitJobs } from '@shared/extra-utils' const expect = chai.expect diff --git a/server/tests/api/videos/multiple-servers.ts b/server/tests/api/videos/multiple-servers.ts index edf2773cd..d916abb09 100644 --- a/server/tests/api/videos/multiple-servers.ts +++ b/server/tests/api/videos/multiple-servers.ts @@ -3,16 +3,15 @@ import 'mocha' import * as chai from 'chai' import * as request from 'supertest' -import { HttpStatusCode } from '@shared/models' import { buildAbsoluteFixturePath, checkTmpIsEmpty, checkVideoFilesWereRemoved, cleanupTests, completeVideoCheck, + createMultipleServers, dateIsValid, doubleFollow, - createMultipleServers, PeerTubeServer, setAccessTokensToServers, testImage, @@ -20,7 +19,7 @@ import { waitJobs, webtorrentAdd } from '@shared/extra-utils' -import { VideoCommentThreadTree, VideoPrivacy } from '@shared/models' +import { HttpStatusCode, VideoCommentThreadTree, VideoPrivacy } from '@shared/models' const expect = chai.expect diff --git a/server/tests/api/videos/resumable-upload.ts b/server/tests/api/videos/resumable-upload.ts index 0e62972c2..13e47c85e 100644 --- a/server/tests/api/videos/resumable-upload.ts +++ b/server/tests/api/videos/resumable-upload.ts @@ -4,7 +4,6 @@ import 'mocha' import * as chai from 'chai' import { pathExists, readdir, stat } from 'fs-extra' import { join } from 'path' -import { HttpStatusCode } from '@shared/models' import { buildAbsoluteFixturePath, cleanupTests, @@ -13,7 +12,7 @@ import { setAccessTokensToServers, setDefaultVideoChannel } from '@shared/extra-utils' -import { VideoPrivacy } from '@shared/models' +import { HttpStatusCode, VideoPrivacy } from '@shared/models' const expect = chai.expect diff --git a/server/tests/api/videos/video-captions.ts b/server/tests/api/videos/video-captions.ts index 6caba6aa6..e3d46e619 100644 --- a/server/tests/api/videos/video-captions.ts +++ b/server/tests/api/videos/video-captions.ts @@ -5,8 +5,8 @@ import * as chai from 'chai' import { checkVideoFilesWereRemoved, cleanupTests, - doubleFollow, createMultipleServers, + doubleFollow, PeerTubeServer, setAccessTokensToServers, testCaptionFile, diff --git a/server/tests/api/videos/video-change-ownership.ts b/server/tests/api/videos/video-change-ownership.ts index 792550101..6ae6d3004 100644 --- a/server/tests/api/videos/video-change-ownership.ts +++ b/server/tests/api/videos/video-change-ownership.ts @@ -2,19 +2,18 @@ import 'mocha' import * as chai from 'chai' -import { HttpStatusCode } from '@shared/models' import { ChangeOwnershipCommand, cleanupTests, - doubleFollow, createMultipleServers, createSingleServer, + doubleFollow, PeerTubeServer, setAccessTokensToServers, setDefaultVideoChannel, waitJobs } from '@shared/extra-utils' -import { VideoPrivacy } from '@shared/models' +import { HttpStatusCode, VideoPrivacy } from '@shared/models' const expect = chai.expect diff --git a/server/tests/api/videos/video-channels.ts b/server/tests/api/videos/video-channels.ts index eeaec5ad2..c25754eb6 100644 --- a/server/tests/api/videos/video-channels.ts +++ b/server/tests/api/videos/video-channels.ts @@ -6,8 +6,8 @@ import { basename } from 'path' import { ACTOR_IMAGES_SIZE } from '@server/initializers/constants' import { cleanupTests, - doubleFollow, createMultipleServers, + doubleFollow, PeerTubeServer, setAccessTokensToServers, setDefaultVideoChannel, diff --git a/server/tests/api/videos/video-comments.ts b/server/tests/api/videos/video-comments.ts index 9709e0628..61ee54540 100644 --- a/server/tests/api/videos/video-comments.ts +++ b/server/tests/api/videos/video-comments.ts @@ -5,8 +5,8 @@ import * as chai from 'chai' import { cleanupTests, CommentsCommand, - dateIsValid, createSingleServer, + dateIsValid, PeerTubeServer, setAccessTokensToServers, testImage diff --git a/server/tests/api/videos/video-description.ts b/server/tests/api/videos/video-description.ts index ce45eac80..d22b4ed96 100644 --- a/server/tests/api/videos/video-description.ts +++ b/server/tests/api/videos/video-description.ts @@ -2,7 +2,7 @@ import 'mocha' import * as chai from 'chai' -import { cleanupTests, doubleFollow, createMultipleServers, PeerTubeServer, setAccessTokensToServers, waitJobs } from '@shared/extra-utils' +import { cleanupTests, createMultipleServers, doubleFollow, PeerTubeServer, setAccessTokensToServers, waitJobs } from '@shared/extra-utils' const expect = chai.expect diff --git a/server/tests/api/videos/video-hls.ts b/server/tests/api/videos/video-hls.ts index df030110b..7845f7334 100644 --- a/server/tests/api/videos/video-hls.ts +++ b/server/tests/api/videos/video-hls.ts @@ -3,22 +3,21 @@ import 'mocha' import * as chai from 'chai' import { join } from 'path' -import { HttpStatusCode } from '@shared/models' import { checkDirectoryIsEmpty, checkResolutionsInMasterPlaylist, checkSegmentHash, checkTmpIsEmpty, cleanupTests, - doubleFollow, createMultipleServers, + doubleFollow, makeRawRequest, PeerTubeServer, setAccessTokensToServers, waitJobs, webtorrentAdd } from '@shared/extra-utils' -import { VideoStreamingPlaylistType } from '@shared/models' +import { HttpStatusCode, VideoStreamingPlaylistType } from '@shared/models' import { DEFAULT_AUDIO_RESOLUTION } from '../../../initializers/constants' const expect = chai.expect diff --git a/server/tests/api/videos/video-nsfw.ts b/server/tests/api/videos/video-nsfw.ts index 0a9e5ce3f..b5d183d62 100644 --- a/server/tests/api/videos/video-nsfw.ts +++ b/server/tests/api/videos/video-nsfw.ts @@ -30,8 +30,8 @@ describe('Test video NSFW policy', function () { promises = [ server.search.advancedVideoSearch({ token, search: { search: 'n', sort: '-publishedAt', ...query } }), server.videos.listWithToken({ token, ...query }), - server.videos.listByAccount({ token, handle: channelName, ...query }), - server.videos.listByChannel({ token, handle: accountName, ...query }) + server.videos.listByAccount({ token, handle: accountName, ...query }), + server.videos.listByChannel({ token, handle: channelName, ...query }) ] // Overviews do not support video filters @@ -47,8 +47,8 @@ describe('Test video NSFW policy', function () { promises = [ server.search.searchVideos({ search: 'n', sort: '-publishedAt' }), server.videos.list(), - server.videos.listByAccount({ handle: channelName }), - server.videos.listByChannel({ handle: accountName }) + server.videos.listByAccount({ token: null, handle: accountName }), + server.videos.listByChannel({ token: null, handle: channelName }) ] // Overviews do not support video filters @@ -82,6 +82,7 @@ describe('Test video NSFW policy', function () { }) describe('Instance default NSFW policy', function () { + it('Should display NSFW videos with display default NSFW policy', async function () { const serverConfig = await server.config.getConfig() expect(serverConfig.instance.defaultNSFWPolicy).to.equal('display') diff --git a/server/tests/api/videos/video-playlist-thumbnails.ts b/server/tests/api/videos/video-playlist-thumbnails.ts index 9a682c12b..f0b2ca169 100644 --- a/server/tests/api/videos/video-playlist-thumbnails.ts +++ b/server/tests/api/videos/video-playlist-thumbnails.ts @@ -4,8 +4,8 @@ import 'mocha' import * as chai from 'chai' import { cleanupTests, - doubleFollow, createMultipleServers, + doubleFollow, PeerTubeServer, setAccessTokensToServers, setDefaultVideoChannel, diff --git a/server/tests/api/videos/video-playlists.ts b/server/tests/api/videos/video-playlists.ts index 9a28a421a..f42aee2ff 100644 --- a/server/tests/api/videos/video-playlists.ts +++ b/server/tests/api/videos/video-playlists.ts @@ -2,14 +2,13 @@ import 'mocha' import * as chai from 'chai' -import { HttpStatusCode } from '@shared/models' import { checkPlaylistFilesWereRemoved, cleanupTests, - doubleFollow, createMultipleServers, - PlaylistsCommand, + doubleFollow, PeerTubeServer, + PlaylistsCommand, setAccessTokensToServers, setDefaultVideoChannel, testImage, @@ -17,6 +16,7 @@ import { waitJobs } from '@shared/extra-utils' import { + HttpStatusCode, VideoPlaylist, VideoPlaylistCreateResult, VideoPlaylistElementType, diff --git a/server/tests/api/videos/video-privacy.ts b/server/tests/api/videos/video-privacy.ts index 06011082d..b51b3bcdd 100644 --- a/server/tests/api/videos/video-privacy.ts +++ b/server/tests/api/videos/video-privacy.ts @@ -2,9 +2,8 @@ import 'mocha' import * as chai from 'chai' -import { HttpStatusCode } from '@shared/models' -import { cleanupTests, doubleFollow, createSingleServer, PeerTubeServer, setAccessTokensToServers, waitJobs } from '@shared/extra-utils' -import { VideoCreateResult, VideoPrivacy } from '@shared/models' +import { cleanupTests, createSingleServer, doubleFollow, PeerTubeServer, setAccessTokensToServers, waitJobs } from '@shared/extra-utils' +import { HttpStatusCode, VideoCreateResult, VideoPrivacy } from '@shared/models' const expect = chai.expect @@ -162,7 +161,7 @@ describe('Test video privacy', function () { }) it('Should not be able to get this unlisted video using its id', async function () { - await servers[1].videos.get({ id: unlistedVideo.id, expectedStatus: HttpStatusCode.BAD_REQUEST_400 }) + await servers[1].videos.get({ id: unlistedVideo.id, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) }) it('Should be able to get this unlisted video using its uuid/shortUUID', async function () { diff --git a/server/tests/api/videos/video-schedule-update.ts b/server/tests/api/videos/video-schedule-update.ts index 22b5cf1c2..3f7738784 100644 --- a/server/tests/api/videos/video-schedule-update.ts +++ b/server/tests/api/videos/video-schedule-update.ts @@ -4,8 +4,8 @@ import 'mocha' import * as chai from 'chai' import { cleanupTests, - doubleFollow, createMultipleServers, + doubleFollow, PeerTubeServer, setAccessTokensToServers, wait, diff --git a/server/tests/api/videos/video-transcoder.ts b/server/tests/api/videos/video-transcoder.ts index 7510472e3..e4892bb24 100644 --- a/server/tests/api/videos/video-transcoder.ts +++ b/server/tests/api/videos/video-transcoder.ts @@ -4,12 +4,11 @@ import 'mocha' import * as chai from 'chai' import { omit } from 'lodash' import { join } from 'path' -import { HttpStatusCode } from '@shared/models' import { buildAbsoluteFixturePath, cleanupTests, - doubleFollow, createMultipleServers, + doubleFollow, generateHighBitrateVideo, generateVideoWithFramerate, makeGetRequest, @@ -18,7 +17,7 @@ import { waitJobs, webtorrentAdd } from '@shared/extra-utils' -import { getMaxBitrate, VideoResolution, VideoState } from '@shared/models' +import { getMaxBitrate, HttpStatusCode, VideoResolution, VideoState } from '@shared/models' import { VIDEO_TRANSCODING_FPS } from '../../../../server/initializers/constants' import { canDoQuickTranscode, diff --git a/server/tests/api/videos/videos-filter.ts b/server/tests/api/videos/videos-filter.ts index 88dff3e7f..2306807bf 100644 --- a/server/tests/api/videos/videos-filter.ts +++ b/server/tests/api/videos/videos-filter.ts @@ -2,16 +2,15 @@ import 'mocha' import { expect } from 'chai' -import { HttpStatusCode } from '@shared/models' import { cleanupTests, - doubleFollow, createMultipleServers, + doubleFollow, makeGetRequest, PeerTubeServer, setAccessTokensToServers } from '@shared/extra-utils' -import { UserRole, Video, VideoPrivacy } from '@shared/models' +import { HttpStatusCode, UserRole, Video, VideoPrivacy } from '@shared/models' async function getVideosNames (server: PeerTubeServer, token: string, filter: string, expectedStatus = HttpStatusCode.OK_200) { const paths = [ diff --git a/server/tests/api/videos/videos-history.ts b/server/tests/api/videos/videos-history.ts index acb9d1a46..e4bc0bb3a 100644 --- a/server/tests/api/videos/videos-history.ts +++ b/server/tests/api/videos/videos-history.ts @@ -2,7 +2,6 @@ import 'mocha' import * as chai from 'chai' -import { HttpStatusCode } from '@shared/models' import { cleanupTests, createSingleServer, @@ -12,7 +11,7 @@ import { setAccessTokensToServers, wait } from '@shared/extra-utils' -import { Video } from '@shared/models' +import { HttpStatusCode, Video } from '@shared/models' const expect = chai.expect diff --git a/server/tests/api/videos/videos-views-cleaner.ts b/server/tests/api/videos/videos-views-cleaner.ts index 0be03ddd2..82268b1be 100644 --- a/server/tests/api/videos/videos-views-cleaner.ts +++ b/server/tests/api/videos/videos-views-cleaner.ts @@ -4,8 +4,8 @@ import 'mocha' import * as chai from 'chai' import { cleanupTests, - doubleFollow, createMultipleServers, + doubleFollow, killallServers, PeerTubeServer, setAccessTokensToServers, diff --git a/server/tests/cli/create-import-video-file-job.ts b/server/tests/cli/create-import-video-file-job.ts index e8cd71e09..bddcff5e7 100644 --- a/server/tests/cli/create-import-video-file-job.ts +++ b/server/tests/cli/create-import-video-file-job.ts @@ -2,7 +2,7 @@ import 'mocha' import * as chai from 'chai' -import { cleanupTests, doubleFollow, createMultipleServers, PeerTubeServer, setAccessTokensToServers, waitJobs } from '@shared/extra-utils' +import { cleanupTests, createMultipleServers, doubleFollow, PeerTubeServer, setAccessTokensToServers, waitJobs } from '@shared/extra-utils' import { VideoFile } from '@shared/models' const expect = chai.expect diff --git a/server/tests/cli/create-transcoding-job.ts b/server/tests/cli/create-transcoding-job.ts index 53f187f90..df787ccdc 100644 --- a/server/tests/cli/create-transcoding-job.ts +++ b/server/tests/cli/create-transcoding-job.ts @@ -4,8 +4,8 @@ import 'mocha' import * as chai from 'chai' import { cleanupTests, - doubleFollow, createMultipleServers, + doubleFollow, PeerTubeServer, setAccessTokensToServers, waitJobs diff --git a/server/tests/cli/optimize-old-videos.ts b/server/tests/cli/optimize-old-videos.ts index 53f47a85e..685b3b7b8 100644 --- a/server/tests/cli/optimize-old-videos.ts +++ b/server/tests/cli/optimize-old-videos.ts @@ -5,8 +5,8 @@ import * as chai from 'chai' import { join } from 'path' import { cleanupTests, - doubleFollow, createMultipleServers, + doubleFollow, generateHighBitrateVideo, PeerTubeServer, setAccessTokensToServers, diff --git a/server/tests/cli/plugins.ts b/server/tests/cli/plugins.ts index 42651d79c..07c78cc89 100644 --- a/server/tests/cli/plugins.ts +++ b/server/tests/cli/plugins.ts @@ -6,8 +6,8 @@ import { cleanupTests, createSingleServer, killallServers, - PluginsCommand, PeerTubeServer, + PluginsCommand, setAccessTokensToServers } from '../../../shared/extra-utils' diff --git a/server/tests/cli/prune-storage.ts b/server/tests/cli/prune-storage.ts index 2bd4a466b..954a87833 100644 --- a/server/tests/cli/prune-storage.ts +++ b/server/tests/cli/prune-storage.ts @@ -5,12 +5,11 @@ import * as chai from 'chai' import { createFile, readdir } from 'fs-extra' import { join } from 'path' import { buildUUID } from '@server/helpers/uuid' -import { HttpStatusCode } from '@shared/models' import { cleanupTests, CLICommand, - doubleFollow, createMultipleServers, + doubleFollow, killallServers, makeGetRequest, PeerTubeServer, @@ -19,7 +18,7 @@ import { wait, waitJobs } from '@shared/extra-utils' -import { VideoPlaylistPrivacy } from '@shared/models' +import { HttpStatusCode, VideoPlaylistPrivacy } from '@shared/models' const expect = chai.expect diff --git a/server/tests/cli/regenerate-thumbnails.ts b/server/tests/cli/regenerate-thumbnails.ts index 595d842ef..780c9b4bd 100644 --- a/server/tests/cli/regenerate-thumbnails.ts +++ b/server/tests/cli/regenerate-thumbnails.ts @@ -2,12 +2,11 @@ import 'mocha' import { expect } from 'chai' import { writeFile } from 'fs-extra' import { basename, join } from 'path' -import { HttpStatusCode } from '@shared/models' -import { Video } from '@shared/models' +import { HttpStatusCode, Video } from '@shared/models' import { cleanupTests, - doubleFollow, createMultipleServers, + doubleFollow, makeRawRequest, PeerTubeServer, setAccessTokensToServers, diff --git a/server/tests/client.ts b/server/tests/client.ts index 6255c6961..9c27a7aae 100644 --- a/server/tests/client.ts +++ b/server/tests/client.ts @@ -3,12 +3,11 @@ import 'mocha' import * as chai from 'chai' import { omit } from 'lodash' -import { HttpStatusCode } from '@shared/models' -import { Account, HTMLServerConfig, ServerConfig, VideoPlaylistCreateResult, VideoPlaylistPrivacy } from '@shared/models' +import { Account, HTMLServerConfig, HttpStatusCode, ServerConfig, VideoPlaylistCreateResult, VideoPlaylistPrivacy } from '@shared/models' import { cleanupTests, - doubleFollow, createMultipleServers, + doubleFollow, makeGetRequest, makeHTMLRequest, PeerTubeServer, diff --git a/server/tests/external-plugins/auth-ldap.ts b/server/tests/external-plugins/auth-ldap.ts index 12b4a1b8d..acec69df5 100644 --- a/server/tests/external-plugins/auth-ldap.ts +++ b/server/tests/external-plugins/auth-ldap.ts @@ -2,8 +2,8 @@ import 'mocha' import { expect } from 'chai' -import { HttpStatusCode } from '@shared/models' import { cleanupTests, createSingleServer, PeerTubeServer, setAccessTokensToServers } from '@shared/extra-utils' +import { HttpStatusCode } from '@shared/models' describe('Official plugin auth-ldap', function () { let server: PeerTubeServer diff --git a/server/tests/external-plugins/auto-block-videos.ts b/server/tests/external-plugins/auto-block-videos.ts index 78b13eded..0eb4bda9a 100644 --- a/server/tests/external-plugins/auto-block-videos.ts +++ b/server/tests/external-plugins/auto-block-videos.ts @@ -4,8 +4,8 @@ import 'mocha' import { expect } from 'chai' import { cleanupTests, - doubleFollow, createMultipleServers, + doubleFollow, killallServers, MockBlocklist, PeerTubeServer, diff --git a/server/tests/external-plugins/auto-mute.ts b/server/tests/external-plugins/auto-mute.ts index b2046313b..271779dd4 100644 --- a/server/tests/external-plugins/auto-mute.ts +++ b/server/tests/external-plugins/auto-mute.ts @@ -2,11 +2,10 @@ import 'mocha' import { expect } from 'chai' -import { HttpStatusCode } from '@shared/models' import { cleanupTests, - doubleFollow, createMultipleServers, + doubleFollow, killallServers, makeGetRequest, MockBlocklist, @@ -14,6 +13,7 @@ import { setAccessTokensToServers, wait } from '@shared/extra-utils' +import { HttpStatusCode } from '@shared/models' describe('Official plugin auto-mute', function () { const autoMuteListPath = '/plugins/auto-mute/router/api/v1/mute-list' diff --git a/server/tests/feeds/feeds.ts b/server/tests/feeds/feeds.ts index 543c431dd..5667207c0 100644 --- a/server/tests/feeds/feeds.ts +++ b/server/tests/feeds/feeds.ts @@ -3,17 +3,16 @@ import 'mocha' import * as chai from 'chai' import * as xmlParser from 'fast-xml-parser' -import { HttpStatusCode } from '@shared/models' import { cleanupTests, - doubleFollow, createMultipleServers, createSingleServer, + doubleFollow, PeerTubeServer, setAccessTokensToServers, waitJobs } from '@shared/extra-utils' -import { VideoPrivacy } from '@shared/models' +import { HttpStatusCode, VideoPrivacy } from '@shared/models' chai.use(require('chai-xml')) chai.use(require('chai-json-schema')) diff --git a/server/tests/helpers/comment-model.ts b/server/tests/helpers/comment-model.ts index 4c51b7000..31dc6ec72 100644 --- a/server/tests/helpers/comment-model.ts +++ b/server/tests/helpers/comment-model.ts @@ -1,7 +1,7 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ -import * as chai from 'chai' import 'mocha' +import * as chai from 'chai' import { VideoCommentModel } from '../../models/video/video-comment' const expect = chai.expect diff --git a/server/tests/helpers/core-utils.ts b/server/tests/helpers/core-utils.ts index c028b316d..d5cac51a3 100644 --- a/server/tests/helpers/core-utils.ts +++ b/server/tests/helpers/core-utils.ts @@ -1,10 +1,10 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ -import * as chai from 'chai' import 'mocha' +import * as chai from 'chai' import { snakeCase } from 'lodash' -import { objectConverter, parseBytes } from '../../helpers/core-utils' import validator from 'validator' +import { objectConverter, parseBytes } from '../../helpers/core-utils' const expect = chai.expect diff --git a/server/tests/helpers/image.ts b/server/tests/helpers/image.ts index 54911697f..9fe9aa4cb 100644 --- a/server/tests/helpers/image.ts +++ b/server/tests/helpers/image.ts @@ -1,11 +1,11 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ import 'mocha' +import { expect } from 'chai' import { readFile, remove } from 'fs-extra' import { join } from 'path' import { processImage } from '../../../server/helpers/image-utils' import { buildAbsoluteFixturePath, root } from '../../../shared/extra-utils' -import { expect } from 'chai' async function checkBuffers (path1: string, path2: string, equals: boolean) { const [ buf1, buf2 ] = await Promise.all([ diff --git a/server/tests/misc-endpoints.ts b/server/tests/misc-endpoints.ts index 4d9c07f1a..4968eef08 100644 --- a/server/tests/misc-endpoints.ts +++ b/server/tests/misc-endpoints.ts @@ -2,9 +2,8 @@ import 'mocha' import * as chai from 'chai' -import { HttpStatusCode } from '@shared/models' import { cleanupTests, createSingleServer, makeGetRequest, PeerTubeServer, setAccessTokensToServers } from '@shared/extra-utils' -import { VideoPrivacy } from '@shared/models' +import { HttpStatusCode, VideoPrivacy } from '@shared/models' const expect = chai.expect diff --git a/server/tests/plugins/action-hooks.ts b/server/tests/plugins/action-hooks.ts index b96de4e90..4c1bc7d06 100644 --- a/server/tests/plugins/action-hooks.ts +++ b/server/tests/plugins/action-hooks.ts @@ -120,7 +120,7 @@ describe('Test plugin action hooks', function () { }) it('Should run action:api.user.oauth2-got-token', async function () { - await servers[0].login.getAccessToken('created_user', 'super_password') + await servers[0].login.login({ user: { username: 'created_user' } }) await checkHook('action:api.user.oauth2-got-token') }) diff --git a/server/tests/plugins/external-auth.ts b/server/tests/plugins/external-auth.ts index a2828603a..f3e018d43 100644 --- a/server/tests/plugins/external-auth.ts +++ b/server/tests/plugins/external-auth.ts @@ -2,17 +2,16 @@ import 'mocha' import { expect } from 'chai' -import { HttpStatusCode } from '@shared/models' import { cleanupTests, - decodeQueryString, createSingleServer, - PluginsCommand, + decodeQueryString, PeerTubeServer, + PluginsCommand, setAccessTokensToServers, wait } from '@shared/extra-utils' -import { UserRole } from '@shared/models' +import { HttpStatusCode, UserRole } from '@shared/models' async function loginExternal (options: { server: PeerTubeServer diff --git a/server/tests/plugins/filter-hooks.ts b/server/tests/plugins/filter-hooks.ts index ba84dd27a..c00ac8f91 100644 --- a/server/tests/plugins/filter-hooks.ts +++ b/server/tests/plugins/filter-hooks.ts @@ -2,7 +2,6 @@ import 'mocha' import * as chai from 'chai' -import { HttpStatusCode } from '@shared/models' import { cleanupTests, createMultipleServers, @@ -15,7 +14,7 @@ import { setDefaultVideoChannel, waitJobs } from '@shared/extra-utils' -import { VideoDetails, VideoImportState, VideoPlaylist, VideoPlaylistPrivacy, VideoPrivacy } from '@shared/models' +import { HttpStatusCode, VideoDetails, VideoImportState, VideoPlaylist, VideoPlaylistPrivacy, VideoPrivacy } from '@shared/models' const expect = chai.expect diff --git a/server/tests/plugins/html-injection.ts b/server/tests/plugins/html-injection.ts index 2902c39b7..95c0cd687 100644 --- a/server/tests/plugins/html-injection.ts +++ b/server/tests/plugins/html-injection.ts @@ -6,8 +6,8 @@ import { cleanupTests, createSingleServer, makeHTMLRequest, - PluginsCommand, PeerTubeServer, + PluginsCommand, setAccessTokensToServers } from '../../../shared/extra-utils' diff --git a/server/tests/plugins/id-and-pass-auth.ts b/server/tests/plugins/id-and-pass-auth.ts index a73d76caa..fde0166f9 100644 --- a/server/tests/plugins/id-and-pass-auth.ts +++ b/server/tests/plugins/id-and-pass-auth.ts @@ -2,9 +2,8 @@ import 'mocha' import { expect } from 'chai' -import { HttpStatusCode } from '@shared/models' -import { cleanupTests, createSingleServer, PluginsCommand, PeerTubeServer, setAccessTokensToServers, wait } from '@shared/extra-utils' -import { UserRole } from '@shared/models' +import { cleanupTests, createSingleServer, PeerTubeServer, PluginsCommand, setAccessTokensToServers, wait } from '@shared/extra-utils' +import { HttpStatusCode, UserRole } from '@shared/models' describe('Test id and pass auth plugins', function () { let server: PeerTubeServer diff --git a/server/tests/plugins/plugin-helpers.ts b/server/tests/plugins/plugin-helpers.ts index 5cb664bda..242994273 100644 --- a/server/tests/plugins/plugin-helpers.ts +++ b/server/tests/plugins/plugin-helpers.ts @@ -2,19 +2,19 @@ import 'mocha' import { expect } from 'chai' -import { HttpStatusCode } from '@shared/models' import { checkVideoFilesWereRemoved, cleanupTests, - doubleFollow, createMultipleServers, + doubleFollow, makeGetRequest, makePostBodyRequest, - PluginsCommand, PeerTubeServer, + PluginsCommand, setAccessTokensToServers, waitJobs } from '@shared/extra-utils' +import { HttpStatusCode } from '@shared/models' function postCommand (server: PeerTubeServer, command: string, bodyArg?: object) { const body = { command } diff --git a/server/tests/plugins/plugin-router.ts b/server/tests/plugins/plugin-router.ts index becb7c47b..b1ac9e2fe 100644 --- a/server/tests/plugins/plugin-router.ts +++ b/server/tests/plugins/plugin-router.ts @@ -2,16 +2,16 @@ import 'mocha' import { expect } from 'chai' -import { HttpStatusCode } from '@shared/models' import { cleanupTests, createSingleServer, makeGetRequest, makePostBodyRequest, - PluginsCommand, PeerTubeServer, + PluginsCommand, setAccessTokensToServers } from '@shared/extra-utils' +import { HttpStatusCode } from '@shared/models' describe('Test plugin helpers', function () { let server: PeerTubeServer diff --git a/server/tests/plugins/plugin-storage.ts b/server/tests/plugins/plugin-storage.ts index 90dafa3e1..e20c36dba 100644 --- a/server/tests/plugins/plugin-storage.ts +++ b/server/tests/plugins/plugin-storage.ts @@ -4,7 +4,6 @@ import 'mocha' import { expect } from 'chai' import { pathExists, readdir, readFile } from 'fs-extra' import { join } from 'path' -import { HttpStatusCode } from '@shared/models' import { cleanupTests, createSingleServer, @@ -13,6 +12,7 @@ import { PluginsCommand, setAccessTokensToServers } from '@shared/extra-utils' +import { HttpStatusCode } from '@shared/models' describe('Test plugin storage', function () { let server: PeerTubeServer diff --git a/server/tests/plugins/plugin-transcoding.ts b/server/tests/plugins/plugin-transcoding.ts index 3c54d3796..0bf1fab01 100644 --- a/server/tests/plugins/plugin-transcoding.ts +++ b/server/tests/plugins/plugin-transcoding.ts @@ -7,8 +7,8 @@ import { getAudioStream, getVideoFileFPS, getVideoStreamFromFile } from '@server import { cleanupTests, createSingleServer, - PluginsCommand, PeerTubeServer, + PluginsCommand, setAccessTokensToServers, setDefaultVideoChannel, testFfmpegStreamError, diff --git a/server/tests/plugins/plugin-unloading.ts b/server/tests/plugins/plugin-unloading.ts index faf9cc599..6bf2fda9b 100644 --- a/server/tests/plugins/plugin-unloading.ts +++ b/server/tests/plugins/plugin-unloading.ts @@ -2,7 +2,6 @@ import 'mocha' import { expect } from 'chai' -import { HttpStatusCode } from '@shared/models' import { cleanupTests, createSingleServer, @@ -11,6 +10,7 @@ import { PluginsCommand, setAccessTokensToServers } from '@shared/extra-utils' +import { HttpStatusCode } from '@shared/models' describe('Test plugins module unloading', function () { let server: PeerTubeServer = null diff --git a/server/tests/plugins/video-constants.ts b/server/tests/plugins/video-constants.ts index dd3b40225..f527a2b30 100644 --- a/server/tests/plugins/video-constants.ts +++ b/server/tests/plugins/video-constants.ts @@ -2,9 +2,8 @@ import 'mocha' import * as chai from 'chai' -import { HttpStatusCode } from '@shared/models' -import { cleanupTests, createSingleServer, PluginsCommand, PeerTubeServer, setAccessTokensToServers } from '@shared/extra-utils' -import { VideoPlaylistPrivacy } from '@shared/models' +import { cleanupTests, createSingleServer, PeerTubeServer, PluginsCommand, setAccessTokensToServers } from '@shared/extra-utils' +import { HttpStatusCode, VideoPlaylistPrivacy } from '@shared/models' const expect = chai.expect diff --git a/server/tools/peertube-redundancy.ts b/server/tools/peertube-redundancy.ts index bcaae63a3..73b026ac8 100644 --- a/server/tools/peertube-redundancy.ts +++ b/server/tools/peertube-redundancy.ts @@ -6,8 +6,7 @@ import { Command, program } from 'commander' import { uniq } from 'lodash' import { URL } from 'url' import validator from 'validator' -import { HttpStatusCode } from '@shared/models' -import { VideoRedundanciesTarget } from '@shared/models' +import { HttpStatusCode, VideoRedundanciesTarget } from '@shared/models' import { assignToken, buildServer, getServerCredentials } from './cli' import bytes = require('bytes') diff --git a/shared/extra-utils/custom-pages/custom-pages-command.ts b/shared/extra-utils/custom-pages/custom-pages-command.ts index 6042233d4..cd869a8de 100644 --- a/shared/extra-utils/custom-pages/custom-pages-command.ts +++ b/shared/extra-utils/custom-pages/custom-pages-command.ts @@ -1,5 +1,4 @@ -import { CustomPage } from '@shared/models' -import { HttpStatusCode } from '@shared/models' +import { CustomPage, HttpStatusCode } from '@shared/models' import { AbstractCommand, OverrideCommandOptions } from '../shared' export class CustomPagesCommand extends AbstractCommand { diff --git a/shared/extra-utils/miscs/generate.ts b/shared/extra-utils/miscs/generate.ts index 4e70ab853..8d6435481 100644 --- a/shared/extra-utils/miscs/generate.ts +++ b/shared/extra-utils/miscs/generate.ts @@ -1,7 +1,7 @@ +import * as ffmpeg from 'fluent-ffmpeg' import { ensureDir, pathExists } from 'fs-extra' import { dirname } from 'path' import { buildAbsoluteFixturePath } from './tests' -import * as ffmpeg from 'fluent-ffmpeg' async function generateHighBitrateVideo () { const tempFixturePath = buildAbsoluteFixturePath('video_high_bitrate_1080p.mp4', true) diff --git a/shared/extra-utils/moderation/abuses-command.ts b/shared/extra-utils/moderation/abuses-command.ts index 72f2c9951..7b3abb056 100644 --- a/shared/extra-utils/moderation/abuses-command.ts +++ b/shared/extra-utils/moderation/abuses-command.ts @@ -7,12 +7,12 @@ import { AbuseUpdate, AbuseVideoIs, AdminAbuse, + HttpStatusCode, ResultList, UserAbuse } from '@shared/models' -import { HttpStatusCode } from '@shared/models' -import { AbstractCommand, OverrideCommandOptions } from '../shared' import { unwrapBody } from '../requests/requests' +import { AbstractCommand, OverrideCommandOptions } from '../shared' export class AbusesCommand extends AbstractCommand { diff --git a/shared/extra-utils/overviews/overviews-command.ts b/shared/extra-utils/overviews/overviews-command.ts index d4a2ac254..06b4892d2 100644 --- a/shared/extra-utils/overviews/overviews-command.ts +++ b/shared/extra-utils/overviews/overviews-command.ts @@ -1,5 +1,4 @@ -import { HttpStatusCode } from '@shared/models' -import { VideosOverview } from '@shared/models' +import { HttpStatusCode, VideosOverview } from '@shared/models' import { AbstractCommand, OverrideCommandOptions } from '../shared' export class OverviewsCommand extends AbstractCommand { diff --git a/shared/extra-utils/requests/activitypub.ts b/shared/extra-utils/requests/activitypub.ts index ecd8ce823..4ae878384 100644 --- a/shared/extra-utils/requests/activitypub.ts +++ b/shared/extra-utils/requests/activitypub.ts @@ -1,7 +1,7 @@ +import { activityPubContextify } from '../../../server/helpers/activitypub' import { doRequest } from '../../../server/helpers/requests' import { HTTP_SIGNATURE } from '../../../server/initializers/constants' import { buildGlobalHeaders } from '../../../server/lib/job-queue/handlers/utils/activitypub-http-utils' -import { activityPubContextify } from '../../../server/helpers/activitypub' function makePOSTAPRequest (url: string, body: any, httpSignature: any, headers: any) { const options = { diff --git a/shared/extra-utils/search/search-command.ts b/shared/extra-utils/search/search-command.ts index 09f5d3f1d..0fbbcd6ef 100644 --- a/shared/extra-utils/search/search-command.ts +++ b/shared/extra-utils/search/search-command.ts @@ -1,4 +1,5 @@ import { + HttpStatusCode, ResultList, Video, VideoChannel, @@ -7,7 +8,6 @@ import { VideoPlaylistsSearchQuery, VideosSearchQuery } from '@shared/models' -import { HttpStatusCode } from '@shared/models' import { AbstractCommand, OverrideCommandOptions } from '../shared' export class SearchCommand extends AbstractCommand { diff --git a/shared/extra-utils/server/config-command.ts b/shared/extra-utils/server/config-command.ts index 6e875fdf6..11148aa46 100644 --- a/shared/extra-utils/server/config-command.ts +++ b/shared/extra-utils/server/config-command.ts @@ -1,6 +1,6 @@ import { merge } from 'lodash' import { DeepPartial } from '@shared/core-utils' -import { About, ServerConfig, HttpStatusCode } from '@shared/models' +import { About, HttpStatusCode, ServerConfig } from '@shared/models' import { CustomConfig } from '../../models/server/custom-config.model' import { AbstractCommand, OverrideCommandOptions } from '../shared' diff --git a/shared/extra-utils/server/debug-command.ts b/shared/extra-utils/server/debug-command.ts index 36704836d..3c5a785bb 100644 --- a/shared/extra-utils/server/debug-command.ts +++ b/shared/extra-utils/server/debug-command.ts @@ -1,5 +1,4 @@ -import { Debug, SendDebugCommand } from '@shared/models' -import { HttpStatusCode } from '@shared/models' +import { Debug, HttpStatusCode, SendDebugCommand } from '@shared/models' import { AbstractCommand, OverrideCommandOptions } from '../shared' export class DebugCommand extends AbstractCommand { diff --git a/shared/extra-utils/server/follows-command.ts b/shared/extra-utils/server/follows-command.ts index 694f5ea24..dce674ac5 100644 --- a/shared/extra-utils/server/follows-command.ts +++ b/shared/extra-utils/server/follows-command.ts @@ -1,6 +1,5 @@ import { pick } from 'lodash' -import { ActivityPubActorType, ActorFollow, FollowState, ResultList } from '@shared/models' -import { HttpStatusCode } from '@shared/models' +import { ActivityPubActorType, ActorFollow, FollowState, HttpStatusCode, ResultList } from '@shared/models' import { AbstractCommand, OverrideCommandOptions } from '../shared' import { PeerTubeServer } from './server' diff --git a/shared/extra-utils/server/plugins-command.ts b/shared/extra-utils/server/plugins-command.ts index 59bc79b3d..b944475a2 100644 --- a/shared/extra-utils/server/plugins-command.ts +++ b/shared/extra-utils/server/plugins-command.ts @@ -3,8 +3,8 @@ import { readJSON, writeJSON } from 'fs-extra' import { join } from 'path' import { root } from '@server/helpers/core-utils' -import { HttpStatusCode } from '@shared/models' import { + HttpStatusCode, PeerTubePlugin, PeerTubePluginIndex, PeertubePluginIndexList, diff --git a/shared/extra-utils/server/redundancy-command.ts b/shared/extra-utils/server/redundancy-command.ts index 137d7f01c..e7a8b3c29 100644 --- a/shared/extra-utils/server/redundancy-command.ts +++ b/shared/extra-utils/server/redundancy-command.ts @@ -1,5 +1,4 @@ -import { ResultList, VideoRedundanciesTarget, VideoRedundancy } from '@shared/models' -import { HttpStatusCode } from '@shared/models' +import { HttpStatusCode, ResultList, VideoRedundanciesTarget, VideoRedundancy } from '@shared/models' import { AbstractCommand, OverrideCommandOptions } from '../shared' export class RedundancyCommand extends AbstractCommand { diff --git a/shared/extra-utils/server/stats-command.ts b/shared/extra-utils/server/stats-command.ts index 6db473588..64a452306 100644 --- a/shared/extra-utils/server/stats-command.ts +++ b/shared/extra-utils/server/stats-command.ts @@ -1,5 +1,4 @@ -import { ServerStats } from '@shared/models' -import { HttpStatusCode } from '@shared/models' +import { HttpStatusCode, ServerStats } from '@shared/models' import { AbstractCommand, OverrideCommandOptions } from '../shared' export class StatsCommand extends AbstractCommand { diff --git a/shared/extra-utils/users/accounts-command.ts b/shared/extra-utils/users/accounts-command.ts index 08977e58b..2f586104e 100644 --- a/shared/extra-utils/users/accounts-command.ts +++ b/shared/extra-utils/users/accounts-command.ts @@ -1,5 +1,4 @@ -import { ResultList } from '@shared/models' -import { HttpStatusCode } from '@shared/models' +import { HttpStatusCode, ResultList } from '@shared/models' import { Account } from '../../models/actors' import { AccountVideoRate, VideoRateType } from '../../models/videos' import { AbstractCommand, OverrideCommandOptions } from '../shared' diff --git a/shared/extra-utils/users/blocklist-command.ts b/shared/extra-utils/users/blocklist-command.ts index a9431acf3..14491a1ae 100644 --- a/shared/extra-utils/users/blocklist-command.ts +++ b/shared/extra-utils/users/blocklist-command.ts @@ -1,7 +1,6 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ -import { HttpStatusCode } from '@shared/models' -import { AccountBlock, ResultList, ServerBlock } from '@shared/models' +import { AccountBlock, HttpStatusCode, ResultList, ServerBlock } from '@shared/models' import { AbstractCommand, OverrideCommandOptions } from '../shared' type ListBlocklistOptions = OverrideCommandOptions & { diff --git a/shared/extra-utils/users/login-command.ts b/shared/extra-utils/users/login-command.ts index b39577260..143f72a59 100644 --- a/shared/extra-utils/users/login-command.ts +++ b/shared/extra-utils/users/login-command.ts @@ -1,5 +1,4 @@ -import { HttpStatusCode } from '@shared/models' -import { PeerTubeProblemDocument } from '@shared/models' +import { HttpStatusCode, PeerTubeProblemDocument } from '@shared/models' import { unwrapBody } from '../requests' import { AbstractCommand, OverrideCommandOptions } from '../shared' diff --git a/shared/extra-utils/users/notifications-command.ts b/shared/extra-utils/users/notifications-command.ts index a51fcc3af..2d79a3747 100644 --- a/shared/extra-utils/users/notifications-command.ts +++ b/shared/extra-utils/users/notifications-command.ts @@ -1,5 +1,4 @@ -import { ResultList } from '@shared/models' -import { HttpStatusCode } from '@shared/models' +import { HttpStatusCode, ResultList } from '@shared/models' import { UserNotification, UserNotificationSetting } from '../../models/users' import { AbstractCommand, OverrideCommandOptions } from '../shared' diff --git a/shared/extra-utils/users/subscriptions-command.ts b/shared/extra-utils/users/subscriptions-command.ts index a69d2a194..edc60e612 100644 --- a/shared/extra-utils/users/subscriptions-command.ts +++ b/shared/extra-utils/users/subscriptions-command.ts @@ -1,5 +1,4 @@ -import { ResultList, Video, VideoChannel } from '@shared/models' -import { HttpStatusCode } from '@shared/models' +import { HttpStatusCode, ResultList, Video, VideoChannel } from '@shared/models' import { AbstractCommand, OverrideCommandOptions } from '../shared' export class SubscriptionsCommand extends AbstractCommand { diff --git a/shared/extra-utils/users/users-command.ts b/shared/extra-utils/users/users-command.ts index f3a251e65..d66ad15f2 100644 --- a/shared/extra-utils/users/users-command.ts +++ b/shared/extra-utils/users/users-command.ts @@ -1,6 +1,6 @@ import { omit, pick } from 'lodash' -import { HttpStatusCode } from '@shared/models' import { + HttpStatusCode, MyUser, ResultList, User, diff --git a/shared/extra-utils/videos/blacklist-command.ts b/shared/extra-utils/videos/blacklist-command.ts index 9404d4c08..3a2ef89ba 100644 --- a/shared/extra-utils/videos/blacklist-command.ts +++ b/shared/extra-utils/videos/blacklist-command.ts @@ -1,6 +1,5 @@ -import { ResultList } from '@shared/models' -import { HttpStatusCode } from '@shared/models' +import { HttpStatusCode, ResultList } from '@shared/models' import { VideoBlacklist, VideoBlacklistType } from '../../models/videos' import { AbstractCommand, OverrideCommandOptions } from '../shared' diff --git a/shared/extra-utils/videos/captions-command.ts b/shared/extra-utils/videos/captions-command.ts index 04dd32f84..a0608e1a6 100644 --- a/shared/extra-utils/videos/captions-command.ts +++ b/shared/extra-utils/videos/captions-command.ts @@ -1,5 +1,4 @@ -import { HttpStatusCode } from '@shared/models' -import { ResultList, VideoCaption } from '@shared/models' +import { HttpStatusCode, ResultList, VideoCaption } from '@shared/models' import { buildAbsoluteFixturePath } from '../miscs' import { AbstractCommand, OverrideCommandOptions } from '../shared' diff --git a/shared/extra-utils/videos/change-ownership-command.ts b/shared/extra-utils/videos/change-ownership-command.ts index ef6f07536..ad4c726ef 100644 --- a/shared/extra-utils/videos/change-ownership-command.ts +++ b/shared/extra-utils/videos/change-ownership-command.ts @@ -1,6 +1,5 @@ -import { ResultList, VideoChangeOwnership } from '@shared/models' -import { HttpStatusCode } from '@shared/models' +import { HttpStatusCode, ResultList, VideoChangeOwnership } from '@shared/models' import { AbstractCommand, OverrideCommandOptions } from '../shared' export class ChangeOwnershipCommand extends AbstractCommand { diff --git a/shared/extra-utils/videos/channels-command.ts b/shared/extra-utils/videos/channels-command.ts index e5393ff56..f8eb3f885 100644 --- a/shared/extra-utils/videos/channels-command.ts +++ b/shared/extra-utils/videos/channels-command.ts @@ -1,6 +1,5 @@ import { pick } from 'lodash' -import { ResultList, VideoChannel, VideoChannelCreateResult } from '@shared/models' -import { HttpStatusCode } from '@shared/models' +import { HttpStatusCode, ResultList, VideoChannel, VideoChannelCreateResult } from '@shared/models' import { VideoChannelCreate } from '../../models/videos/channel/video-channel-create.model' import { VideoChannelUpdate } from '../../models/videos/channel/video-channel-update.model' import { unwrapBody } from '../requests' diff --git a/shared/extra-utils/videos/comments-command.ts b/shared/extra-utils/videos/comments-command.ts index 7368f3ea2..dd14e4b64 100644 --- a/shared/extra-utils/videos/comments-command.ts +++ b/shared/extra-utils/videos/comments-command.ts @@ -1,6 +1,5 @@ import { pick } from 'lodash' -import { HttpStatusCode } from '@shared/models' -import { ResultList, VideoComment, VideoCommentThreads, VideoCommentThreadTree } from '@shared/models' +import { HttpStatusCode, ResultList, VideoComment, VideoCommentThreads, VideoCommentThreadTree } from '@shared/models' import { unwrapBody } from '../requests' import { AbstractCommand, OverrideCommandOptions } from '../shared' diff --git a/shared/extra-utils/videos/history-command.ts b/shared/extra-utils/videos/history-command.ts index 41afc6bc6..13b7150c1 100644 --- a/shared/extra-utils/videos/history-command.ts +++ b/shared/extra-utils/videos/history-command.ts @@ -1,5 +1,4 @@ -import { HttpStatusCode } from '@shared/models' -import { ResultList, Video } from '@shared/models' +import { HttpStatusCode, ResultList, Video } from '@shared/models' import { AbstractCommand, OverrideCommandOptions } from '../shared' export class HistoryCommand extends AbstractCommand { diff --git a/shared/extra-utils/videos/imports-command.ts b/shared/extra-utils/videos/imports-command.ts index d30f9745b..e4944694d 100644 --- a/shared/extra-utils/videos/imports-command.ts +++ b/shared/extra-utils/videos/imports-command.ts @@ -1,6 +1,5 @@ -import { HttpStatusCode } from '@shared/models' -import { ResultList } from '@shared/models' +import { HttpStatusCode, ResultList } from '@shared/models' import { VideoImport, VideoImportCreate } from '../../models/videos' import { unwrapBody } from '../requests' import { AbstractCommand, OverrideCommandOptions } from '../shared' diff --git a/shared/extra-utils/videos/live-command.ts b/shared/extra-utils/videos/live-command.ts index 9dfe3087e..bf9486a05 100644 --- a/shared/extra-utils/videos/live-command.ts +++ b/shared/extra-utils/videos/live-command.ts @@ -3,8 +3,7 @@ import { readdir } from 'fs-extra' import { omit } from 'lodash' import { join } from 'path' -import { HttpStatusCode } from '@shared/models' -import { LiveVideo, LiveVideoCreate, LiveVideoUpdate, VideoCreateResult, VideoDetails, VideoState } from '@shared/models' +import { HttpStatusCode, LiveVideo, LiveVideoCreate, LiveVideoUpdate, VideoCreateResult, VideoDetails, VideoState } from '@shared/models' import { wait } from '../miscs' import { unwrapBody } from '../requests' import { AbstractCommand, OverrideCommandOptions } from '../shared' diff --git a/shared/extra-utils/videos/playlists-command.ts b/shared/extra-utils/videos/playlists-command.ts index 40162c30d..6f329800e 100644 --- a/shared/extra-utils/videos/playlists-command.ts +++ b/shared/extra-utils/videos/playlists-command.ts @@ -1,7 +1,7 @@ import { omit, pick } from 'lodash' -import { HttpStatusCode } from '@shared/models' import { BooleanBothQuery, + HttpStatusCode, ResultList, VideoExistInPlaylist, VideoPlaylist, diff --git a/shared/extra-utils/videos/streaming-playlists.ts b/shared/extra-utils/videos/streaming-playlists.ts index 007d3d98d..1ae3fefc1 100644 --- a/shared/extra-utils/videos/streaming-playlists.ts +++ b/shared/extra-utils/videos/streaming-playlists.ts @@ -1,7 +1,6 @@ import { expect } from 'chai' import { sha256 } from '@server/helpers/core-utils' -import { HttpStatusCode } from '@shared/models' -import { VideoStreamingPlaylist } from '@shared/models' +import { HttpStatusCode, VideoStreamingPlaylist } from '@shared/models' import { PeerTubeServer } from '../server' async function checkSegmentHash (options: { diff --git a/shared/extra-utils/videos/videos-command.ts b/shared/extra-utils/videos/videos-command.ts index f46d386f4..40cc4dc28 100644 --- a/shared/extra-utils/videos/videos-command.ts +++ b/shared/extra-utils/videos/videos-command.ts @@ -7,8 +7,8 @@ import { omit, pick } from 'lodash' import validator from 'validator' import { buildUUID } from '@server/helpers/uuid' import { loadLanguages } from '@server/initializers/constants' -import { HttpStatusCode } from '@shared/models' import { + HttpStatusCode, ResultList, UserVideoRateType, Video, @@ -332,7 +332,7 @@ export class VideosCommand extends AbstractCommand { attributes?: VideoEdit mode?: 'legacy' | 'resumable' // default legacy } = {}) { - const { mode = 'legacy', expectedStatus } = options + const { mode = 'legacy' } = options let defaultChannelId = 1 try { @@ -360,22 +360,23 @@ export class VideosCommand extends AbstractCommand { ...options.attributes } - const res = mode === 'legacy' + const created = mode === 'legacy' ? await this.buildLegacyUpload({ ...options, attributes }) : await this.buildResumeUpload({ ...options, attributes }) // Wait torrent generation + const expectedStatus = this.buildExpectedStatus({ ...options, defaultExpectedStatus: HttpStatusCode.OK_200 }) if (expectedStatus === HttpStatusCode.OK_200) { let video: VideoDetails do { - video = await this.getWithToken({ ...options, id: video.uuid }) + video = await this.getWithToken({ ...options, id: created.uuid }) await wait(50) } while (!video.files[0].torrentUrl) } - return res + return created } async buildLegacyUpload (options: OverrideCommandOptions & { @@ -535,13 +536,13 @@ export class VideosCommand extends AbstractCommand { async randomUpload (options: OverrideCommandOptions & { wait?: boolean // default true - additionalParams?: VideoEdit & { prefixName: string } + additionalParams?: VideoEdit & { prefixName?: string } } = {}) { const { wait = true, additionalParams } = options const prefixName = additionalParams?.prefixName || '' const name = prefixName + buildUUID() - const attributes = { name, additionalParams } + const attributes = { name, ...additionalParams } const result = await this.upload({ ...options, attributes }) diff --git a/shared/extra-utils/videos/videos.ts b/shared/extra-utils/videos/videos.ts index a96073c56..9a9bfb3cf 100644 --- a/shared/extra-utils/videos/videos.ts +++ b/shared/extra-utils/videos/videos.ts @@ -202,7 +202,7 @@ async function uploadRandomVideoOnServers ( additionalParams?: VideoEdit & { prefixName?: string } ) { const server = servers.find(s => s.serverNumber === serverNumber) - const res = await server.videos.randomUpload({ wait: false, ...additionalParams }) + const res = await server.videos.randomUpload({ wait: false, additionalParams }) await waitJobs(servers) -- cgit v1.2.3 From 01af646261264befde7ce6ca5130fd07c0b23aa1 Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Tue, 20 Jul 2021 13:38:26 +0200 Subject: Channel deletion consistency --- .../app/+my-library/+my-video-channels/my-video-channels.component.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/client/src/app/+my-library/+my-video-channels/my-video-channels.component.ts b/client/src/app/+my-library/+my-video-channels/my-video-channels.component.ts index 67b3ee496..b6a2f592d 100644 --- a/client/src/app/+my-library/+my-video-channels/my-video-channels.component.ts +++ b/client/src/app/+my-library/+my-video-channels/my-video-channels.component.ts @@ -45,9 +45,9 @@ export class MyVideoChannelsComponent { It will delete ${videoChannel.videosCount} videos uploaded in this channel, and you will not be able to create another channel with the same name (${videoChannel.name})!`, - $localize`Please type the display name of the video channel (${videoChannel.displayName}) to confirm`, + $localize`Please type the name of the video channel (${videoChannel.name}) to confirm`, - videoChannel.displayName, + videoChannel.name, $localize`Delete` ) -- cgit v1.2.3 From 7f28f2ddbaeecf451d501e99ded0408c14a33600 Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Tue, 20 Jul 2021 13:47:49 +0200 Subject: Warning when using capitalized letter in login --- client/src/app/+login/login.component.html | 4 ++++ client/src/app/+login/login.component.ts | 4 ++++ client/src/sass/application.scss | 8 ++++++-- 3 files changed, 14 insertions(+), 2 deletions(-) diff --git a/client/src/app/+login/login.component.html b/client/src/app/+login/login.component.html index 5f5b0f565..27793ff0c 100644 --- a/client/src/app/+login/login.component.html +++ b/client/src/app/+login/login.component.html @@ -28,6 +28,10 @@
{{ formErrors.username }}
+ +
+ ⚠️ Most email addresses do not include capital letters. +
diff --git a/client/src/app/+login/login.component.ts b/client/src/app/+login/login.component.ts index d8ad49081..9731383af 100644 --- a/client/src/app/+login/login.component.ts +++ b/client/src/app/+login/login.component.ts @@ -141,6 +141,10 @@ The link will expire within 1 hour.` this.accordion = instanceAboutAccordion.accordion } + hasUsernameUppercase () { + return this.form.value['username'].match(/[A-Z]/) + } + private loadExternalAuthToken (username: string, token: string) { this.isAuthenticatedWithExternalAuth = true diff --git a/client/src/sass/application.scss b/client/src/sass/application.scss index 30d487b11..bd834db70 100644 --- a/client/src/sass/application.scss +++ b/client/src/sass/application.scss @@ -123,12 +123,16 @@ code { vertical-align: middle; } -.form-error { +.form-error, +.form-warning { display: block; - color: $red; margin-top: 5px; } +.form-error { + color: $red; +} + .input-error, my-input-toggle-hidden ::ng-deep input { border-color: $red !important; -- cgit v1.2.3 From 4d029ef8ec3d5274eeaa3ee6d808eb7035e7faef Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Tue, 20 Jul 2021 14:15:15 +0200 Subject: Add ability for instances to follow any actor --- client/src/app/+admin/admin.component.ts | 4 +- client/src/app/+admin/admin.module.ts | 3 +- .../followers-list/followers-list.component.html | 4 +- .../following-list/follow-modal.component.html | 42 ++ .../following-list/follow-modal.component.scss | 3 + .../following-list/follow-modal.component.ts | 69 +++ .../following-list/following-list.component.html | 21 +- .../following-list/following-list.component.ts | 22 +- .../src/app/+admin/follows/following-list/index.ts | 1 + client/src/app/+admin/follows/follows.routes.ts | 4 +- .../form-validators/batch-domains-validators.ts | 60 --- .../app/shared/form-validators/host-validators.ts | 105 ++++ client/src/app/shared/form-validators/host.ts | 8 - client/src/app/shared/form-validators/index.ts | 1 - .../shared-instance/instance-follow.service.ts | 13 +- .../batch-domains-modal.component.html | 14 +- .../batch-domains-modal.component.ts | 8 +- server/controllers/api/server/follows.ts | 21 +- server/helpers/custom-validators/follows.ts | 20 +- server/helpers/custom-validators/servers.ts | 1 - server/lib/activitypub/crawl.ts | 3 +- server/lib/activitypub/follow.ts | 17 +- server/middlewares/validators/follows.ts | 37 +- server/models/actor/actor-follow.ts | 26 +- .../video/sql/videos-id-list-query-builder.ts | 6 +- server/tests/api/check-params/follows.ts | 36 +- server/tests/api/moderation/blocklist.ts | 4 +- .../api/notifications/moderation-notifications.ts | 4 +- .../tests/api/redundancy/redundancy-constraints.ts | 4 +- server/tests/api/server/auto-follows.ts | 2 +- server/tests/api/server/follows-moderation.ts | 10 +- server/tests/api/server/follows.ts | 595 ++++++++++++--------- server/tests/api/server/handle-down.ts | 6 +- server/tests/api/server/stats.ts | 2 +- server/tests/api/users/user-subscriptions.ts | 2 +- server/tests/api/users/users.ts | 2 +- shared/extra-utils/server/follows-command.ts | 35 +- shared/extra-utils/server/follows.ts | 4 +- shared/extra-utils/users/accounts.ts | 44 -- shared/extra-utils/users/actors.ts | 73 +++ shared/extra-utils/users/index.ts | 2 +- shared/extra-utils/videos/comments-command.ts | 21 + shared/extra-utils/videos/videos-command.ts | 10 + shared/models/server/index.ts | 1 + shared/models/server/server-follow-create.model.ts | 4 + support/doc/api/openapi.yaml | 18 +- 46 files changed, 874 insertions(+), 518 deletions(-) create mode 100644 client/src/app/+admin/follows/following-list/follow-modal.component.html create mode 100644 client/src/app/+admin/follows/following-list/follow-modal.component.scss create mode 100644 client/src/app/+admin/follows/following-list/follow-modal.component.ts delete mode 100644 client/src/app/shared/form-validators/batch-domains-validators.ts create mode 100644 client/src/app/shared/form-validators/host-validators.ts delete mode 100644 client/src/app/shared/form-validators/host.ts delete mode 100644 shared/extra-utils/users/accounts.ts create mode 100644 shared/extra-utils/users/actors.ts create mode 100644 shared/models/server/server-follow-create.model.ts diff --git a/client/src/app/+admin/admin.component.ts b/client/src/app/+admin/admin.component.ts index dd92ed2ca..4b6fab6ed 100644 --- a/client/src/app/+admin/admin.component.ts +++ b/client/src/app/+admin/admin.component.ts @@ -26,12 +26,12 @@ export class AdminComponent implements OnInit { label: $localize`Federation`, children: [ { - label: $localize`Instances you follow`, + label: $localize`Following`, routerLink: '/admin/follows/following-list', iconName: 'following' }, { - label: $localize`Instances following you`, + label: $localize`Followers`, routerLink: '/admin/follows/followers-list', iconName: 'follower' }, diff --git a/client/src/app/+admin/admin.module.ts b/client/src/app/+admin/admin.module.ts index a7fe20b07..1ea7b9784 100644 --- a/client/src/app/+admin/admin.module.ts +++ b/client/src/app/+admin/admin.module.ts @@ -25,7 +25,7 @@ import { EditVODTranscodingComponent } from './config' import { ConfigService } from './config/shared/config.service' -import { FollowersListComponent, FollowsComponent, VideoRedundanciesListComponent } from './follows' +import { FollowersListComponent, FollowModalComponent, FollowsComponent, VideoRedundanciesListComponent } from './follows' import { FollowingListComponent } from './follows/following-list/following-list.component' import { RedundancyCheckboxComponent } from './follows/shared/redundancy-checkbox.component' import { VideoRedundancyInformationComponent } from './follows/video-redundancies-list/video-redundancy-information.component' @@ -68,6 +68,7 @@ import { UserCreateComponent, UserListComponent, UserPasswordComponent, UsersCom FollowsComponent, FollowersListComponent, FollowingListComponent, + FollowModalComponent, RedundancyCheckboxComponent, VideoRedundanciesListComponent, VideoRedundancyInformationComponent, diff --git a/client/src/app/+admin/follows/followers-list/followers-list.component.html b/client/src/app/+admin/follows/followers-list/followers-list.component.html index c2e9a4df6..08459634d 100644 --- a/client/src/app/+admin/follows/followers-list/followers-list.component.html +++ b/client/src/app/+admin/follows/followers-list/followers-list.component.html @@ -1,6 +1,6 @@

- Instances following you + Followers of your instance

Actions - Follower handle + Follower State Score Created diff --git a/client/src/app/+admin/follows/following-list/follow-modal.component.html b/client/src/app/+admin/follows/following-list/follow-modal.component.html new file mode 100644 index 000000000..d0761b718 --- /dev/null +++ b/client/src/app/+admin/follows/following-list/follow-modal.component.html @@ -0,0 +1,42 @@ + + + + + + diff --git a/client/src/app/+admin/follows/following-list/follow-modal.component.scss b/client/src/app/+admin/follows/following-list/follow-modal.component.scss new file mode 100644 index 000000000..9621a566f --- /dev/null +++ b/client/src/app/+admin/follows/following-list/follow-modal.component.scss @@ -0,0 +1,3 @@ +textarea { + height: 200px; +} diff --git a/client/src/app/+admin/follows/following-list/follow-modal.component.ts b/client/src/app/+admin/follows/following-list/follow-modal.component.ts new file mode 100644 index 000000000..dc6909200 --- /dev/null +++ b/client/src/app/+admin/follows/following-list/follow-modal.component.ts @@ -0,0 +1,69 @@ +import { Component, EventEmitter, OnInit, Output, ViewChild } from '@angular/core' +import { Notifier } from '@app/core' +import { splitAndGetNotEmpty, UNIQUE_HOSTS_OR_HANDLE_VALIDATOR } from '@app/shared/form-validators/host-validators' +import { FormReactive, FormValidatorService } from '@app/shared/shared-forms' +import { InstanceFollowService } from '@app/shared/shared-instance' +import { NgbModal } from '@ng-bootstrap/ng-bootstrap' +import { NgbModalRef } from '@ng-bootstrap/ng-bootstrap/modal/modal-ref' + +@Component({ + selector: 'my-follow-modal', + templateUrl: './follow-modal.component.html', + styleUrls: [ './follow-modal.component.scss' ] +}) +export class FollowModalComponent extends FormReactive implements OnInit { + @ViewChild('modal', { static: true }) modal: NgbModal + + @Output() newFollow = new EventEmitter() + + placeholder = 'example.com\nchocobozzz@example.com\nchocobozzz_channel@example.com' + + private openedModal: NgbModalRef + + constructor ( + protected formValidatorService: FormValidatorService, + private modalService: NgbModal, + private followService: InstanceFollowService, + private notifier: Notifier + ) { + super() + } + + ngOnInit () { + this.buildForm({ + hostsOrHandles: UNIQUE_HOSTS_OR_HANDLE_VALIDATOR + }) + } + + openModal () { + this.openedModal = this.modalService.open(this.modal, { centered: true }) + } + + hide () { + this.openedModal.close() + } + + submit () { + this.addFollowing() + + this.form.reset() + this.hide() + } + + httpEnabled () { + return window.location.protocol === 'https:' + } + + private async addFollowing () { + const hostsOrHandles = splitAndGetNotEmpty(this.form.value['hostsOrHandles']) + + this.followService.follow(hostsOrHandles).subscribe( + () => { + this.notifier.success($localize`Follow request(s) sent!`) + this.newFollow.emit() + }, + + err => this.notifier.error(err.message) + ) + } +} diff --git a/client/src/app/+admin/follows/following-list/following-list.component.html b/client/src/app/+admin/follows/following-list/following-list.component.html index e7c0c9088..75b0efca8 100644 --- a/client/src/app/+admin/follows/following-list/following-list.component.html +++ b/client/src/app/+admin/follows/following-list/following-list.component.html @@ -1,6 +1,6 @@

- Instances you follow + Your instance subscriptions

@@ -28,7 +28,7 @@ Action - Host + Following State Created Redundancy allowed @@ -41,8 +41,8 @@ - - {{ follow.following.host }} + + {{ follow.following.name + '@' + follow.following.host }} @@ -57,6 +57,7 @@ {{ follow.createdAt | date: 'short' }} @@ -75,10 +76,4 @@ - - -
- It seems that you are not on a HTTPS server. Your webserver needs to have TLS activated in order to follow servers. -
-
-
+ diff --git a/client/src/app/+admin/follows/following-list/following-list.component.ts b/client/src/app/+admin/follows/following-list/following-list.component.ts index b63fe08c0..ba62dfa23 100644 --- a/client/src/app/+admin/follows/following-list/following-list.component.ts +++ b/client/src/app/+admin/follows/following-list/following-list.component.ts @@ -4,13 +4,14 @@ import { ConfirmService, Notifier, RestPagination, RestTable } from '@app/core' import { InstanceFollowService } from '@app/shared/shared-instance' import { BatchDomainsModalComponent } from '@app/shared/shared-moderation' import { ActorFollow } from '@shared/models' +import { FollowModalComponent } from './follow-modal.component' @Component({ templateUrl: './following-list.component.html', styleUrls: [ '../follows.component.scss', './following-list.component.scss' ] }) export class FollowingListComponent extends RestTable implements OnInit { - @ViewChild('batchDomainsModal') batchDomainsModal: BatchDomainsModalComponent + @ViewChild('followModal') followModal: FollowModalComponent following: ActorFollow[] = [] totalRecords = 0 @@ -33,23 +34,12 @@ export class FollowingListComponent extends RestTable implements OnInit { return 'FollowingListComponent' } - addDomainsToFollow () { - this.batchDomainsModal.openModal() + openFollowModal () { + this.followModal.openModal() } - httpEnabled () { - return window.location.protocol === 'https:' - } - - async addFollowing (hosts: string[]) { - this.followService.follow(hosts).subscribe( - () => { - this.notifier.success($localize`Follow request(s) sent!`) - this.reloadData() - }, - - err => this.notifier.error(err.message) - ) + isInstanceFollowing (follow: ActorFollow) { + return follow.following.name === 'peertube' } async removeFollowing (follow: ActorFollow) { diff --git a/client/src/app/+admin/follows/following-list/index.ts b/client/src/app/+admin/follows/following-list/index.ts index a70d46a7e..88be0ed4c 100644 --- a/client/src/app/+admin/follows/following-list/index.ts +++ b/client/src/app/+admin/follows/following-list/index.ts @@ -1 +1,2 @@ +export * from './follow-modal.component' export * from './following-list.component' diff --git a/client/src/app/+admin/follows/follows.routes.ts b/client/src/app/+admin/follows/follows.routes.ts index cd70daf77..3843b42b5 100644 --- a/client/src/app/+admin/follows/follows.routes.ts +++ b/client/src/app/+admin/follows/follows.routes.ts @@ -25,7 +25,7 @@ export const FollowsRoutes: Routes = [ component: FollowingListComponent, data: { meta: { - title: $localize`Following list` + title: $localize`Following` } } }, @@ -34,7 +34,7 @@ export const FollowsRoutes: Routes = [ component: FollowersListComponent, data: { meta: { - title: $localize`Followers list` + title: $localize`Followers` } } }, diff --git a/client/src/app/shared/form-validators/batch-domains-validators.ts b/client/src/app/shared/form-validators/batch-domains-validators.ts deleted file mode 100644 index 423d1337f..000000000 --- a/client/src/app/shared/form-validators/batch-domains-validators.ts +++ /dev/null @@ -1,60 +0,0 @@ -import { AbstractControl, FormControl, ValidatorFn, Validators } from '@angular/forms' -import { BuildFormValidator } from './form-validator.model' -import { validateHost } from './host' - -export function getNotEmptyHosts (hosts: string) { - return hosts - .split('\n') - .filter((host: string) => host && host.length !== 0) // Eject empty hosts -} - -const validDomains: ValidatorFn = (control: FormControl) => { - if (!control.value) return null - - const newHostsErrors = [] - const hosts = getNotEmptyHosts(control.value) - - for (const host of hosts) { - if (validateHost(host) === false) { - newHostsErrors.push($localize`${host} is not valid`) - } - } - - /* Is not valid. */ - if (newHostsErrors.length !== 0) { - return { - 'validDomains': { - reason: 'invalid', - value: newHostsErrors.join('. ') + '.' - } - } - } - - /* Is valid. */ - return null -} - -const isHostsUnique: ValidatorFn = (control: AbstractControl) => { - if (!control.value) return null - - const hosts = getNotEmptyHosts(control.value) - - if (hosts.every((host: string) => hosts.indexOf(host) === hosts.lastIndexOf(host))) { - return null - } else { - return { - 'uniqueDomains': { - reason: 'invalid' - } - } - } -} - -export const DOMAINS_VALIDATOR: BuildFormValidator = { - VALIDATORS: [Validators.required, validDomains, isHostsUnique], - MESSAGES: { - 'required': $localize`Domain is required.`, - 'validDomains': $localize`Domains entered are invalid.`, - 'uniqueDomains': $localize`Domains entered contain duplicates.` - } -} diff --git a/client/src/app/shared/form-validators/host-validators.ts b/client/src/app/shared/form-validators/host-validators.ts new file mode 100644 index 000000000..d750113ef --- /dev/null +++ b/client/src/app/shared/form-validators/host-validators.ts @@ -0,0 +1,105 @@ +import { AbstractControl, ValidatorFn, Validators } from '@angular/forms' +import { BuildFormValidator } from './form-validator.model' + +function validateHost (value: string) { + // Thanks to http://stackoverflow.com/a/106223 + const HOST_REGEXP = new RegExp( + '^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$' + ) + + return HOST_REGEXP.test(value) +} + +function validateHandle (value: string) { + if (!value) return false + + return value.includes('@') +} + +const validHosts: ValidatorFn = (control: AbstractControl) => { + if (!control.value) return null + + const errors = [] + const hosts = splitAndGetNotEmpty(control.value) + + for (const host of hosts) { + if (validateHost(host) === false) { + errors.push($localize`${host} is not valid`) + } + } + + // valid + if (errors.length === 0) return null + + return { + 'validHosts': { + reason: 'invalid', + value: errors.join('. ') + '.' + } + } +} + +const validHostsOrHandles: ValidatorFn = (control: AbstractControl) => { + if (!control.value) return null + + const errors = [] + const lines = splitAndGetNotEmpty(control.value) + + for (const line of lines) { + if (validateHost(line) === false && validateHandle(line) === false) { + errors.push($localize`${line} is not valid`) + } + } + + // valid + if (errors.length === 0) return null + + return { + 'validHostsOrHandles': { + reason: 'invalid', + value: errors.join('. ') + '.' + } + } +} + +// --------------------------------------------------------------------------- + +export function splitAndGetNotEmpty (value: string) { + return value + .split('\n') + .filter(line => line && line.length !== 0) // Eject empty hosts +} + +export const unique: ValidatorFn = (control: AbstractControl) => { + if (!control.value) return null + + const hosts = splitAndGetNotEmpty(control.value) + + if (hosts.every((host: string) => hosts.indexOf(host) === hosts.lastIndexOf(host))) { + return null + } + + return { + 'unique': { + reason: 'invalid' + } + } +} + +export const UNIQUE_HOSTS_VALIDATOR: BuildFormValidator = { + VALIDATORS: [ Validators.required, validHosts, unique ], + MESSAGES: { + 'required': $localize`Domain is required.`, + 'validHosts': $localize`Hosts entered are invalid.`, + 'unique': $localize`Hosts entered contain duplicates.` + } +} + +export const UNIQUE_HOSTS_OR_HANDLE_VALIDATOR: BuildFormValidator = { + VALIDATORS: [ Validators.required, validHostsOrHandles, unique ], + MESSAGES: { + 'required': $localize`Domain is required.`, + 'validHostsOrHandles': $localize`Hosts or handles are invalid.`, + 'unique': $localize`Hosts or handles contain duplicates.` + } +} diff --git a/client/src/app/shared/form-validators/host.ts b/client/src/app/shared/form-validators/host.ts deleted file mode 100644 index c18a35f9b..000000000 --- a/client/src/app/shared/form-validators/host.ts +++ /dev/null @@ -1,8 +0,0 @@ -export function validateHost (value: string) { - // Thanks to http://stackoverflow.com/a/106223 - const HOST_REGEXP = new RegExp( - '^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$' - ) - - return HOST_REGEXP.test(value) -} diff --git a/client/src/app/shared/form-validators/index.ts b/client/src/app/shared/form-validators/index.ts index f621f03a4..c14272a2a 100644 --- a/client/src/app/shared/form-validators/index.ts +++ b/client/src/app/shared/form-validators/index.ts @@ -1,5 +1,4 @@ export * from './form-validator.model' -export * from './host' // Don't re export const variables because webpack 4 cannot do tree shaking with them // export * from './abuse-validators' diff --git a/client/src/app/shared/shared-instance/instance-follow.service.ts b/client/src/app/shared/shared-instance/instance-follow.service.ts index e52660140..af44020cf 100644 --- a/client/src/app/shared/shared-instance/instance-follow.service.ts +++ b/client/src/app/shared/shared-instance/instance-follow.service.ts @@ -4,7 +4,7 @@ import { catchError, map } from 'rxjs/operators' import { HttpClient, HttpParams } from '@angular/common/http' import { Injectable } from '@angular/core' import { RestExtractor, RestPagination, RestService } from '@app/core' -import { ActivityPubActorType, ActorFollow, FollowState, ResultList } from '@shared/models' +import { ActivityPubActorType, ActorFollow, FollowState, ResultList, ServerFollowCreate } from '@shared/models' import { environment } from '../../../environments/environment' @Injectable() @@ -64,9 +64,10 @@ export class InstanceFollowService { ) } - follow (notEmptyHosts: string[]) { - const body = { - hosts: notEmptyHosts + follow (hostsOrHandles: string[]) { + const body: ServerFollowCreate = { + handles: hostsOrHandles.filter(v => v.includes('@')), + hosts: hostsOrHandles.filter(v => !v.includes('@')) } return this.authHttp.post(InstanceFollowService.BASE_APPLICATION_URL + '/following', body) @@ -77,7 +78,9 @@ export class InstanceFollowService { } unfollow (follow: ActorFollow) { - return this.authHttp.delete(InstanceFollowService.BASE_APPLICATION_URL + '/following/' + follow.following.host) + const handle = follow.following.name + '@' + follow.following.host + + return this.authHttp.delete(InstanceFollowService.BASE_APPLICATION_URL + '/following/' + handle) .pipe( map(this.restExtractor.extractDataBool), catchError(res => this.restExtractor.handleError(res)) diff --git a/client/src/app/shared/shared-moderation/batch-domains-modal.component.html b/client/src/app/shared/shared-moderation/batch-domains-modal.component.html index 6a3c65721..8306a96bc 100644 --- a/client/src/app/shared/shared-moderation/batch-domains-modal.component.html +++ b/client/src/app/shared/shared-moderation/batch-domains-modal.component.html @@ -1,6 +1,6 @@ @@ -11,15 +11,15 @@ -
- {{ formErrors.domains }} +
+ {{ formErrors.hosts }} -
- {{ form.controls['domains'].errors.validDomains.value }} +
+ {{ form.controls['hosts'].errors.validHosts.value }}
diff --git a/client/src/app/shared/shared-moderation/batch-domains-modal.component.ts b/client/src/app/shared/shared-moderation/batch-domains-modal.component.ts index 6edbb6023..20be728f6 100644 --- a/client/src/app/shared/shared-moderation/batch-domains-modal.component.ts +++ b/client/src/app/shared/shared-moderation/batch-domains-modal.component.ts @@ -2,7 +2,7 @@ import { Component, EventEmitter, Input, OnInit, Output, ViewChild } from '@angu import { FormReactive, FormValidatorService } from '@app/shared/shared-forms' import { NgbModal } from '@ng-bootstrap/ng-bootstrap' import { NgbModalRef } from '@ng-bootstrap/ng-bootstrap/modal/modal-ref' -import { DOMAINS_VALIDATOR, getNotEmptyHosts } from '../form-validators/batch-domains-validators' +import { splitAndGetNotEmpty, UNIQUE_HOSTS_VALIDATOR } from '../form-validators/host-validators' @Component({ selector: 'my-batch-domains-modal', @@ -28,7 +28,7 @@ export class BatchDomainsModalComponent extends FormReactive implements OnInit { if (!this.action) this.action = $localize`Process domains` this.buildForm({ - domains: DOMAINS_VALIDATOR + hosts: UNIQUE_HOSTS_VALIDATOR }) } @@ -41,9 +41,7 @@ export class BatchDomainsModalComponent extends FormReactive implements OnInit { } submit () { - this.domains.emit( - getNotEmptyHosts(this.form.controls['domains'].value) - ) + this.domains.emit(splitAndGetNotEmpty(this.form.controls['hosts'].value)) this.form.reset() this.hide() } diff --git a/server/controllers/api/server/follows.ts b/server/controllers/api/server/follows.ts index e6f4f6b92..cbe6b7e4f 100644 --- a/server/controllers/api/server/follows.ts +++ b/server/controllers/api/server/follows.ts @@ -29,6 +29,7 @@ import { removeFollowingValidator } from '../../../middlewares/validators' import { ActorFollowModel } from '../../../models/actor/actor-follow' +import { ServerFollowCreate } from '@shared/models' const serverFollowsRouter = express.Router() serverFollowsRouter.get('/following', @@ -45,10 +46,10 @@ serverFollowsRouter.post('/following', ensureUserHasRight(UserRight.MANAGE_SERVER_FOLLOW), followValidator, setBodyHostsPort, - asyncMiddleware(followInstance) + asyncMiddleware(addFollow) ) -serverFollowsRouter.delete('/following/:host', +serverFollowsRouter.delete('/following/:hostOrHandle', authenticate, ensureUserHasRight(UserRight.MANAGE_SERVER_FOLLOW), asyncMiddleware(removeFollowingValidator), @@ -125,8 +126,8 @@ async function listFollowers (req: express.Request, res: express.Response) { return res.json(getFormattedObjects(resultList.data, resultList.total)) } -async function followInstance (req: express.Request, res: express.Response) { - const hosts = req.body.hosts as string[] +async function addFollow (req: express.Request, res: express.Response) { + const { hosts, handles } = req.body as ServerFollowCreate const follower = await getServerActor() for (const host of hosts) { @@ -139,6 +140,18 @@ async function followInstance (req: express.Request, res: express.Response) { JobQueue.Instance.createJob({ type: 'activitypub-follow', payload }) } + for (const handle of handles) { + const [ name, host ] = handle.split('@') + + const payload = { + host, + name, + followerActorId: follower.id + } + + JobQueue.Instance.createJob({ type: 'activitypub-follow', payload }) + } + return res.status(HttpStatusCode.NO_CONTENT_204).end() } diff --git a/server/helpers/custom-validators/follows.ts b/server/helpers/custom-validators/follows.ts index fbef7ad87..8f65552c3 100644 --- a/server/helpers/custom-validators/follows.ts +++ b/server/helpers/custom-validators/follows.ts @@ -1,4 +1,4 @@ -import { exists } from './misc' +import { exists, isArray } from './misc' import { FollowState } from '@shared/models' function isFollowStateValid (value: FollowState) { @@ -7,8 +7,24 @@ function isFollowStateValid (value: FollowState) { return value === 'pending' || value === 'accepted' } +function isRemoteHandleValid (value: string) { + if (!exists(value)) return false + if (typeof value !== 'string') return false + + return value.includes('@') +} + +function isEachUniqueHandleValid (handles: string[]) { + return isArray(handles) && + handles.every(handle => { + return isRemoteHandleValid(handle) && handles.indexOf(handle) === handles.lastIndexOf(handle) + }) +} + // --------------------------------------------------------------------------- export { - isFollowStateValid + isFollowStateValid, + isRemoteHandleValid, + isEachUniqueHandleValid } diff --git a/server/helpers/custom-validators/servers.ts b/server/helpers/custom-validators/servers.ts index adf1ea497..c0f8b6aeb 100644 --- a/server/helpers/custom-validators/servers.ts +++ b/server/helpers/custom-validators/servers.ts @@ -19,7 +19,6 @@ function isHostValid (host: string) { function isEachUniqueHostValid (hosts: string[]) { return isArray(hosts) && - hosts.length !== 0 && hosts.every(host => { return isHostValid(host) && hosts.indexOf(host) === hosts.lastIndexOf(host) }) diff --git a/server/lib/activitypub/crawl.ts b/server/lib/activitypub/crawl.ts index cd117f571..28ff5225a 100644 --- a/server/lib/activitypub/crawl.ts +++ b/server/lib/activitypub/crawl.ts @@ -1,3 +1,4 @@ +import { retryTransactionWrapper } from '@server/helpers/database-utils' import * as Bluebird from 'bluebird' import { URL } from 'url' import { ActivityPubOrderedCollection } from '../../../shared/models/activitypub' @@ -51,7 +52,7 @@ async function crawlCollectionPage (argUrl: string, handler: HandlerFunction } } - if (cleaner) await cleaner(startDate) + if (cleaner) await retryTransactionWrapper(cleaner, startDate) } export { diff --git a/server/lib/activitypub/follow.ts b/server/lib/activitypub/follow.ts index c1bd667e0..741b54df5 100644 --- a/server/lib/activitypub/follow.ts +++ b/server/lib/activitypub/follow.ts @@ -31,6 +31,21 @@ async function autoFollowBackIfNeeded (actorFollow: MActorFollowActors, transact } } +// If we only have an host, use a default account handle +function getRemoteNameAndHost (handleOrHost: string) { + let name = SERVER_ACTOR_NAME + let host = handleOrHost + + const splitted = handleOrHost.split('@') + if (splitted.length === 2) { + name = splitted[0] + host = splitted[1] + } + + return { name, host } +} + export { - autoFollowBackIfNeeded + autoFollowBackIfNeeded, + getRemoteNameAndHost } diff --git a/server/middlewares/validators/follows.ts b/server/middlewares/validators/follows.ts index 05cc66c38..16abdd096 100644 --- a/server/middlewares/validators/follows.ts +++ b/server/middlewares/validators/follows.ts @@ -1,7 +1,8 @@ import * as express from 'express' import { body, param, query } from 'express-validator' -import { isFollowStateValid } from '@server/helpers/custom-validators/follows' +import { isEachUniqueHandleValid, isFollowStateValid, isRemoteHandleValid } from '@server/helpers/custom-validators/follows' import { loadActorUrlOrGetFromWebfinger } from '@server/lib/activitypub/actors' +import { getRemoteNameAndHost } from '@server/lib/activitypub/follow' import { getServerActor } from '@server/models/application/application' import { MActorFollowActorsDefault } from '@server/types/models' import { HttpStatusCode } from '../../../shared/models/http/http-error-codes' @@ -9,10 +10,11 @@ import { isTestInstance } from '../../helpers/core-utils' import { isActorTypeValid, isValidActorHandle } from '../../helpers/custom-validators/activitypub/actor' import { isEachUniqueHostValid, isHostValid } from '../../helpers/custom-validators/servers' import { logger } from '../../helpers/logger' -import { SERVER_ACTOR_NAME, WEBSERVER } from '../../initializers/constants' +import { WEBSERVER } from '../../initializers/constants' import { ActorModel } from '../../models/actor/actor' import { ActorFollowModel } from '../../models/actor/actor-follow' import { areValidationErrors } from './shared' +import { ServerFollowCreate } from '@shared/models' const listFollowsValidator = [ query('state') @@ -30,29 +32,46 @@ const listFollowsValidator = [ ] const followValidator = [ - body('hosts').custom(isEachUniqueHostValid).withMessage('Should have an array of unique hosts'), + body('hosts') + .toArray() + .custom(isEachUniqueHostValid).withMessage('Should have an array of unique hosts'), + + body('handles') + .toArray() + .custom(isEachUniqueHandleValid).withMessage('Should have an array of handles'), (req: express.Request, res: express.Response, next: express.NextFunction) => { - // Force https if the administrator wants to make friends + // Force https if the administrator wants to follow remote actors if (isTestInstance() === false && WEBSERVER.SCHEME === 'http') { return res .status(HttpStatusCode.INTERNAL_SERVER_ERROR_500) .json({ error: 'Cannot follow on a non HTTPS web server.' }) - .end() } logger.debug('Checking follow parameters', { parameters: req.body }) if (areValidationErrors(req, res)) return + const body: ServerFollowCreate = req.body + if (body.hosts.length === 0 && body.handles.length === 0) { + + return res + .status(HttpStatusCode.BAD_REQUEST_400) + .json({ + error: 'You must provide at least one handle or one host.' + }) + } + return next() } ] const removeFollowingValidator = [ - param('host').custom(isHostValid).withMessage('Should have a valid host'), + param('hostOrHandle') + .custom(value => isHostValid(value) || isRemoteHandleValid(value)) + .withMessage('Should have a valid host/handle'), async (req: express.Request, res: express.Response, next: express.NextFunction) => { logger.debug('Checking unfollowing parameters', { parameters: req.params }) @@ -60,12 +79,14 @@ const removeFollowingValidator = [ if (areValidationErrors(req, res)) return const serverActor = await getServerActor() - const follow = await ActorFollowModel.loadByActorAndTargetNameAndHostForAPI(serverActor.id, SERVER_ACTOR_NAME, req.params.host) + + const { name, host } = getRemoteNameAndHost(req.params.hostOrHandle) + const follow = await ActorFollowModel.loadByActorAndTargetNameAndHostForAPI(serverActor.id, name, host) if (!follow) { return res.fail({ status: HttpStatusCode.NOT_FOUND_404, - message: `Following ${req.params.host} not found.` + message: `Follow ${req.params.hostOrHandle} not found.` }) } diff --git a/server/models/actor/actor-follow.ts b/server/models/actor/actor-follow.ts index 3a09e51d6..83c00a22d 100644 --- a/server/models/actor/actor-follow.ts +++ b/server/models/actor/actor-follow.ts @@ -324,13 +324,13 @@ export class ActorFollowModel extends Model s.follows) // Get the access tokens await setAccessTokensToServers(servers) }) - it('Should not have followers', async function () { - for (const server of servers) { - const body = await server.follows.getFollowers({ start: 0, count: 5, sort: 'createdAt' }) - expect(body.total).to.equal(0) - - const follows = body.data - expect(follows).to.be.an('array') - expect(follows.length).to.equal(0) - } - }) + describe('Data propagation after follow', function () { - it('Should not have following', async function () { - for (const server of servers) { - const body = await server.follows.getFollowings({ start: 0, count: 5, sort: 'createdAt' }) - expect(body.total).to.equal(0) + it('Should not have followers/followings', async function () { + for (const server of servers) { + const bodies = await Promise.all([ + server.follows.getFollowers({ start: 0, count: 5, sort: 'createdAt' }), + server.follows.getFollowings({ start: 0, count: 5, sort: 'createdAt' }) + ]) - const follows = body.data - expect(follows).to.be.an('array') - expect(follows.length).to.equal(0) - } - }) + for (const body of bodies) { + expect(body.total).to.equal(0) - it('Should have server 1 following server 2 and 3', async function () { - this.timeout(30000) + const follows = body.data + expect(follows).to.be.an('array') + expect(follows).to.have.lengthOf(0) + } + } + }) - await followsCommands[0].follow({ targets: [ servers[1].url, servers[2].url ] }) + it('Should have server 1 following root account of server 2 and server 3', async function () { + this.timeout(30000) - await waitJobs(servers) - }) + await servers[0].follows.follow({ + hosts: [ servers[2].url ], + handles: [ 'root@' + servers[1].host ] + }) - it('Should have 2 followings on server 1', async function () { - const body = await followsCommands[0].getFollowings({ start: 0, count: 1, sort: 'createdAt' }) - expect(body.total).to.equal(2) + await waitJobs(servers) + }) - let follows = body.data - expect(follows).to.be.an('array') - expect(follows.length).to.equal(1) + it('Should have 2 followings on server 1', async function () { + const body = await servers[0].follows.getFollowings({ start: 0, count: 1, sort: 'createdAt' }) + expect(body.total).to.equal(2) - const body2 = await followsCommands[0].getFollowings({ start: 1, count: 1, sort: 'createdAt' }) - follows = follows.concat(body2.data) + let follows = body.data + expect(follows).to.be.an('array') + expect(follows).to.have.lengthOf(1) - const server2Follow = follows.find(f => f.following.host === 'localhost:' + servers[1].port) - const server3Follow = follows.find(f => f.following.host === 'localhost:' + servers[2].port) + const body2 = await servers[0].follows.getFollowings({ start: 1, count: 1, sort: 'createdAt' }) + follows = follows.concat(body2.data) - expect(server2Follow).to.not.be.undefined - expect(server3Follow).to.not.be.undefined - expect(server2Follow.state).to.equal('accepted') - expect(server3Follow.state).to.equal('accepted') - }) + const server2Follow = follows.find(f => f.following.host === servers[1].host) + const server3Follow = follows.find(f => f.following.host === servers[2].host) - it('Should search/filter followings on server 1', async function () { - const sort = 'createdAt' - const start = 0 - const count = 1 + expect(server2Follow).to.not.be.undefined + expect(server2Follow.following.name).to.equal('root') + expect(server2Follow.state).to.equal('accepted') - { - const search = ':' + servers[1].port + expect(server3Follow).to.not.be.undefined + expect(server3Follow.following.name).to.equal('peertube') + expect(server3Follow.state).to.equal('accepted') + }) - { - const body = await followsCommands[0].getFollowings({ start, count, sort, search }) - expect(body.total).to.equal(1) + it('Should have 0 followings on server 2 and 3', async function () { + for (const server of [ servers[1], servers[2] ]) { + const body = await server.follows.getFollowings({ start: 0, count: 5, sort: 'createdAt' }) + expect(body.total).to.equal(0) const follows = body.data - expect(follows.length).to.equal(1) - expect(follows[0].following.host).to.equal('localhost:' + servers[1].port) + expect(follows).to.be.an('array') + expect(follows).to.have.lengthOf(0) } + }) - { - const body = await followsCommands[0].getFollowings({ start, count, sort, search, state: 'accepted' }) - expect(body.total).to.equal(1) - expect(body.data).to.have.lengthOf(1) + it('Should have 1 followers on server 3', async function () { + const body = await servers[2].follows.getFollowers({ start: 0, count: 1, sort: 'createdAt' }) + expect(body.total).to.equal(1) + + const follows = body.data + expect(follows).to.be.an('array') + expect(follows).to.have.lengthOf(1) + expect(follows[0].follower.host).to.equal('localhost:' + servers[0].port) + }) + + it('Should have 0 followers on server 1 and 2', async function () { + for (const server of [ servers[0], servers[1] ]) { + const body = await server.follows.getFollowers({ start: 0, count: 5, sort: 'createdAt' }) + expect(body.total).to.equal(0) + + const follows = body.data + expect(follows).to.be.an('array') + expect(follows).to.have.lengthOf(0) } + }) + + it('Should search/filter followings on server 1', async function () { + const sort = 'createdAt' + const start = 0 + const count = 1 { - const body = await followsCommands[0].getFollowings({ start, count, sort, search, state: 'accepted', actorType: 'Person' }) - expect(body.total).to.equal(0) - expect(body.data).to.have.lengthOf(0) + const search = ':' + servers[1].port + + { + const body = await servers[0].follows.getFollowings({ start, count, sort, search }) + expect(body.total).to.equal(1) + + const follows = body.data + expect(follows).to.have.lengthOf(1) + expect(follows[0].following.host).to.equal(servers[1].host) + } + + { + const body = await servers[0].follows.getFollowings({ start, count, sort, search, state: 'accepted' }) + expect(body.total).to.equal(1) + expect(body.data).to.have.lengthOf(1) + } + + { + const body = await servers[0].follows.getFollowings({ start, count, sort, search, state: 'accepted', actorType: 'Person' }) + expect(body.total).to.equal(1) + expect(body.data).to.have.lengthOf(1) + } + + { + const body = await servers[0].follows.getFollowings({ + start, + count, + sort, + search, + state: 'accepted', + actorType: 'Application' + }) + expect(body.total).to.equal(0) + expect(body.data).to.have.lengthOf(0) + } + + { + const body = await servers[0].follows.getFollowings({ start, count, sort, search, state: 'pending' }) + expect(body.total).to.equal(0) + expect(body.data).to.have.lengthOf(0) + } } { - const body = await followsCommands[0].getFollowings({ - start, - count, - sort, - search, - state: 'accepted', - actorType: 'Application' - }) + const body = await servers[0].follows.getFollowings({ start, count, sort, search: 'root' }) expect(body.total).to.equal(1) expect(body.data).to.have.lengthOf(1) } { - const body = await followsCommands[0].getFollowings({ start, count, sort, search, state: 'pending' }) + const body = await servers[0].follows.getFollowings({ start, count, sort, search: 'bla' }) expect(body.total).to.equal(0) + expect(body.data).to.have.lengthOf(0) } - } + }) - { - const body = await followsCommands[0].getFollowings({ start, count, sort, search: 'bla' }) - expect(body.total).to.equal(0) + it('Should search/filter followers on server 2', async function () { + const start = 0 + const count = 5 + const sort = 'createdAt' - expect(body.data.length).to.equal(0) - } - }) + { + const search = servers[0].port + '' - it('Should have 0 followings on server 2 and 3', async function () { - for (const server of [ servers[1], servers[2] ]) { - const body = await server.follows.getFollowings({ start: 0, count: 5, sort: 'createdAt' }) - expect(body.total).to.equal(0) + { + const body = await servers[2].follows.getFollowers({ start, count, sort, search }) + expect(body.total).to.equal(1) - const follows = body.data - expect(follows).to.be.an('array') - expect(follows.length).to.equal(0) - } - }) + const follows = body.data + expect(follows).to.have.lengthOf(1) + expect(follows[0].following.host).to.equal(servers[2].host) + } - it('Should have 1 followers on server 2 and 3', async function () { - for (const server of [ servers[1], servers[2] ]) { - const body = await server.follows.getFollowers({ start: 0, count: 1, sort: 'createdAt' }) - expect(body.total).to.equal(1) + { + const body = await servers[2].follows.getFollowers({ start, count, sort, search, state: 'accepted' }) + expect(body.total).to.equal(1) + expect(body.data).to.have.lengthOf(1) + } - const follows = body.data - expect(follows).to.be.an('array') - expect(follows.length).to.equal(1) - expect(follows[0].follower.host).to.equal('localhost:' + servers[0].port) - } - }) + { + const body = await servers[2].follows.getFollowers({ start, count, sort, search, state: 'accepted', actorType: 'Person' }) + expect(body.total).to.equal(0) + expect(body.data).to.have.lengthOf(0) + } - it('Should search/filter followers on server 2', async function () { - const start = 0 - const count = 5 - const sort = 'createdAt' + { + const body = await servers[2].follows.getFollowers({ + start, + count, + sort, + search, + state: 'accepted', + actorType: 'Application' + }) + expect(body.total).to.equal(1) + expect(body.data).to.have.lengthOf(1) + } - { - const search = servers[0].port + '' + { + const body = await servers[2].follows.getFollowers({ start, count, sort, search, state: 'pending' }) + expect(body.total).to.equal(0) + expect(body.data).to.have.lengthOf(0) + } + } { - const body = await followsCommands[2].getFollowers({ start, count, sort, search }) - expect(body.total).to.equal(1) + const body = await servers[2].follows.getFollowers({ start, count, sort, search: 'bla' }) + expect(body.total).to.equal(0) const follows = body.data - expect(follows.length).to.equal(1) - expect(follows[0].following.host).to.equal('localhost:' + servers[2].port) + expect(follows).to.have.lengthOf(0) } + }) - { - const body = await followsCommands[2].getFollowers({ start, count, sort, search, state: 'accepted' }) - expect(body.total).to.equal(1) - expect(body.data).to.have.lengthOf(1) - } + it('Should have the correct follows counts', async function () { + await expectAccountFollows({ server: servers[0], handle: 'peertube@' + servers[0].host, followers: 0, following: 2 }) + await expectAccountFollows({ server: servers[0], handle: 'root@' + servers[1].host, followers: 1, following: 0 }) + await expectAccountFollows({ server: servers[0], handle: 'peertube@' + servers[2].host, followers: 1, following: 0 }) - { - const body = await followsCommands[2].getFollowers({ start, count, sort, search, state: 'accepted', actorType: 'Person' }) - expect(body.total).to.equal(0) - expect(body.data).to.have.lengthOf(0) - } + // Server 2 and 3 does not know server 1 follow another server (there was not a refresh) + await expectAccountFollows({ server: servers[1], handle: 'peertube@' + servers[0].host, followers: 0, following: 1 }) + await expectAccountFollows({ server: servers[1], handle: 'root@' + servers[1].host, followers: 1, following: 0 }) + await expectAccountFollows({ server: servers[1], handle: 'peertube@' + servers[1].host, followers: 0, following: 0 }) - { - const body = await followsCommands[2].getFollowers({ - start, - count, - sort, - search, - state: 'accepted', - actorType: 'Application' - }) - expect(body.total).to.equal(1) - expect(body.data).to.have.lengthOf(1) - } + await expectAccountFollows({ server: servers[2], handle: 'peertube@' + servers[0].host, followers: 0, following: 1 }) + await expectAccountFollows({ server: servers[2], handle: 'peertube@' + servers[2].host, followers: 1, following: 0 }) + }) - { - const body = await followsCommands[2].getFollowers({ start, count, sort, search, state: 'pending' }) - expect(body.total).to.equal(0) - expect(body.data).to.have.lengthOf(0) - } - } + it('Should unfollow server 3 on server 1', async function () { + this.timeout(15000) - { - const body = await followsCommands[2].getFollowers({ start, count, sort, search: 'bla' }) - expect(body.total).to.equal(0) + await servers[0].follows.unfollow({ target: servers[2] }) + + await waitJobs(servers) + }) + + it('Should not follow server 3 on server 1 anymore', async function () { + const body = await servers[0].follows.getFollowings({ start: 0, count: 2, sort: 'createdAt' }) + expect(body.total).to.equal(1) const follows = body.data - expect(follows.length).to.equal(0) - } - }) + expect(follows).to.be.an('array') + expect(follows).to.have.lengthOf(1) - it('Should have 0 followers on server 1', async function () { - const body = await followsCommands[0].getFollowers({ start: 0, count: 5, sort: 'createdAt' }) - expect(body.total).to.equal(0) + expect(follows[0].following.host).to.equal(servers[1].host) + }) - const follows = body.data - expect(follows).to.be.an('array') - expect(follows.length).to.equal(0) - }) + it('Should not have server 1 as follower on server 3 anymore', async function () { + const body = await servers[2].follows.getFollowers({ start: 0, count: 1, sort: 'createdAt' }) + expect(body.total).to.equal(0) - it('Should have the correct follows counts', async function () { - await expectAccountFollows({ server: servers[0], handle: 'peertube@localhost:' + servers[0].port, followers: 0, following: 2 }) - await expectAccountFollows({ server: servers[0], handle: 'peertube@localhost:' + servers[1].port, followers: 1, following: 0 }) - await expectAccountFollows({ server: servers[0], handle: 'peertube@localhost:' + servers[2].port, followers: 1, following: 0 }) + const follows = body.data + expect(follows).to.be.an('array') + expect(follows).to.have.lengthOf(0) + }) - // Server 2 and 3 does not know server 1 follow another server (there was not a refresh) - await expectAccountFollows({ server: servers[1], handle: 'peertube@localhost:' + servers[0].port, followers: 0, following: 1 }) - await expectAccountFollows({ server: servers[1], handle: 'peertube@localhost:' + servers[1].port, followers: 1, following: 0 }) + it('Should have the correct follows counts after the unfollow', async function () { + await expectAccountFollows({ server: servers[0], handle: 'peertube@' + servers[0].host, followers: 0, following: 1 }) + await expectAccountFollows({ server: servers[0], handle: 'root@' + servers[1].host, followers: 1, following: 0 }) + await expectAccountFollows({ server: servers[0], handle: 'peertube@' + servers[2].host, followers: 0, following: 0 }) - await expectAccountFollows({ server: servers[2], handle: 'peertube@localhost:' + servers[0].port, followers: 0, following: 1 }) - await expectAccountFollows({ server: servers[2], handle: 'peertube@localhost:' + servers[2].port, followers: 1, following: 0 }) - }) + await expectAccountFollows({ server: servers[1], handle: 'peertube@' + servers[0].host, followers: 0, following: 1 }) + await expectAccountFollows({ server: servers[1], handle: 'root@' + servers[1].host, followers: 1, following: 0 }) + await expectAccountFollows({ server: servers[1], handle: 'peertube@' + servers[1].host, followers: 0, following: 0 }) - it('Should unfollow server 3 on server 1', async function () { - this.timeout(5000) + await expectAccountFollows({ server: servers[2], handle: 'peertube@' + servers[0].host, followers: 0, following: 0 }) + await expectAccountFollows({ server: servers[2], handle: 'peertube@' + servers[2].host, followers: 0, following: 0 }) + }) - await followsCommands[0].unfollow({ target: servers[2] }) + it('Should upload a video on server 2 and 3 and propagate only the video of server 2', async function () { + this.timeout(60000) - await waitJobs(servers) - }) + await servers[1].videos.upload({ attributes: { name: 'server2' } }) + await servers[2].videos.upload({ attributes: { name: 'server3' } }) - it('Should not follow server 3 on server 1 anymore', async function () { - const body = await followsCommands[0].getFollowings({ start: 0, count: 2, sort: 'createdAt' }) - expect(body.total).to.equal(1) + await waitJobs(servers) - const follows = body.data - expect(follows).to.be.an('array') - expect(follows.length).to.equal(1) + { + const { total, data } = await servers[0].videos.list() + expect(total).to.equal(1) + expect(data[0].name).to.equal('server2') + } - expect(follows[0].following.host).to.equal('localhost:' + servers[1].port) - }) + { + const { total, data } = await servers[1].videos.list() + expect(total).to.equal(1) + expect(data[0].name).to.equal('server2') + } - it('Should not have server 1 as follower on server 3 anymore', async function () { - const body = await followsCommands[2].getFollowers({ start: 0, count: 1, sort: 'createdAt' }) - expect(body.total).to.equal(0) + { + const { total, data } = await servers[2].videos.list() + expect(total).to.equal(1) + expect(data[0].name).to.equal('server3') + } + }) - const follows = body.data - expect(follows).to.be.an('array') - expect(follows.length).to.equal(0) - }) + it('Should remove account follow', async function () { + this.timeout(15000) - it('Should have the correct follows counts 2', async function () { - await expectAccountFollows({ server: servers[0], handle: 'peertube@localhost:' + servers[0].port, followers: 0, following: 1 }) - await expectAccountFollows({ server: servers[0], handle: 'peertube@localhost:' + servers[1].port, followers: 1, following: 0 }) + await servers[0].follows.unfollow({ target: 'root@' + servers[1].host }) - await expectAccountFollows({ server: servers[1], handle: 'peertube@localhost:' + servers[0].port, followers: 0, following: 1 }) - await expectAccountFollows({ server: servers[1], handle: 'peertube@localhost:' + servers[1].port, followers: 1, following: 0 }) + await waitJobs(servers) + }) - await expectAccountFollows({ server: servers[2], handle: 'peertube@localhost:' + servers[0].port, followers: 0, following: 0 }) - await expectAccountFollows({ server: servers[2], handle: 'peertube@localhost:' + servers[2].port, followers: 0, following: 0 }) - }) + it('Should have removed the account follow', async function () { + await expectAccountFollows({ server: servers[0], handle: 'root@' + servers[1].host, followers: 0, following: 0 }) + await expectAccountFollows({ server: servers[1], handle: 'root@' + servers[1].host, followers: 0, following: 0 }) - it('Should upload a video on server 2 and 3 and propagate only the video of server 2', async function () { - this.timeout(60000) + { + const { total, data } = await servers[0].follows.getFollowings() + expect(total).to.equal(0) + expect(data).to.have.lengthOf(0) + } - await servers[1].videos.upload({ attributes: { name: 'server2' } }) - await servers[2].videos.upload({ attributes: { name: 'server3' } }) + { + const { total, data } = await servers[0].videos.list() + expect(total).to.equal(0) + expect(data).to.have.lengthOf(0) + } + }) - await waitJobs(servers) + it('Should follow a channel', async function () { + this.timeout(15000) - { - const { total, data } = await servers[0].videos.list() - expect(total).to.equal(1) - expect(data[0].name).to.equal('server2') - } + await servers[0].follows.follow({ + handles: [ 'root_channel@' + servers[1].host ] + }) - { - const { total, data } = await servers[1].videos.list() - expect(total).to.equal(1) - expect(data[0].name).to.equal('server2') - } + await waitJobs(servers) - { - const { total, data } = await servers[2].videos.list() - expect(total).to.equal(1) - expect(data[0].name).to.equal('server3') - } + await expectChannelsFollows({ server: servers[0], handle: 'root_channel@' + servers[1].host, followers: 1, following: 0 }) + await expectChannelsFollows({ server: servers[1], handle: 'root_channel@' + servers[1].host, followers: 1, following: 0 }) + + { + const { total, data } = await servers[0].follows.getFollowings() + expect(total).to.equal(1) + expect(data).to.have.lengthOf(1) + } + + { + const { total, data } = await servers[0].videos.list() + expect(total).to.equal(1) + expect(data).to.have.lengthOf(1) + } + }) }) - describe('Should propagate data on a new following', function () { - let video4: Video + describe('Should propagate data on a new server follow', function () { + let video4: VideoCreateResult before(async function () { this.timeout(50000) @@ -324,83 +385,64 @@ describe('Test follows', function () { await servers[2].videos.upload({ attributes: { name: 'server3-2' } }) await servers[2].videos.upload({ attributes: { name: 'server3-3' } }) - await servers[2].videos.upload({ attributes: video4Attributes }) + video4 = await servers[2].videos.upload({ attributes: video4Attributes }) await servers[2].videos.upload({ attributes: { name: 'server3-5' } }) await servers[2].videos.upload({ attributes: { name: 'server3-6' } }) { const userAccessToken = await servers[2].users.generateUserAndToken('captain') - const { data } = await servers[2].videos.list() - video4 = data.find(v => v.name === 'server3-4') - - { - await servers[2].videos.rate({ id: video4.id, rating: 'like' }) - await servers[2].videos.rate({ token: userAccessToken, id: video4.id, rating: 'dislike' }) - } - - { - { - const text = 'my super first comment' - const created = await servers[2].comments.createThread({ videoId: video4.id, text }) - const threadId = created.id - - const text1 = 'my super answer to thread 1' - const childComment = await servers[2].comments.addReply({ videoId: video4.id, toCommentId: threadId, text: text1 }) - - const text2 = 'my super answer to answer of thread 1' - await servers[2].comments.addReply({ videoId: video4.id, toCommentId: childComment.id, text: text2 }) - - const text3 = 'my second answer to thread 1' - await servers[2].comments.addReply({ videoId: video4.id, toCommentId: threadId, text: text3 }) - } + await servers[2].videos.rate({ id: video4.id, rating: 'like' }) + await servers[2].videos.rate({ token: userAccessToken, id: video4.id, rating: 'dislike' }) + } - { - const text = 'will be deleted' - const created = await servers[2].comments.createThread({ videoId: video4.id, text }) - const threadId = created.id + { + await servers[2].comments.createThread({ videoId: video4.id, text: 'my super first comment' }) - const text1 = 'answer to deleted' - await servers[2].comments.addReply({ videoId: video4.id, toCommentId: threadId, text: text1 }) + await servers[2].comments.addReplyToLastThread({ text: 'my super answer to thread 1' }) + await servers[2].comments.addReplyToLastReply({ text: 'my super answer to answer of thread 1' }) + await servers[2].comments.addReplyToLastThread({ text: 'my second answer to thread 1' }) + } - const text2 = 'will also be deleted' - const childComment = await servers[2].comments.addReply({ videoId: video4.id, toCommentId: threadId, text: text2 }) + { + const { id: threadId } = await servers[2].comments.createThread({ videoId: video4.id, text: 'will be deleted' }) + await servers[2].comments.addReplyToLastThread({ text: 'answer to deleted' }) - const text3 = 'my second answer to deleted' - await servers[2].comments.addReply({ videoId: video4.id, toCommentId: childComment.id, text: text3 }) + const { id: replyId } = await servers[2].comments.addReplyToLastThread({ text: 'will also be deleted' }) - await servers[2].comments.delete({ videoId: video4.id, commentId: threadId }) - await servers[2].comments.delete({ videoId: video4.id, commentId: childComment.id }) - } - } + await servers[2].comments.addReplyToLastReply({ text: 'my second answer to deleted' }) - { - await servers[2].captions.createVideoCaption({ - language: 'ar', - videoId: video4.id, - fixture: 'subtitle-good2.vtt' - }) - } + await servers[2].comments.delete({ videoId: video4.id, commentId: threadId }) + await servers[2].comments.delete({ videoId: video4.id, commentId: replyId }) } + await servers[2].captions.createVideoCaption({ + language: 'ar', + videoId: video4.id, + fixture: 'subtitle-good2.vtt' + }) + await waitJobs(servers) // Server 1 follows server 3 - await followsCommands[0].follow({ targets: [ servers[2].url ] }) + await servers[0].follows.follow({ hosts: [ servers[2].url ] }) await waitJobs(servers) }) - it('Should have the correct follows counts 3', async function () { - await expectAccountFollows({ server: servers[0], handle: 'peertube@localhost:' + servers[0].port, followers: 0, following: 2 }) - await expectAccountFollows({ server: servers[0], handle: 'peertube@localhost:' + servers[1].port, followers: 1, following: 0 }) - await expectAccountFollows({ server: servers[0], handle: 'peertube@localhost:' + servers[2].port, followers: 1, following: 0 }) + it('Should have the correct follows counts', async function () { + await expectAccountFollows({ server: servers[0], handle: 'peertube@' + servers[0].host, followers: 0, following: 2 }) + await expectAccountFollows({ server: servers[0], handle: 'root@' + servers[1].host, followers: 0, following: 0 }) + await expectChannelsFollows({ server: servers[0], handle: 'root_channel@' + servers[1].host, followers: 1, following: 0 }) + await expectAccountFollows({ server: servers[0], handle: 'peertube@' + servers[2].host, followers: 1, following: 0 }) - await expectAccountFollows({ server: servers[1], handle: 'peertube@localhost:' + servers[0].port, followers: 0, following: 1 }) - await expectAccountFollows({ server: servers[1], handle: 'peertube@localhost:' + servers[1].port, followers: 1, following: 0 }) + await expectAccountFollows({ server: servers[1], handle: 'peertube@' + servers[0].host, followers: 0, following: 1 }) + await expectAccountFollows({ server: servers[1], handle: 'peertube@' + servers[1].host, followers: 0, following: 0 }) + await expectAccountFollows({ server: servers[1], handle: 'root@' + servers[1].host, followers: 0, following: 0 }) + await expectChannelsFollows({ server: servers[1], handle: 'root_channel@' + servers[1].host, followers: 1, following: 0 }) - await expectAccountFollows({ server: servers[2], handle: 'peertube@localhost:' + servers[0].port, followers: 0, following: 1 }) - await expectAccountFollows({ server: servers[2], handle: 'peertube@localhost:' + servers[2].port, followers: 1, following: 0 }) + await expectAccountFollows({ server: servers[2], handle: 'peertube@' + servers[0].host, followers: 0, following: 1 }) + await expectAccountFollows({ server: servers[2], handle: 'peertube@' + servers[2].host, followers: 1, following: 0 }) }) it('Should have propagated videos', async function () { @@ -426,7 +468,7 @@ describe('Test follows', function () { support: 'my super support text', account: { name: 'root', - host: 'localhost:' + servers[2].port + host: servers[2].host }, isLocal, commentsEnabled: true, @@ -467,7 +509,7 @@ describe('Test follows', function () { expect(comment.videoId).to.equal(video4.id) expect(comment.id).to.equal(comment.threadId) expect(comment.account.name).to.equal('root') - expect(comment.account.host).to.equal('localhost:' + servers[2].port) + expect(comment.account.host).to.equal(servers[2].host) expect(comment.totalReplies).to.equal(3) expect(dateIsValid(comment.createdAt as string)).to.be.true expect(dateIsValid(comment.updatedAt as string)).to.be.true @@ -541,14 +583,39 @@ describe('Test follows', function () { it('Should unfollow server 3 on server 1 and does not list server 3 videos', async function () { this.timeout(5000) - await followsCommands[0].unfollow({ target: servers[2] }) + await servers[0].follows.unfollow({ target: servers[2] }) await waitJobs(servers) const { total } = await servers[0].videos.list() expect(total).to.equal(1) }) + }) + + describe('Should propagate data on a new channel follow', function () { + + before(async function () { + this.timeout(60000) + await servers[2].videos.upload({ attributes: { name: 'server3-7' } }) + + await waitJobs(servers) + + const video = await servers[0].videos.find({ name: 'server3-7' }) + expect(video).to.not.exist + }) + + it('Should have propagated channel video', async function () { + this.timeout(60000) + + await servers[0].follows.follow({ handles: [ 'root_channel@' + servers[2].host ] }) + + await waitJobs(servers) + + const video = await servers[0].videos.find({ name: 'server3-7' }) + + expect(video).to.exist + }) }) after(async function () { diff --git a/server/tests/api/server/handle-down.ts b/server/tests/api/server/handle-down.ts index 1f751c957..2f3950354 100644 --- a/server/tests/api/server/handle-down.ts +++ b/server/tests/api/server/handle-down.ts @@ -97,8 +97,8 @@ describe('Test handle downs', function () { this.timeout(240000) // Server 2 and 3 follow server 1 - await servers[1].follows.follow({ targets: [ servers[0].url ] }) - await servers[2].follows.follow({ targets: [ servers[0].url ] }) + await servers[1].follows.follow({ hosts: [ servers[0].url ] }) + await servers[2].follows.follow({ hosts: [ servers[0].url ] }) await waitJobs(servers) @@ -180,7 +180,7 @@ describe('Test handle downs', function () { await servers[1].follows.unfollow({ target: servers[0] }) await waitJobs(servers) - await servers[1].follows.follow({ targets: [ servers[0].url ] }) + await servers[1].follows.follow({ hosts: [ servers[0].url ] }) await waitJobs(servers) diff --git a/server/tests/api/server/stats.ts b/server/tests/api/server/stats.ts index 942602b70..5ec771429 100644 --- a/server/tests/api/server/stats.ts +++ b/server/tests/api/server/stats.ts @@ -43,7 +43,7 @@ describe('Test stats (excluding redundancy)', function () { // Wait the video views repeatable job await wait(8000) - await servers[2].follows.follow({ targets: [ servers[0].url ] }) + await servers[2].follows.follow({ hosts: [ servers[0].url ] }) await waitJobs(servers) }) diff --git a/server/tests/api/users/user-subscriptions.ts b/server/tests/api/users/user-subscriptions.ts index 565b4bd77..77b99886d 100644 --- a/server/tests/api/users/user-subscriptions.ts +++ b/server/tests/api/users/user-subscriptions.ts @@ -224,7 +224,7 @@ describe('Test users subscriptions', function () { it('Should have server 1 follow server 3 and display server 3 videos', async function () { this.timeout(60000) - await servers[0].follows.follow({ targets: [ servers[2].url ] }) + await servers[0].follows.follow({ hosts: [ servers[2].url ] }) await waitJobs(servers) diff --git a/server/tests/api/users/users.ts b/server/tests/api/users/users.ts index 066da88ee..1419ae820 100644 --- a/server/tests/api/users/users.ts +++ b/server/tests/api/users/users.ts @@ -103,7 +103,7 @@ describe('Test users', function () { token = 'my_super_token' await server.follows.follow({ - targets: [ 'http://example.com' ], + hosts: [ 'http://example.com' ], token, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) diff --git a/shared/extra-utils/server/follows-command.ts b/shared/extra-utils/server/follows-command.ts index dce674ac5..2b889cf66 100644 --- a/shared/extra-utils/server/follows-command.ts +++ b/shared/extra-utils/server/follows-command.ts @@ -1,5 +1,5 @@ import { pick } from 'lodash' -import { ActivityPubActorType, ActorFollow, FollowState, HttpStatusCode, ResultList } from '@shared/models' +import { ActivityPubActorType, ActorFollow, FollowState, HttpStatusCode, ResultList, ServerFollowCreate } from '@shared/models' import { AbstractCommand, OverrideCommandOptions } from '../shared' import { PeerTubeServer } from './server' @@ -29,13 +29,13 @@ export class FollowsCommand extends AbstractCommand { } getFollowings (options: OverrideCommandOptions & { - start: number - count: number - sort: string + start?: number + count?: number + sort?: string search?: string actorType?: ActivityPubActorType state?: FollowState - }) { + } = {}) { const path = '/api/v1/server/following' const toPick = [ 'start', 'count', 'sort', 'search', 'state', 'actorType' ] @@ -52,26 +52,41 @@ export class FollowsCommand extends AbstractCommand { } follow (options: OverrideCommandOptions & { - targets: string[] + hosts?: string[] + handles?: string[] }) { const path = '/api/v1/server/following' - const hosts = options.targets.map(f => f.replace(/^http:\/\//, '')) + const fields: ServerFollowCreate = {} + + if (options.hosts) { + fields.hosts = options.hosts.map(f => f.replace(/^http:\/\//, '')) + } + + if (options.handles) { + fields.handles = options.handles + } return this.postBodyRequest({ ...options, path, - fields: { hosts }, + fields, implicitToken: true, defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 }) } async unfollow (options: OverrideCommandOptions & { - target: PeerTubeServer + target: PeerTubeServer | string }) { - const path = '/api/v1/server/following/' + options.target.host + const { target } = options + + const handle = typeof target === 'string' + ? target + : target.host + + const path = '/api/v1/server/following/' + handle return this.deleteRequest({ ...options, diff --git a/shared/extra-utils/server/follows.ts b/shared/extra-utils/server/follows.ts index 0188be1aa..698238f29 100644 --- a/shared/extra-utils/server/follows.ts +++ b/shared/extra-utils/server/follows.ts @@ -3,8 +3,8 @@ import { PeerTubeServer } from './server' async function doubleFollow (server1: PeerTubeServer, server2: PeerTubeServer) { await Promise.all([ - server1.follows.follow({ targets: [ server2.url ] }), - server2.follows.follow({ targets: [ server1.url ] }) + server1.follows.follow({ hosts: [ server2.url ] }), + server2.follows.follow({ hosts: [ server1.url ] }) ]) // Wait request propagation diff --git a/shared/extra-utils/users/accounts.ts b/shared/extra-utils/users/accounts.ts deleted file mode 100644 index 9fc1bcfc4..000000000 --- a/shared/extra-utils/users/accounts.ts +++ /dev/null @@ -1,44 +0,0 @@ -/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ - -import { expect } from 'chai' -import { pathExists, readdir } from 'fs-extra' -import { join } from 'path' -import { root } from '@server/helpers/core-utils' -import { PeerTubeServer } from '../server' - -async function expectAccountFollows (options: { - server: PeerTubeServer - handle: string - followers: number - following: number -}) { - const { server, handle, followers, following } = options - - const body = await server.accounts.list() - const account = body.data.find(a => a.name + '@' + a.host === handle) - - const message = `${handle} on ${server.url}` - expect(account.followersCount).to.equal(followers, message) - expect(account.followingCount).to.equal(following, message) -} - -async function checkActorFilesWereRemoved (filename: string, serverNumber: number) { - const testDirectory = 'test' + serverNumber - - for (const directory of [ 'avatars' ]) { - const directoryPath = join(root(), testDirectory, directory) - - const directoryExists = await pathExists(directoryPath) - expect(directoryExists).to.be.true - - const files = await readdir(directoryPath) - for (const file of files) { - expect(file).to.not.contain(filename) - } - } -} - -export { - expectAccountFollows, - checkActorFilesWereRemoved -} diff --git a/shared/extra-utils/users/actors.ts b/shared/extra-utils/users/actors.ts new file mode 100644 index 000000000..cfcc7d0a7 --- /dev/null +++ b/shared/extra-utils/users/actors.ts @@ -0,0 +1,73 @@ +/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ + +import { expect } from 'chai' +import { pathExists, readdir } from 'fs-extra' +import { join } from 'path' +import { root } from '@server/helpers/core-utils' +import { Account, VideoChannel } from '@shared/models' +import { PeerTubeServer } from '../server' + +async function expectChannelsFollows (options: { + server: PeerTubeServer + handle: string + followers: number + following: number +}) { + const { server } = options + const { data } = await server.channels.list() + + return expectActorFollow({ ...options, data }) +} + +async function expectAccountFollows (options: { + server: PeerTubeServer + handle: string + followers: number + following: number +}) { + const { server } = options + const { data } = await server.accounts.list() + + return expectActorFollow({ ...options, data }) +} + +async function checkActorFilesWereRemoved (filename: string, serverNumber: number) { + const testDirectory = 'test' + serverNumber + + for (const directory of [ 'avatars' ]) { + const directoryPath = join(root(), testDirectory, directory) + + const directoryExists = await pathExists(directoryPath) + expect(directoryExists).to.be.true + + const files = await readdir(directoryPath) + for (const file of files) { + expect(file).to.not.contain(filename) + } + } +} + +export { + expectAccountFollows, + expectChannelsFollows, + checkActorFilesWereRemoved +} + +// --------------------------------------------------------------------------- + +function expectActorFollow (options: { + server: PeerTubeServer + data: (Account | VideoChannel)[] + handle: string + followers: number + following: number +}) { + const { server, data, handle, followers, following } = options + + const actor = data.find(a => a.name + '@' + a.host === handle) + const message = `${handle} on ${server.url}` + + expect(actor, message).to.exist + expect(actor.followersCount).to.equal(followers, message) + expect(actor.followingCount).to.equal(following, message) +} diff --git a/shared/extra-utils/users/index.ts b/shared/extra-utils/users/index.ts index fbb454e8f..460a06f70 100644 --- a/shared/extra-utils/users/index.ts +++ b/shared/extra-utils/users/index.ts @@ -1,5 +1,5 @@ export * from './accounts-command' -export * from './accounts' +export * from './actors' export * from './blocklist-command' export * from './login' export * from './login-command' diff --git a/shared/extra-utils/videos/comments-command.ts b/shared/extra-utils/videos/comments-command.ts index dd14e4b64..5034c57ad 100644 --- a/shared/extra-utils/videos/comments-command.ts +++ b/shared/extra-utils/videos/comments-command.ts @@ -5,6 +5,10 @@ import { AbstractCommand, OverrideCommandOptions } from '../shared' export class CommentsCommand extends AbstractCommand { + private lastVideoId: number | string + private lastThreadId: number + private lastReplyId: number + listForAdmin (options: OverrideCommandOptions & { start?: number count?: number @@ -80,6 +84,9 @@ export class CommentsCommand extends AbstractCommand { defaultExpectedStatus: HttpStatusCode.OK_200 })) + this.lastThreadId = body.comment.id + this.lastVideoId = videoId + return body.comment } @@ -100,9 +107,23 @@ export class CommentsCommand extends AbstractCommand { defaultExpectedStatus: HttpStatusCode.OK_200 })) + this.lastReplyId = body.comment.id + return body.comment } + async addReplyToLastReply (options: OverrideCommandOptions & { + text: string + }) { + return this.addReply({ ...options, videoId: this.lastVideoId, toCommentId: this.lastReplyId }) + } + + async addReplyToLastThread (options: OverrideCommandOptions & { + text: string + }) { + return this.addReply({ ...options, videoId: this.lastVideoId, toCommentId: this.lastThreadId }) + } + async findCommentId (options: OverrideCommandOptions & { videoId: number | string text: string diff --git a/shared/extra-utils/videos/videos-command.ts b/shared/extra-utils/videos/videos-command.ts index 40cc4dc28..98465e8f6 100644 --- a/shared/extra-utils/videos/videos-command.ts +++ b/shared/extra-utils/videos/videos-command.ts @@ -267,6 +267,16 @@ export class VideosCommand extends AbstractCommand { // --------------------------------------------------------------------------- + async find (options: OverrideCommandOptions & { + name: string + }) { + const { data } = await this.list(options) + + return data.find(v => v.name === options.name) + } + + // --------------------------------------------------------------------------- + update (options: OverrideCommandOptions & { id: number | string attributes?: VideoEdit diff --git a/shared/models/server/index.ts b/shared/models/server/index.ts index 06bf5c599..0f7646c7a 100644 --- a/shared/models/server/index.ts +++ b/shared/models/server/index.ts @@ -10,4 +10,5 @@ export * from './peertube-problem-document.model' export * from './server-config.model' export * from './server-debug.model' export * from './server-error-code.enum' +export * from './server-follow-create.model' export * from './server-stats.model' diff --git a/shared/models/server/server-follow-create.model.ts b/shared/models/server/server-follow-create.model.ts new file mode 100644 index 000000000..3f90c7d6f --- /dev/null +++ b/shared/models/server/server-follow-create.model.ts @@ -0,0 +1,4 @@ +export interface ServerFollowCreate { + hosts?: string[] + handles?: string[] +} diff --git a/support/doc/api/openapi.yaml b/support/doc/api/openapi.yaml index 99a725ead..76e78fe53 100644 --- a/support/doc/api/openapi.yaml +++ b/support/doc/api/openapi.yaml @@ -716,7 +716,7 @@ paths: - admin tags: - Instance Follows - summary: Follow a list of servers + summary: Follow a list of actors (PeerTube instance, channel or account) responses: '204': description: successful operation @@ -734,28 +734,32 @@ paths: type: string format: hostname uniqueItems: true + handles: + type: array + items: + type: string + uniqueItems: true - '/server/following/{host}': + '/server/following/{hostOrHandle}': delete: - summary: Unfollow a server + summary: Unfollow an actor (PeerTube instance, channel or account) security: - OAuth2: - admin tags: - Instance Follows parameters: - - name: host + - name: hostOrHandle in: path required: true - description: The host to unfollow + description: The hostOrHandle to unfollow schema: type: string - format: hostname responses: '204': description: successful operation '404': - description: host not found + description: host or handle not found /users: post: -- cgit v1.2.3 From c63830f15403ac4e750829f27d8bbbdc9a59282c Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Wed, 21 Jul 2021 13:58:35 +0200 Subject: Rename captions commands --- client/src/app/shared/form-validators/index.ts | 2 +- scripts/benchmark.ts | 2 +- server/tests/api/check-params/video-captions.ts | 2 +- server/tests/api/search/search-videos.ts | 4 ++-- server/tests/api/server/follows.ts | 4 ++-- server/tests/api/videos/video-captions.ts | 20 ++++++++++---------- server/tests/api/videos/video-imports.ts | 6 +++--- shared/extra-utils/videos/captions-command.ts | 6 +++--- shared/extra-utils/videos/comments-command.ts | 4 ++-- 9 files changed, 25 insertions(+), 25 deletions(-) diff --git a/client/src/app/shared/form-validators/index.ts b/client/src/app/shared/form-validators/index.ts index c14272a2a..0b605719c 100644 --- a/client/src/app/shared/form-validators/index.ts +++ b/client/src/app/shared/form-validators/index.ts @@ -1,6 +1,6 @@ export * from './form-validator.model' -// Don't re export const variables because webpack 4 cannot do tree shaking with them +// Don't re export const variables because webpack cannot do tree shaking with them // export * from './abuse-validators' // export * from './batch-domains-validators' // export * from './custom-config-validators' diff --git a/scripts/benchmark.ts b/scripts/benchmark.ts index 071c4dea7..83b932909 100644 --- a/scripts/benchmark.ts +++ b/scripts/benchmark.ts @@ -232,7 +232,7 @@ async function prepare () { } for (const caption of [ 'ar', 'fr', 'en', 'zh' ]) { - await server.captions.createVideoCaption({ + await server.captions.add({ language: caption, videoId: video.id, fixture: 'subtitle-good2.vtt' diff --git a/server/tests/api/check-params/video-captions.ts b/server/tests/api/check-params/video-captions.ts index 5aaeb27fe..90f429314 100644 --- a/server/tests/api/check-params/video-captions.ts +++ b/server/tests/api/check-params/video-captions.ts @@ -151,7 +151,7 @@ describe('Test video captions API validator', function () { // }) it('Should succeed with a valid captionfile extension and octet-stream mime type', async function () { - await server.captions.createVideoCaption({ + await server.captions.add({ language: 'zh', videoId: video.uuid, fixture: 'subtitle-good.srt', diff --git a/server/tests/api/search/search-videos.ts b/server/tests/api/search/search-videos.ts index f834c7f36..965766742 100644 --- a/server/tests/api/search/search-videos.ts +++ b/server/tests/api/search/search-videos.ts @@ -50,14 +50,14 @@ describe('Test videos search', function () { const { id, uuid } = await server.videos.upload({ attributes: attributes3 }) videoUUID = uuid - await server.captions.createVideoCaption({ + await server.captions.add({ language: 'en', videoId: id, fixture: 'subtitle-good2.vtt', mimeType: 'application/octet-stream' }) - await server.captions.createVideoCaption({ + await server.captions.add({ language: 'aa', videoId: id, fixture: 'subtitle-good2.vtt', diff --git a/server/tests/api/server/follows.ts b/server/tests/api/server/follows.ts index a616edcff..832ba561a 100644 --- a/server/tests/api/server/follows.ts +++ b/server/tests/api/server/follows.ts @@ -416,7 +416,7 @@ describe('Test follows', function () { await servers[2].comments.delete({ videoId: video4.id, commentId: replyId }) } - await servers[2].captions.createVideoCaption({ + await servers[2].captions.add({ language: 'ar', videoId: video4.id, fixture: 'subtitle-good2.vtt' @@ -569,7 +569,7 @@ describe('Test follows', function () { }) it('Should have propagated captions', async function () { - const body = await servers[0].captions.listVideoCaptions({ videoId: video4.id }) + const body = await servers[0].captions.list({ videoId: video4.id }) expect(body.total).to.equal(1) expect(body.data).to.have.lengthOf(1) diff --git a/server/tests/api/videos/video-captions.ts b/server/tests/api/videos/video-captions.ts index e3d46e619..4c8e28adf 100644 --- a/server/tests/api/videos/video-captions.ts +++ b/server/tests/api/videos/video-captions.ts @@ -40,7 +40,7 @@ describe('Test video captions', function () { it('Should list the captions and return an empty list', async function () { for (const server of servers) { - const body = await server.captions.listVideoCaptions({ videoId: videoUUID }) + const body = await server.captions.list({ videoId: videoUUID }) expect(body.total).to.equal(0) expect(body.data).to.have.lengthOf(0) } @@ -49,13 +49,13 @@ describe('Test video captions', function () { it('Should create two new captions', async function () { this.timeout(30000) - await servers[0].captions.createVideoCaption({ + await servers[0].captions.add({ language: 'ar', videoId: videoUUID, fixture: 'subtitle-good1.vtt' }) - await servers[0].captions.createVideoCaption({ + await servers[0].captions.add({ language: 'zh', videoId: videoUUID, fixture: 'subtitle-good2.vtt', @@ -67,7 +67,7 @@ describe('Test video captions', function () { it('Should list these uploaded captions', async function () { for (const server of servers) { - const body = await server.captions.listVideoCaptions({ videoId: videoUUID }) + const body = await server.captions.list({ videoId: videoUUID }) expect(body.total).to.equal(2) expect(body.data).to.have.lengthOf(2) @@ -88,7 +88,7 @@ describe('Test video captions', function () { it('Should replace an existing caption', async function () { this.timeout(30000) - await servers[0].captions.createVideoCaption({ + await servers[0].captions.add({ language: 'ar', videoId: videoUUID, fixture: 'subtitle-good2.vtt' @@ -99,7 +99,7 @@ describe('Test video captions', function () { it('Should have this caption updated', async function () { for (const server of servers) { - const body = await server.captions.listVideoCaptions({ videoId: videoUUID }) + const body = await server.captions.list({ videoId: videoUUID }) expect(body.total).to.equal(2) expect(body.data).to.have.lengthOf(2) @@ -114,7 +114,7 @@ describe('Test video captions', function () { it('Should replace an existing caption with a srt file and convert it', async function () { this.timeout(30000) - await servers[0].captions.createVideoCaption({ + await servers[0].captions.add({ language: 'ar', videoId: videoUUID, fixture: 'subtitle-good.srt' @@ -128,7 +128,7 @@ describe('Test video captions', function () { it('Should have this caption updated and converted', async function () { for (const server of servers) { - const body = await server.captions.listVideoCaptions({ videoId: videoUUID }) + const body = await server.captions.list({ videoId: videoUUID }) expect(body.total).to.equal(2) expect(body.data).to.have.lengthOf(2) @@ -157,14 +157,14 @@ describe('Test video captions', function () { it('Should remove one caption', async function () { this.timeout(30000) - await servers[0].captions.deleteVideoCaption({ videoId: videoUUID, language: 'ar' }) + await servers[0].captions.delete({ videoId: videoUUID, language: 'ar' }) await waitJobs(servers) }) it('Should only list the caption that was not deleted', async function () { for (const server of servers) { - const body = await server.captions.listVideoCaptions({ videoId: videoUUID }) + const body = await server.captions.list({ videoId: videoUUID }) expect(body.total).to.equal(1) expect(body.data).to.have.lengthOf(1) diff --git a/server/tests/api/videos/video-imports.ts b/server/tests/api/videos/video-imports.ts index 192f5232e..2eac130d2 100644 --- a/server/tests/api/videos/video-imports.ts +++ b/server/tests/api/videos/video-imports.ts @@ -59,7 +59,7 @@ describe('Test video imports', function () { expect(videoTorrent.name).to.contain('你好 世界 720p.mp4') expect(videoMagnet.name).to.contain('super peertube2 video') - const bodyCaptions = await server.captions.listVideoCaptions({ videoId: idHttp }) + const bodyCaptions = await server.captions.list({ videoId: idHttp }) expect(bodyCaptions.total).to.equal(2) } @@ -76,7 +76,7 @@ describe('Test video imports', function () { expect(video.files).to.have.lengthOf(1) - const bodyCaptions = await server.captions.listVideoCaptions({ videoId: id }) + const bodyCaptions = await server.captions.list({ videoId: id }) expect(bodyCaptions.total).to.equal(2) } @@ -120,7 +120,7 @@ describe('Test video imports', function () { await testImage(servers[0].url, 'video_import_thumbnail', video.thumbnailPath) await testImage(servers[0].url, 'video_import_preview', video.previewPath) - const bodyCaptions = await servers[0].captions.listVideoCaptions({ videoId: video.id }) + const bodyCaptions = await servers[0].captions.list({ videoId: video.id }) const videoCaptions = bodyCaptions.data expect(videoCaptions).to.have.lengthOf(2) diff --git a/shared/extra-utils/videos/captions-command.ts b/shared/extra-utils/videos/captions-command.ts index a0608e1a6..a65ea99e3 100644 --- a/shared/extra-utils/videos/captions-command.ts +++ b/shared/extra-utils/videos/captions-command.ts @@ -4,7 +4,7 @@ import { AbstractCommand, OverrideCommandOptions } from '../shared' export class CaptionsCommand extends AbstractCommand { - createVideoCaption (options: OverrideCommandOptions & { + add (options: OverrideCommandOptions & { videoId: string | number language: string fixture: string @@ -32,7 +32,7 @@ export class CaptionsCommand extends AbstractCommand { }) } - listVideoCaptions (options: OverrideCommandOptions & { + list (options: OverrideCommandOptions & { videoId: string | number }) { const { videoId } = options @@ -47,7 +47,7 @@ export class CaptionsCommand extends AbstractCommand { }) } - deleteVideoCaption (options: OverrideCommandOptions & { + delete (options: OverrideCommandOptions & { videoId: string | number language: string }) { diff --git a/shared/extra-utils/videos/comments-command.ts b/shared/extra-utils/videos/comments-command.ts index 5034c57ad..f0d163a07 100644 --- a/shared/extra-utils/videos/comments-command.ts +++ b/shared/extra-utils/videos/comments-command.ts @@ -84,7 +84,7 @@ export class CommentsCommand extends AbstractCommand { defaultExpectedStatus: HttpStatusCode.OK_200 })) - this.lastThreadId = body.comment.id + this.lastThreadId = body.comment?.id this.lastVideoId = videoId return body.comment @@ -107,7 +107,7 @@ export class CommentsCommand extends AbstractCommand { defaultExpectedStatus: HttpStatusCode.OK_200 })) - this.lastReplyId = body.comment.id + this.lastReplyId = body.comment?.id return body.comment } -- cgit v1.2.3