- {{ formErrors.domains }}
+
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/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;
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/scripts/benchmark.ts b/scripts/benchmark.ts
index 0cadb36d9..83b932909 100644
--- a/scripts/benchmark.ts
+++ b/scripts/benchmark.ts
@@ -1,22 +1,12 @@
+import * as autocannon from 'autocannon'
+import { writeJson } from 'fs-extra'
+import { createSingleServer, killallServers, PeerTubeServer, setAccessTokensToServers } from '@shared/extra-utils'
+import { Video, VideoPrivacy } from '@shared/models'
import { registerTSPaths } from '../server/helpers/register-ts-paths'
+
registerTSPaths()
-import * as autocannon from 'autocannon'
-import {
- addVideoCommentReply,
- addVideoCommentThread,
- createVideoCaption,
- flushAndRunServer,
- getVideosList,
- killallServers,
- ServerInfo,
- setAccessTokensToServers,
- uploadVideo
-} from '@shared/extra-utils'
-import { Video, VideoPrivacy } from '@shared/models'
-import { writeJson } from 'fs-extra'
-
-let server: ServerInfo
+let server: PeerTubeServer
let video: Video
let threadId: number
@@ -25,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 () {
@@ -198,7 +188,7 @@ function runBenchmark (options: {
}
async function prepare () {
- server = await flushAndRunServer(1, {
+ server = await createSingleServer(1, {
rates_limit: {
api: {
max: 5_000_000
@@ -207,7 +197,7 @@ async function prepare () {
})
await setAccessTokensToServers([ server ])
- const videoAttributes = {
+ const attributes = {
name: 'my super video',
category: 2,
nsfw: true,
@@ -220,33 +210,29 @@ 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.videos.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.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 res = await addVideoCommentThread(server.url, server.accessToken, video.id, text)
- threadId = res.body.comment.id
+ const created = await server.comments.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.comments.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.comments.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.comments.addReply({ videoId: video.id, toCommentId: threadId, text: text3 })
}
for (const caption of [ 'ar', 'fr', 'en', 'zh' ]) {
- await createVideoCaption({
- url: server.url,
- accessToken: server.accessToken,
+ await server.captions.add({
language: caption,
videoId: video.id,
fixture: 'subtitle-good2.vtt'
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.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..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 { HttpStatusCode } from '@shared/models'
import { BulkRemoveCommentsOfBody } from '@shared/models/bulk/bulk-remove-comments-of-body.model'
-import { HttpStatusCode } from '@shared/core-utils/miscs/http-error-codes'
+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 c19f03c56..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/core-utils'
-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/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/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 { buildNSFWFilter } from '../../helpers/express-utils'
-import { VideoModel } from '../../models/video/video'
-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 { CategoryOverview, ChannelOverview, TagOverview, VideosOverview } from '../../../shared/models/overviews'
+import { buildNSFWFilter } from '../../helpers/express-utils'
+import { MEMOIZE_TTL, OVERVIEWS } from '../../initializers/constants'
+import { asyncMiddleware, optionalAuthenticate, videosOverviewValidator } from '../../middlewares'
+import { TagModel } from '../../models/video/tag'
+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 1e6a02c49..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/core-utils'
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 16beeed60..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/core-utils/miscs/http-error-codes'
-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 b231ff1e2..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/core-utils'
-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 b626baa28..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/core-utils/miscs/http-error-codes'
-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 caddc0909..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 { HttpStatusCode } from '../../../../shared/models/http/http-error-codes'
import { ContactForm } from '../../../../shared/models/server'
-import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
+import { Emailer } from '../../../lib/emailer'
+import { Redis } from '../../../lib/redis'
+import { asyncMiddleware, contactAdministratorValidator } from '../../../middlewares'
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 a6e9147f3..0601b89ce 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 { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
-import { SendDebugCommand } from '@shared/models'
-import * as express from 'express'
+import { Debug, SendDebugCommand } from '@shared/models'
+import { HttpStatusCode } from '../../../../shared/models/http/http-error-codes'
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/controllers/api/server/follows.ts b/server/controllers/api/server/follows.ts
index 12357a2ca..cbe6b7e4f 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'
@@ -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/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 { LogLevel } from '../../../../shared/models/server/log-level.type'
-import { CONFIG } from '../../../initializers/config'
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 { 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/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 d907b49bf..be800e8b5 100644
--- a/server/controllers/api/users/index.ts
+++ b/server/controllers/api/users/index.ts
@@ -4,8 +4,8 @@ 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 { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
+import { UserCreate, UserCreateResult, UserRight, UserRole, UserUpdate } from '../../../../shared'
+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'
@@ -220,7 +220,7 @@ async function createUser (req: express.Request, res: express.Response) {
account: {
id: account.id
}
- }
+ } as UserCreateResult
})
}
diff --git a/server/controllers/api/users/me.ts b/server/controllers/api/users/me.ts
index 1f2b2f9dd..ac6faca9c 100644
--- a/server/controllers/api/users/me.ts
+++ b/server/controllers/api/users/me.ts
@@ -2,8 +2,9 @@ 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/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'
@@ -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 a1561b751..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/core-utils/miscs/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..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/core-utils/miscs/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/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/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 87a6f6bbe..4971d0a77 100644
--- a/server/controllers/api/video-playlist.ts
+++ b/server/controllers/api/video-playlist.ts
@@ -5,7 +5,8 @@ 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 { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes'
+import { VideoPlaylistCreateResult, VideoPlaylistElementCreateResult } from '@shared/models'
+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'
@@ -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/controllers/api/videos/blacklist.ts b/server/controllers/api/videos/blacklist.ts
index 530e17965..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/core-utils/miscs/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 e6f28c1cb..cb696f652 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 { 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'
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/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..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 { 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/core-utils/miscs/http-error-codes'
+import { VideoChangeOwnershipModel } from '../../../models/video/video-change-ownership'
+import { VideoChannelModel } from '../../../models/video/video-channel'
const ownershipVideoRouter = express.Router()
diff --git a/server/controllers/api/videos/rate.ts b/server/controllers/api/videos/rate.ts
index 84f42633e..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/core-utils/miscs/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..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/core-utils/miscs/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..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/core-utils/miscs/http-error-codes'
-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/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/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/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/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/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/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
}
}
-export {
- autoFollowBackIfNeeded
+// 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,
+ getRemoteNameAndHost
}
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/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/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..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/core-utils/miscs/http-error-codes'
+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/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..cf70d901e 100644
--- a/server/middlewares/servers.ts
+++ b/server/middlewares/servers.ts
@@ -1,6 +1,6 @@
import * as express from 'express'
+import { HttpStatusCode } from '../../shared/models/http/http-error-codes'
import { getHostWithPort } from '../helpers/express-utils'
-import { HttpStatusCode } from '../../shared/core-utils/miscs/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..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 { HttpStatusCode } from '../../shared/models/http/http-error-codes'
import { logger } from '../helpers/logger'
-import { HttpStatusCode } from '../../shared/core-utils/miscs/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..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 { 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'
-import { getServerActor } from '@server/models/application/application'
-import { HttpStatusCode } from '../../../../shared/core-utils/miscs/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..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/core-utils/miscs/http-error-codes'
-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 51b8fdd19..d29bebf64 100644
--- a/server/middlewares/validators/feeds.ts
+++ b/server/middlewares/validators/feeds.ts
@@ -1,7 +1,6 @@
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..16abdd096 100644
--- a/server/middlewares/validators/follows.ts
+++ b/server/middlewares/validators/follows.ts
@@ -1,18 +1,20 @@
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/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'
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/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..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/core-utils'
-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/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..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/core-utils/miscs/http-error-codes'
-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 54ac46c99..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/core-utils'
-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/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/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 u.username === 'user1').id
- rootId = users.find(u => u.username === 'root').id
- moderatorId = users.find(u => u.username === 'moderator2').id
+ 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
}
})
@@ -156,7 +102,7 @@ describe('Test users API validators', function () {
await makeGetRequest({
url: server.url,
path,
- statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401
+ expectedStatus: HttpStatusCode.UNAUTHORIZED_401
})
})
@@ -164,8 +110,8 @@ describe('Test users API validators', function () {
await makeGetRequest({
url: server.url,
path,
- token: userAccessToken,
- statusCodeExpected: HttpStatusCode.FORBIDDEN_403
+ token: userToken,
+ expectedStatus: HttpStatusCode.FORBIDDEN_403
})
})
})
@@ -182,25 +128,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 })
})
@@ -212,25 +158,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 })
})
@@ -238,33 +184,37 @@ 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 = {
+ ...overrideConfig,
- const config = immutableAssign(overrideConfig, {
smtp: {
hostname: 'localhost',
port: emailPort
}
- })
- await reRunServer(server, config)
+ }
+ await server.run(config)
+
+ const fields = {
+ ...baseCorrectParams,
- const fields = immutableAssign(baseCorrectParams, {
password: '',
username: 'create_password',
email: 'create_password@example.com'
- })
+ }
await makePostBodyRequest({
url: server.url,
path: path,
token: server.accessToken,
fields,
- statusCodeExpected: HttpStatusCode.OK_200
+ expectedStatus: HttpStatusCode.OK_200
})
})
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 })
})
@@ -275,31 +225,31 @@ describe('Test users API validators', function () {
path,
token: 'super token',
fields: baseCorrectParams,
- statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401
+ expectedStatus: HttpStatusCode.UNAUTHORIZED_401
})
})
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,
path,
token: server.accessToken,
fields,
- statusCodeExpected: HttpStatusCode.CONFLICT_409
+ expectedStatus: HttpStatusCode.CONFLICT_409
})
})
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,
path,
token: server.accessToken,
fields,
- statusCodeExpected: HttpStatusCode.CONFLICT_409
+ expectedStatus: HttpStatusCode.CONFLICT_409
})
})
@@ -316,13 +266,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 })
})
@@ -334,46 +284,46 @@ 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,
path,
token: server.accessToken,
fields,
- statusCodeExpected: HttpStatusCode.CONFLICT_409
+ expectedStatus: HttpStatusCode.CONFLICT_409
})
})
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,
path,
- token: moderatorAccessToken,
+ token: moderatorToken,
fields,
- statusCodeExpected: HttpStatusCode.FORBIDDEN_403
+ expectedStatus: HttpStatusCode.FORBIDDEN_403
})
}
})
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,
path,
- token: moderatorAccessToken,
+ token: moderatorToken,
fields,
- statusCodeExpected: HttpStatusCode.OK_200
+ expectedStatus: HttpStatusCode.OK_200
})
})
@@ -383,16 +333,13 @@ describe('Test users API validators', function () {
path,
token: server.accessToken,
fields: baseCorrectParams,
- statusCodeExpected: HttpStatusCode.OK_200
+ expectedStatus: HttpStatusCode.OK_200
})
})
it('Should fail with a non admin user', async function () {
- const user = {
- username: 'user1',
- password: 'my super password'
- }
- userAccessToken = await userLogin(server, user)
+ const user = { username: 'user1' }
+ userToken = await server.login.getAccessToken(user)
const fields = {
username: 'user3',
@@ -400,11 +347,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, expectedStatus: HttpStatusCode.FORBIDDEN_403 })
})
})
describe('When updating my account', function () {
+
it('Should fail with an invalid email attribute', async function () {
const fields = {
email: 'blabla'
@@ -415,29 +363,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 () {
@@ -449,9 +397,9 @@ describe('Test users API validators', function () {
await makePutBodyRequest({
url: server.url,
path: path + 'me',
- token: userAccessToken,
+ token: userToken,
fields,
- statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401
+ expectedStatus: HttpStatusCode.UNAUTHORIZED_401
})
})
@@ -460,7 +408,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 () {
@@ -468,7 +416,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 () {
@@ -476,7 +424,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 () {
@@ -484,12 +432,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'
}
@@ -498,7 +446,7 @@ describe('Test users API validators', function () {
path: path + 'me',
token: 'super token',
fields,
- statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401
+ expectedStatus: HttpStatusCode.UNAUTHORIZED_401
})
})
@@ -507,7 +455,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 () {
@@ -516,7 +464,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 })
}
{
@@ -529,18 +477,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 () {
@@ -548,7 +496,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 () {
@@ -556,12 +504,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,
@@ -574,9 +522,9 @@ describe('Test users API validators', function () {
await makePutBodyRequest({
url: server.url,
path: path + 'me',
- token: userAccessToken,
+ token: userToken,
fields,
- statusCodeExpected: HttpStatusCode.NO_CONTENT_204
+ expectedStatus: HttpStatusCode.NO_CONTENT_204
})
})
@@ -589,9 +537,9 @@ describe('Test users API validators', function () {
await makePutBodyRequest({
url: server.url,
path: path + 'me',
- token: userAccessToken,
+ token: userToken,
fields,
- statusCodeExpected: HttpStatusCode.NO_CONTENT_204
+ expectedStatus: HttpStatusCode.NO_CONTENT_204
})
})
})
@@ -623,7 +571,7 @@ describe('Test users API validators', function () {
path: path + '/me/avatar/pick',
fields,
attaches,
- statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401
+ expectedStatus: HttpStatusCode.UNAUTHORIZED_401
})
})
@@ -638,7 +586,7 @@ describe('Test users API validators', function () {
token: server.accessToken,
fields,
attaches,
- statusCodeExpected: HttpStatusCode.OK_200
+ expectedStatus: HttpStatusCode.OK_200
})
})
})
@@ -646,28 +594,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.users.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.users.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.users.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.users.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.users.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.users.renewMyScopedTokens()
})
})
@@ -678,16 +626,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: userAccessToken, 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 })
})
})
@@ -727,7 +675,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'
}
@@ -736,7 +684,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)
}
@@ -753,7 +701,7 @@ describe('Test users API validators', function () {
path: path + userId,
token: 'super token',
fields,
- statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401
+ expectedStatus: HttpStatusCode.UNAUTHORIZED_401
})
})
@@ -779,9 +727,9 @@ describe('Test users API validators', function () {
await makePutBodyRequest({
url: server.url,
path: path + moderatorId,
- token: moderatorAccessToken,
+ token: moderatorToken,
fields,
- statusCodeExpected: HttpStatusCode.FORBIDDEN_403
+ expectedStatus: HttpStatusCode.FORBIDDEN_403
})
})
@@ -793,9 +741,9 @@ describe('Test users API validators', function () {
await makePutBodyRequest({
url: server.url,
path: path + userId,
- token: moderatorAccessToken,
+ token: moderatorToken,
fields,
- statusCodeExpected: HttpStatusCode.NO_CONTENT_204
+ expectedStatus: HttpStatusCode.NO_CONTENT_204
})
})
@@ -812,38 +760,44 @@ describe('Test users API validators', function () {
path: path + userId,
token: server.accessToken,
fields,
- statusCodeExpected: HttpStatusCode.NO_CONTENT_204
+ expectedStatus: HttpStatusCode.NO_CONTENT_204
})
})
})
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.users.getMyInfo({ token: 'fake_token', expectedStatus: HttpStatusCode.UNAUTHORIZED_401 })
})
it('Should success with the correct parameters', async function () {
- await getMyUserInformation(server.url, userAccessToken)
+ await server.users.getMyInfo({ token: userToken })
})
})
describe('When getting my video rating', function () {
+ let command: UsersCommand
+
+ before(function () {
+ command = server.users
+ })
+
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 })
})
})
@@ -851,80 +805,93 @@ 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 () {
- 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 () {
await makeGetRequest({
url: server.url,
path,
- token: userAccessToken,
+ 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: userAccessToken, statusCodeExpected: HttpStatusCode.OK_200 })
+ await makeGetRequest({ url: server.url, path, token: userToken, expectedStatus: 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.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 () {
- 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.users.remove(options)
+ await server.users.banUser(options)
+ await server.users.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.users.remove(options)
+ await server.users.banUser(options)
+ await server.users.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.users.remove(options)
+ await server.users.banUser(options)
+ await server.users.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.users.remove(options)
+ await server.users.banUser(options)
+ await server.users.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.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 deleteMe(server.url, server.accessToken, HttpStatusCode.BAD_REQUEST_400)
+ await server.users.deleteMe({ expectedStatus: HttpStatusCode.BAD_REQUEST_400 })
})
})
@@ -938,19 +905,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 })
})
@@ -962,108 +929,108 @@ 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,
path: registrationPath,
token: server.accessToken,
fields,
- statusCodeExpected: HttpStatusCode.CONFLICT_409
+ expectedStatus: HttpStatusCode.CONFLICT_409
})
})
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,
path: registrationPath,
token: server.accessToken,
fields,
- statusCodeExpected: HttpStatusCode.CONFLICT_409
+ expectedStatus: HttpStatusCode.CONFLICT_409
})
})
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,
path: registrationPath,
token: server.accessToken,
fields,
- statusCodeExpected: HttpStatusCode.CONFLICT_409
+ expectedStatus: HttpStatusCode.CONFLICT_409
})
})
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 })
})
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.channels.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,
path: registrationPath,
token: server.accessToken,
fields,
- statusCodeExpected: HttpStatusCode.CONFLICT_409
+ expectedStatus: HttpStatusCode.CONFLICT_409
})
})
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,
path: registrationPath,
token: server.accessToken,
fields: fields,
- statusCodeExpected: HttpStatusCode.NO_CONTENT_204
+ expectedStatus: HttpStatusCode.NO_CONTENT_204
})
})
@@ -1079,14 +1046,14 @@ describe('Test users API validators', function () {
path: registrationPath,
token: serverWithRegistrationDisabled.accessToken,
fields,
- statusCodeExpected: HttpStatusCode.FORBIDDEN_403
+ expectedStatus: HttpStatusCode.FORBIDDEN_403
})
})
})
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.users.register({ username: 'user42', expectedStatus: HttpStatusCode.FORBIDDEN_403 })
})
})
@@ -1113,7 +1080,7 @@ describe('Test users API validators', function () {
path,
token: server.accessToken,
fields,
- statusCodeExpected: HttpStatusCode.NO_CONTENT_204
+ expectedStatus: HttpStatusCode.NO_CONTENT_204
})
})
})
@@ -1141,7 +1108,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 ce7f5fa17..d28c6a952 100644
--- a/server/tests/api/check-params/video-blacklist.ts
+++ b/server/tests/api/check-params/video-blacklist.ts
@@ -1,46 +1,37 @@
/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */
import 'mocha'
-
-import {
- cleanupTests,
- createUser,
- doubleFollow,
- flushAndRunMultipleServers,
- getBlacklistedVideosList,
- getVideo,
- getVideoWithToken,
- makePostBodyRequest,
- makePutBodyRequest,
- removeVideoFromBlacklist,
- ServerInfo,
- setAccessTokensToServers,
- uploadVideo,
- userLogin,
- waitJobs
-} from '../../../../shared/extra-utils'
+import { expect } from 'chai'
import {
+ BlacklistCommand,
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'
+ checkBadStartPagination,
+ cleanupTests,
+ createMultipleServers,
+ doubleFollow,
+ makePostBodyRequest,
+ makePutBodyRequest,
+ PeerTubeServer,
+ setAccessTokensToServers,
+ waitJobs
+} from '@shared/extra-utils'
+import { HttpStatusCode, VideoBlacklistType } from '@shared/models'
describe('Test video blacklist API validators', function () {
- let servers: ServerInfo[]
- let notBlacklistedVideoId: number
+ let servers: PeerTubeServer[]
+ let notBlacklistedVideoId: string
let remoteVideoUUID: string
let userAccessToken1 = ''
let userAccessToken2 = ''
+ let command: BlacklistCommand
// ---------------------------------------------------------------
before(async function () {
this.timeout(120000)
- servers = await flushAndRunMultipleServers(2)
+ servers = await createMultipleServers(2)
await setAccessTokensToServers(servers)
await doubleFollow(servers[0], servers[1])
@@ -48,40 +39,41 @@ 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 })
+ 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 createUser({ url: servers[0].url, accessToken: servers[0].accessToken, username: username, password: password })
- userAccessToken2 = await userLogin(servers[0], { username, password })
+ await servers[0].users.create({ username: username, password: password })
+ userAccessToken2 = await servers[0].login.getAccessToken({ username, password })
}
{
- const res = await uploadVideo(servers[0].url, userAccessToken1, {})
- servers[0].video = res.body.video
+ servers[0].store.video = await servers[0].videos.upload({ token: userAccessToken1 })
}
{
- const res = await uploadVideo(servers[0].url, servers[0].accessToken, {})
- notBlacklistedVideoId = res.body.video.uuid
+ const { uuid } = await servers[0].videos.upload()
+ notBlacklistedVideoId = uuid
}
{
- const res = await uploadVideo(servers[1].url, servers[1].accessToken, {})
- remoteVideoUUID = res.body.video.uuid
+ const { uuid } = await servers[1].videos.upload()
+ remoteVideoUUID = uuid
}
await waitJobs(servers)
+
+ 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 })
})
@@ -93,25 +85,25 @@ 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 })
+ await makePostBodyRequest({ url: servers[0].url, path, token: 'hello', fields, expectedStatus: 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,
path,
token: userAccessToken2,
fields,
- statusCodeExpected: HttpStatusCode.FORBIDDEN_403
+ expectedStatus: HttpStatusCode.FORBIDDEN_403
})
})
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 })
@@ -126,12 +118,12 @@ describe('Test video blacklist API validators', function () {
path,
token: servers[0].accessToken,
fields,
- statusCodeExpected: HttpStatusCode.CONFLICT_409
+ expectedStatus: HttpStatusCode.CONFLICT_409
})
})
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({
@@ -139,7 +131,7 @@ describe('Test video blacklist API validators', function () {
path,
token: servers[0].accessToken,
fields,
- statusCodeExpected: HttpStatusCode.NO_CONTENT_204
+ expectedStatus: HttpStatusCode.NO_CONTENT_204
})
})
})
@@ -161,37 +153,37 @@ 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].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 })
+ await makePutBodyRequest({ url: servers[0].url, path, token: 'hello', fields, expectedStatus: 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,
path,
token: userAccessToken2,
fields,
- statusCodeExpected: HttpStatusCode.FORBIDDEN_403
+ expectedStatus: HttpStatusCode.FORBIDDEN_403
})
})
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({
@@ -199,7 +191,7 @@ describe('Test video blacklist API validators', function () {
path,
token: servers[0].accessToken,
fields,
- statusCodeExpected: HttpStatusCode.NO_CONTENT_204
+ expectedStatus: HttpStatusCode.NO_CONTENT_204
})
})
})
@@ -207,52 +199,53 @@ 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].videos.get({ id: servers[0].store.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].videos.getWithToken({
+ token: userAccessToken2,
+ id: servers[0].store.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].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 res = await getVideoWithToken(servers[0].url, servers[0].accessToken, id, HttpStatusCode.OK_200)
- const video: VideoDetails = res.body
-
+ const video = await servers[0].videos.getWithToken({ id, expectedStatus: HttpStatusCode.OK_200 })
expect(video.blacklisted).to.be.true
}
})
})
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].store.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].store.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].store.video.uuid, expectedStatus: HttpStatusCode.NO_CONTENT_204 })
})
})
@@ -260,11 +253,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].blacklist.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].blacklist.list({ token: userAccessToken2, expectedStatus: HttpStatusCode.FORBIDDEN_403 })
})
it('Should fail with a bad start pagination', async function () {
@@ -280,16 +273,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].blacklist.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].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 c0595c04d..90f429314 100644
--- a/server/tests/api/check-params/video-captions.ts
+++ b/server/tests/api/check-params/video-captions.ts
@@ -1,27 +1,22 @@
/* 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 {
buildAbsoluteFixturePath,
cleanupTests,
- createUser,
- flushAndRunServer,
+ createSingleServer,
makeDeleteRequest,
makeGetRequest,
makeUploadRequest,
- ServerInfo,
- setAccessTokensToServers,
- uploadVideo,
- userLogin
-} from '../../../../shared/extra-utils'
-import { createVideoCaption } from '../../../../shared/extra-utils/videos/video-captions'
+ PeerTubeServer,
+ setAccessTokensToServers
+} from '@shared/extra-utils'
+import { HttpStatusCode, 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
@@ -30,22 +25,19 @@ describe('Test video captions API validator', function () {
before(async function () {
this.timeout(30000)
- server = await flushAndRunServer(1)
+ server = await createSingleServer(1)
await setAccessTokensToServers([ server ])
- {
- const res = await uploadVideo(server.url, server.accessToken, {})
- video = res.body.video
- }
+ video = await server.videos.upload()
{
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)
+ await server.users.create({ username: user.username, password: user.password })
+ userAccessToken = await server.login.getAccessToken(user)
}
})
@@ -74,7 +66,7 @@ describe('Test video captions API validator', function () {
token: server.accessToken,
fields,
attaches,
- statusCodeExpected: 404
+ expectedStatus: 404
})
})
@@ -110,7 +102,7 @@ describe('Test video captions API validator', function () {
path: captionPath,
fields,
attaches,
- statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401
+ expectedStatus: HttpStatusCode.UNAUTHORIZED_401
})
})
@@ -123,7 +115,7 @@ describe('Test video captions API validator', function () {
token: 'blabla',
fields,
attaches,
- statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401
+ expectedStatus: HttpStatusCode.UNAUTHORIZED_401
})
})
@@ -141,7 +133,7 @@ describe('Test video captions API validator', function () {
// token: server.accessToken,
// fields,
// attaches,
- // statusCodeExpected: HttpStatusCode.BAD_REQUEST_400
+ // expectedStatus: HttpStatusCode.BAD_REQUEST_400
// })
// })
@@ -154,14 +146,12 @@ 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
// })
// })
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.captions.add({
language: 'zh',
videoId: video.uuid,
fixture: 'subtitle-good.srt',
@@ -183,7 +173,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
// })
// })
@@ -196,7 +186,7 @@ describe('Test video captions API validator', function () {
token: server.accessToken,
fields,
attaches,
- statusCodeExpected: HttpStatusCode.NO_CONTENT_204
+ expectedStatus: HttpStatusCode.NO_CONTENT_204
})
})
})
@@ -210,12 +200,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 })
})
})
@@ -233,7 +223,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
})
})
@@ -257,12 +247,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 () {
@@ -271,7 +261,7 @@ describe('Test video captions API validator', function () {
url: server.url,
path: captionPath,
token: userAccessToken,
- statusCodeExpected: HttpStatusCode.FORBIDDEN_403
+ expectedStatus: HttpStatusCode.FORBIDDEN_403
})
})
@@ -281,7 +271,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 5c02afd31..2e63916d4 100644
--- a/server/tests/api/check-params/video-channels.ts
+++ b/server/tests/api/check-params/video-channels.ts
@@ -3,43 +3,37 @@
import 'mocha'
import * as chai from 'chai'
import { omit } from 'lodash'
-import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
import {
buildAbsoluteFixturePath,
+ ChannelsCommand,
+ checkBadCountPagination,
+ checkBadSortPagination,
+ checkBadStartPagination,
cleanupTests,
- createUser,
- deleteVideoChannel,
- flushAndRunServer,
- getAccountVideoChannelsList,
- immutableAssign,
+ createSingleServer,
makeGetRequest,
makePostBodyRequest,
makePutBodyRequest,
makeUploadRequest,
- 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'
+ PeerTubeServer,
+ setAccessTokensToServers
+} from '@shared/extra-utils'
+import { HttpStatusCode, VideoChannelUpdate } from '@shared/models'
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
// ---------------------------------------------------------------
before(async function () {
this.timeout(30000)
- server = await flushAndRunServer(1)
+ server = await createSingleServer(1)
await setAccessTokensToServers([ server ])
@@ -49,9 +43,11 @@ 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)
+ await server.users.create({ username: user.username, password: user.password })
+ accessTokenUser = await server.login.getAccessToken(user)
}
+
+ command = server.channels
})
describe('When listing a video channels', function () {
@@ -84,14 +80,14 @@ 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.channels.listByAccount({ accountName: 'unknown', expectedStatus: HttpStatusCode.NOT_FOUND_404 })
})
it('Should succeed with the correct parameters', async function () {
await makeGetRequest({
url: server.url,
path: accountChannelPath,
- statusCodeExpected: HttpStatusCode.OK_200
+ expectedStatus: HttpStatusCode.OK_200
})
})
})
@@ -110,7 +106,7 @@ describe('Test video channels API validator', function () {
path: videoChannelPath,
token: 'none',
fields: baseCorrectParams,
- statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401
+ expectedStatus: HttpStatusCode.UNAUTHORIZED_401
})
})
@@ -125,7 +121,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 })
})
@@ -135,17 +131,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 })
})
@@ -155,7 +151,7 @@ describe('Test video channels API validator', function () {
path: videoChannelPath,
token: server.accessToken,
fields: baseCorrectParams,
- statusCodeExpected: HttpStatusCode.OK_200
+ expectedStatus: HttpStatusCode.OK_200
})
})
@@ -165,7 +161,7 @@ describe('Test video channels API validator', function () {
path: videoChannelPath,
token: server.accessToken,
fields: baseCorrectParams,
- statusCodeExpected: HttpStatusCode.CONFLICT_409
+ expectedStatus: HttpStatusCode.CONFLICT_409
})
})
})
@@ -189,7 +185,7 @@ describe('Test video channels API validator', function () {
path,
token: 'hi',
fields: baseCorrectParams,
- statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401
+ expectedStatus: HttpStatusCode.UNAUTHORIZED_401
})
})
@@ -199,27 +195,27 @@ describe('Test video channels API validator', function () {
path,
token: accessTokenUser,
fields: baseCorrectParams,
- statusCodeExpected: HttpStatusCode.FORBIDDEN_403
+ expectedStatus: HttpStatusCode.FORBIDDEN_403
})
})
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 })
})
@@ -229,7 +225,7 @@ describe('Test video channels API validator', function () {
path,
token: server.accessToken,
fields: baseCorrectParams,
- statusCodeExpected: HttpStatusCode.NO_CONTENT_204
+ expectedStatus: HttpStatusCode.NO_CONTENT_204
})
})
})
@@ -274,7 +270,7 @@ describe('Test video channels API validator', function () {
path: `${path}/${type}/pick`,
fields,
attaches,
- statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401
+ expectedStatus: HttpStatusCode.UNAUTHORIZED_401
})
}
})
@@ -291,7 +287,7 @@ describe('Test video channels API validator', function () {
token: server.accessToken,
fields,
attaches,
- statusCodeExpected: HttpStatusCode.OK_200
+ expectedStatus: HttpStatusCode.OK_200
})
}
})
@@ -302,7 +298,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')
@@ -312,7 +308,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
})
})
@@ -320,30 +316,30 @@ describe('Test video channels API validator', function () {
await makeGetRequest({
url: server.url,
path: videoChannelPath + '/super_channel',
- statusCodeExpected: HttpStatusCode.OK_200
+ expectedStatus: HttpStatusCode.OK_200
})
})
})
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/check-params/video-comments.ts b/server/tests/api/check-params/video-comments.ts
index a38420851..2d9ee1e0d 100644
--- a/server/tests/api/check-params/video-comments.ts
+++ b/server/tests/api/check-params/video-comments.ts
@@ -2,33 +2,26 @@
import 'mocha'
import * as chai from 'chai'
-import { VideoCreateResult } from '@shared/models'
-import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
-import {
- cleanupTests,
- createUser,
- flushAndRunServer,
- makeDeleteRequest,
- makeGetRequest,
- makePostBodyRequest,
- ServerInfo,
- 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'
+ checkBadStartPagination,
+ cleanupTests,
+ createSingleServer,
+ makeDeleteRequest,
+ makeGetRequest,
+ makePostBodyRequest,
+ PeerTubeServer,
+ setAccessTokensToServers
+} from '@shared/extra-utils'
+import { HttpStatusCode, VideoCreateResult } from '@shared/models'
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
@@ -39,32 +32,31 @@ describe('Test video comments API validator', function () {
before(async function () {
this.timeout(30000)
- server = await flushAndRunServer(1)
+ server = await createSingleServer(1)
await setAccessTokensToServers([ server ])
{
- const res = await uploadVideo(server.url, server.accessToken, {})
- video = res.body.video
+ video = await server.videos.upload({ attributes: {} })
pathThread = '/api/v1/videos/' + video.uuid + '/comment-threads'
}
{
- const res = await addVideoCommentThread(server.url, server.accessToken, video.uuid, 'coucou')
- commentId = res.body.comment.id
+ 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 createUser({ url: server.url, accessToken: server.accessToken, username: user.username, password: user.password })
- userAccessToken = await userLogin(server, 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 createUser({ url: server.url, accessToken: server.accessToken, username: user.username, password: user.password })
- userAccessToken2 = await userLogin(server, user)
+ await server.users.create({ username: user.username, password: user.password })
+ userAccessToken2 = await server.login.getAccessToken(user)
}
})
@@ -85,7 +77,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
})
})
})
@@ -95,7 +87,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
})
})
@@ -103,7 +95,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
})
})
@@ -111,7 +103,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
})
})
})
@@ -127,7 +119,7 @@ describe('Test video comments API validator', function () {
path: pathThread,
token: 'none',
fields,
- statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401
+ expectedStatus: HttpStatusCode.UNAUTHORIZED_401
})
})
@@ -160,7 +152,7 @@ describe('Test video comments API validator', function () {
path,
token: server.accessToken,
fields,
- statusCodeExpected: HttpStatusCode.NOT_FOUND_404
+ expectedStatus: HttpStatusCode.NOT_FOUND_404
})
})
@@ -173,7 +165,7 @@ describe('Test video comments API validator', function () {
path: pathThread,
token: server.accessToken,
fields,
- statusCodeExpected: HttpStatusCode.OK_200
+ expectedStatus: HttpStatusCode.OK_200
})
})
})
@@ -188,7 +180,7 @@ describe('Test video comments API validator', function () {
path: pathComment,
token: 'none',
fields,
- statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401
+ expectedStatus: HttpStatusCode.UNAUTHORIZED_401
})
})
@@ -221,7 +213,7 @@ describe('Test video comments API validator', function () {
path,
token: server.accessToken,
fields,
- statusCodeExpected: HttpStatusCode.NOT_FOUND_404
+ expectedStatus: HttpStatusCode.NOT_FOUND_404
})
})
@@ -235,7 +227,7 @@ describe('Test video comments API validator', function () {
path,
token: server.accessToken,
fields,
- statusCodeExpected: HttpStatusCode.NOT_FOUND_404
+ expectedStatus: HttpStatusCode.NOT_FOUND_404
})
})
@@ -248,14 +240,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 () {
@@ -263,32 +255,32 @@ 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 () {
let commentToDelete: number
{
- const res = await addVideoCommentThread(server.url, userAccessToken, video.uuid, 'hello')
- commentToDelete = res.body.comment.id
+ const created = await server.comments.createThread({ videoId: video.uuid, token: userAccessToken, text: 'hello' })
+ commentToDelete = created.id
}
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 () {
@@ -296,19 +288,19 @@ 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.videos.upload({ token: userAccessToken, attributes: { name: 'video' } })
+ anotherVideoUUID = uuid
}
{
- const res = await addVideoCommentThread(server.url, server.accessToken, anotherVideoUUID, 'hello')
- commentToDelete = res.body.comment.id
+ const created = await server.comments.createThread({ videoId: anotherVideoUUID, text: 'hello' })
+ commentToDelete = created.id
}
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 () {
@@ -316,15 +308,14 @@ 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
})
})
})
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.videos.upload({ attributes: { commentsEnabled: false } })
pathThread = '/api/v1/videos/' + video.uuid + '/comment-threads'
})
@@ -332,7 +323,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)
@@ -349,7 +340,7 @@ describe('Test video comments API validator', function () {
path: pathThread,
token: server.accessToken,
fields,
- statusCodeExpected: HttpStatusCode.CONFLICT_409
+ expectedStatus: HttpStatusCode.CONFLICT_409
})
})
@@ -375,7 +366,7 @@ describe('Test video comments API validator', function () {
await makeGetRequest({
url: server.url,
path,
- statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401
+ expectedStatus: HttpStatusCode.UNAUTHORIZED_401
})
})
@@ -384,7 +375,7 @@ describe('Test video comments API validator', function () {
url: server.url,
path,
token: userAccessToken,
- statusCodeExpected: HttpStatusCode.FORBIDDEN_403
+ expectedStatus: HttpStatusCode.FORBIDDEN_403
})
})
@@ -399,7 +390,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 a27b624d0..d6d745488 100644
--- a/server/tests/api/check-params/video-imports.ts
+++ b/server/tests/api/check-params/video-imports.ts
@@ -2,33 +2,25 @@
import 'mocha'
import { omit } from 'lodash'
-import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
import {
buildAbsoluteFixturePath,
+ checkBadCountPagination,
+ checkBadSortPagination,
+ checkBadStartPagination,
cleanupTests,
- createUser,
- flushAndRunServer,
- getMyUserInformation,
- immutableAssign,
+ createSingleServer,
+ FIXTURE_URLS,
makeGetRequest,
makePostBodyRequest,
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'
+ PeerTubeServer,
+ setAccessTokensToServers
+} from '@shared/extra-utils'
+import { HttpStatusCode, 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
@@ -37,18 +29,18 @@ describe('Test video imports API validator', function () {
before(async function () {
this.timeout(30000)
- server = await flushAndRunServer(1)
+ server = await createSingleServer(1)
await setAccessTokensToServers([ server ])
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 })
+ await server.users.create({ username: username, password: password })
+ userAccessToken = await server.login.getAccessToken({ username, password })
{
- const res = await getMyUserInformation(server.url, server.accessToken)
- channelId = res.body.videoChannels[0].id
+ const { videoChannels } = await server.users.getMyInfo()
+ channelId = videoChannels[0].id
}
})
@@ -68,7 +60,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 })
})
})
@@ -77,7 +69,7 @@ describe('Test video imports API validator', function () {
before(function () {
baseCorrectParams = {
- targetUrl: getGoodVideoUrl(),
+ targetUrl: FIXTURE_URLS.goodVideo,
name: 'my super name',
category: 5,
licence: 1,
@@ -106,48 +98,48 @@ describe('Test video imports API validator', function () {
path,
token: server.accessToken,
fields,
- statusCodeExpected: HttpStatusCode.BAD_REQUEST_400
+ expectedStatus: HttpStatusCode.BAD_REQUEST_400
})
})
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 })
})
@@ -159,7 +151,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 })
})
@@ -169,31 +161,31 @@ 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.users.create({ username: user.username, password: user.password })
- const accessTokenUser = await userLogin(server, user)
- const res = await getMyUserInformation(server.url, accessTokenUser)
- const customChannelId = res.body.videoChannels[0].id
+ const accessTokenUser = await server.login.getAccessToken(user)
+ const { videoChannels } = await server.users.getMyInfo({ token: accessTokenUser })
+ const customChannelId = 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 })
})
@@ -245,7 +237,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 })
})
@@ -258,19 +250,21 @@ describe('Test video imports API validator', function () {
path,
token: server.accessToken,
fields: baseCorrectParams,
- statusCodeExpected: HttpStatusCode.OK_200
+ expectedStatus: HttpStatusCode.OK_200
})
})
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.config.updateCustomSubConfig({
+ newConfig: {
+ import: {
+ videos: {
+ http: {
+ enabled: false
+ },
+ torrent: {
+ enabled: true
+ }
}
}
}
@@ -281,33 +275,35 @@ describe('Test video imports API validator', function () {
path,
token: server.accessToken,
fields: baseCorrectParams,
- statusCodeExpected: HttpStatusCode.CONFLICT_409
+ expectedStatus: HttpStatusCode.CONFLICT_409
})
})
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.config.updateCustomSubConfig({
+ newConfig: {
+ import: {
+ videos: {
+ http: {
+ enabled: true
+ },
+ torrent: {
+ enabled: false
+ }
}
}
}
})
let fields = omit(baseCorrectParams, 'targetUrl')
- fields = immutableAssign(fields, { magnetUri: getMagnetURI() })
+ fields = { ...fields, magnetUri: FIXTURE_URLS.magnet }
await makePostBodyRequest({
url: server.url,
path,
token: server.accessToken,
fields,
- statusCodeExpected: HttpStatusCode.CONFLICT_409
+ expectedStatus: HttpStatusCode.CONFLICT_409
})
fields = omit(fields, 'magnetUri')
@@ -321,7 +317,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 18253d11a..e4d541b48 100644
--- a/server/tests/api/check-params/video-playlists.ts
+++ b/server/tests/api/check-params/video-playlists.ts
@@ -1,34 +1,31 @@
/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */
import 'mocha'
-import { VideoPlaylistCreateResult, VideoPlaylistPrivacy, 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,
+ createSingleServer,
makeGetRequest,
- removeVideoFromPlaylist,
- reorderVideosPlaylist,
- ServerInfo,
+ PeerTubeServer,
+ PlaylistsCommand,
setAccessTokensToServers,
- setDefaultVideoChannel,
- updateVideoPlaylist,
- updateVideoPlaylistElement,
- uploadVideoAndGetId
-} from '../../../../shared/extra-utils'
+ setDefaultVideoChannel
+} from '@shared/extra-utils'
+import {
+ HttpStatusCode,
+ VideoPlaylistCreate,
+ VideoPlaylistCreateResult,
+ VideoPlaylistElementCreate,
+ VideoPlaylistElementUpdate,
+ VideoPlaylistPrivacy,
+ VideoPlaylistReorder,
+ VideoPlaylistType
+} from '@shared/models'
describe('Test video playlists API validator', function () {
- let server: ServerInfo
+ let server: PeerTubeServer
let userAccessToken: string
let playlist: VideoPlaylistCreateResult
@@ -36,49 +33,54 @@ describe('Test video playlists API validator', function () {
let watchLaterPlaylistId: number
let videoId: number
- let playlistElementId: number
+ let elementId: number
+
+ let command: PlaylistsCommand
// ---------------------------------------------------------------
before(async function () {
this.timeout(30000)
- server = await flushAndRunServer(1)
+ server = await createSingleServer(1)
await setAccessTokensToServers([ server ])
await setDefaultVideoChannel([ server ])
- userAccessToken = await generateUserAccessToken(server, 'user1')
- videoId = (await uploadVideoAndGetId({ server, videoName: 'video 1' })).id
+ userAccessToken = await server.users.generateUserAndToken('user1')
+ videoId = (await server.videos.quickUpload({ name: 'video 1' })).id
+
+ command = server.playlists
{
- 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
+ videoChannelId: server.store.channel.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
}
})
@@ -117,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
})
})
@@ -128,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
})
})
@@ -157,141 +159,144 @@ 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 })
})
})
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,
+ videoChannelId: server.store.channel.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.store.channel.id,
+
+ ...attributes
+ },
+
+ expectedStatus: HttpStatusCode.BAD_REQUEST_400,
+
+ ...wrapper
+ }
}
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 () {
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 +305,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,110 +464,111 @@ 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 () {
- videoId3 = (await uploadVideoAndGetId({ server, videoName: 'video 3' })).id
- videoId4 = (await uploadVideoAndGetId({ server, videoName: '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 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)
})
})
@@ -562,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
})
})
@@ -595,82 +613,82 @@ describe('Test video playlists API validator', function () {
token: server.accessToken,
path,
query: { videoIds: [ 1, 2 ] },
- statusCodeExpected: HttpStatusCode.OK_200
+ expectedStatus: HttpStatusCode.OK_200
})
})
})
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/check-params/videos-filter.ts b/server/tests/api/check-params/videos-filter.ts
index 4d54a4fd0..d08570bbe 100644
--- a/server/tests/api/check-params/videos-filter.ts
+++ b/server/tests/api/check-params/videos-filter.ts
@@ -3,18 +3,15 @@
import 'mocha'
import {
cleanupTests,
- createUser,
- flushAndRunServer,
+ createSingleServer,
makeGetRequest,
- ServerInfo,
+ PeerTubeServer,
setAccessTokensToServers,
- setDefaultVideoChannel,
- userLogin
-} from '../../../../shared/extra-utils'
-import { UserRole } from '../../../../shared/models/users'
-import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
+ setDefaultVideoChannel
+} from '@shared/extra-utils'
+import { HttpStatusCode, UserRole } from '@shared/models'
-async function testEndpoints (server: ServerInfo, 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',
@@ -30,13 +27,13 @@ async function testEndpoints (server: ServerInfo, token: string, filter: string,
query: {
filter
},
- statusCodeExpected
+ expectedStatus
})
}
}
describe('Test video filters validators', function () {
- let server: ServerInfo
+ let server: PeerTubeServer
let userAccessToken: string
let moderatorAccessToken: string
@@ -45,28 +42,19 @@ 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 ])
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)
+ 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 createUser(
- {
- url: server.url,
- accessToken: server.accessToken,
- username: moderator.username,
- password: moderator.password,
- videoQuota: undefined,
- videoQuotaDaily: undefined,
- role: UserRole.MODERATOR
- }
- )
- moderatorAccessToken = await userLogin(server, moderator)
+ await server.users.create({ username: moderator.username, password: moderator.password, role: UserRole.MODERATOR })
+
+ moderatorAccessToken = await server.login.getAccessToken(moderator)
})
describe('When setting a video filter', function () {
@@ -100,7 +88,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
}
@@ -112,7 +100,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 0e91fe0a8..c3c309ed2 100644
--- a/server/tests/api/check-params/videos-history.ts
+++ b/server/tests/api/check-params/videos-history.ts
@@ -5,42 +5,39 @@ import {
checkBadCountPagination,
checkBadStartPagination,
cleanupTests,
- flushAndRunServer,
+ createSingleServer,
makeGetRequest,
makePostBodyRequest,
makePutBodyRequest,
- ServerInfo,
- setAccessTokensToServers,
- uploadVideo
-} from '../../../../shared/extra-utils'
-import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
+ 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'
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 ])
- const res = await uploadVideo(server.url, server.accessToken, {})
- const videoUUID = res.body.video.uuid
-
- watchingPath = '/api/v1/videos/' + videoUUID + '/watching'
+ const { uuid } = await server.videos.upload()
+ watchingPath = '/api/v1/videos/' + uuid + '/watching'
})
describe('When notifying a user is watching a video', 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 () {
@@ -51,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
})
})
@@ -64,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
})
})
@@ -75,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
})
})
@@ -87,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
})
})
})
@@ -102,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 () {
@@ -122,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
})
})
@@ -133,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
})
})
@@ -142,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-overviews.ts b/server/tests/api/check-params/videos-overviews.ts
index 69d7fc471..c2139d74b 100644
--- a/server/tests/api/check-params/videos-overviews.ts
+++ b/server/tests/api/check-params/videos-overviews.ts
@@ -1,29 +1,28 @@
/* 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, 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 () {
it('Should fail with a bad pagination', async function () {
- await getVideosOverview(server.url, 0, 400)
- await getVideosOverview(server.url, 100, 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 getVideosOverview(server.url, 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 4d7a9a23b..e11ca0c82 100644
--- a/server/tests/api/check-params/videos.ts
+++ b/server/tests/api/check-params/videos.ts
@@ -5,39 +5,28 @@ 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 {
+ checkBadCountPagination,
+ checkBadSortPagination,
+ checkBadStartPagination,
checkUploadVideoParam,
cleanupTests,
- createUser,
- flushAndRunServer,
- getMyUserInformation,
- getVideo,
- getVideosList,
- immutableAssign,
+ createSingleServer,
makeDeleteRequest,
makeGetRequest,
makePutBodyRequest,
makeUploadRequest,
- removeVideo,
+ PeerTubeServer,
root,
- ServerInfo,
- setAccessTokensToServers,
- userLogin
-} 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'
+ setAccessTokensToServers
+} from '@shared/extra-utils'
+import { HttpStatusCode, PeerTubeProblemDocument, VideoCreateResult, VideoPrivacy } from '@shared/models'
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
@@ -49,20 +38,20 @@ describe('Test videos API validator', function () {
before(async function () {
this.timeout(30000)
- server = await flushAndRunServer(1)
+ server = await createSingleServer(1)
await setAccessTokensToServers([ server ])
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 })
+ await server.users.create({ username: username, password: password })
+ userAccessToken = await server.login.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.users.getMyInfo()
+ channelId = body.videoChannels[0].id
+ channelName = body.videoChannels[0].name
+ accountName = body.account.name + '@' + body.account.host
}
})
@@ -80,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 } })
})
})
@@ -94,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
})
})
@@ -111,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 })
})
})
@@ -131,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 })
})
})
@@ -155,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 })
})
})
@@ -179,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 })
})
})
@@ -214,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 = 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)
+ await checkUploadVideoParam(server, 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)
+ await checkUploadVideoParam(server, 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)
+ await checkUploadVideoParam(server, 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)
+ await checkUploadVideoParam(server, 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)
+ await checkUploadVideoParam(server, 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)
+ 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 = 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)
+ await checkUploadVideoParam(server, server.accessToken, { ...fields, ...attaches }, HttpStatusCode.BAD_REQUEST_400, mode)
})
it('Should fail with another user channel', async function () {
@@ -285,69 +274,71 @@ 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.users.create({ username: user.username, password: user.password })
- const accessTokenUser = await userLogin(server, user)
- const res = await getMyUserInformation(server.url, accessTokenUser)
- const customChannelId = res.body.videoChannels[0].id
+ const accessTokenUser = await server.login.getAccessToken(user)
+ const { videoChannels } = await server.users.getMyInfo({ token: accessTokenUser })
+ const customChannelId = 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)
+ await checkUploadVideoParam(server, 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)
+ 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 = 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)
+ 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 = 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)
+ 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 = 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)
+ await checkUploadVideoParam(server, 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)
+ 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 = 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)
+ 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 () {
@@ -355,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,
@@ -364,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,
@@ -379,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 () {
@@ -389,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 () {
@@ -399,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 () {
@@ -409,17 +400,17 @@ 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 () {
- const fields = immutableAssign(baseCorrectParams, { language: 'a'.repeat(15) })
+ const fields = { ...baseCorrectParams, language: 'a'.repeat(15) }
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')
@@ -444,23 +435,27 @@ 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)
}
{
- 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)
+ await checkUploadVideoParam(server, server.accessToken, { ...fields, ...attaches }, HttpStatusCode.OK_200, mode)
}
{
- const attaches = immutableAssign(baseCorrectAttaches, {
- videofile: join(root(), 'server', 'tests', 'fixtures', 'video_short.ogv')
- })
+ const attaches = {
+ ...baseCorrectAttaches,
- await checkUploadVideoParam(server.url, server.accessToken, { ...fields, ...attaches }, HttpStatusCode.OK_200, mode)
+ videofile: join(root(), 'server', 'tests', 'fixtures', 'video_short.ogv')
+ }
+
+ await checkUploadVideoParam(server, server.accessToken, { ...fields, ...attaches }, HttpStatusCode.OK_200, mode)
}
})
}
@@ -489,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.videos.list()
+ video = data[0]
})
it('Should fail with nothing', async function () {
@@ -511,84 +506,84 @@ 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
})
})
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 })
})
@@ -665,14 +660,14 @@ describe('Test videos API validator', function () {
path: path + video.shortUUID,
token: userAccessToken,
fields,
- statusCodeExpected: HttpStatusCode.FORBIDDEN_403
+ expectedStatus: HttpStatusCode.FORBIDDEN_403
})
})
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
@@ -697,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
})
})
})
@@ -707,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')
@@ -715,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.videos.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.videos.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.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')
@@ -739,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.videos.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.videos.list()
+ videoId = data[0].id
})
it('Should fail without a valid uuid', async function () {
@@ -767,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
})
})
@@ -787,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
})
})
})
@@ -797,27 +792,27 @@ describe('Test videos API validator', function () {
await makeDeleteRequest({
url: server.url,
path,
- statusCodeExpected: HttpStatusCode.BAD_REQUEST_400
+ expectedStatus: HttpStatusCode.BAD_REQUEST_400
})
})
it('Should fail without a correct uuid', async function () {
- await removeVideo(server.url, server.accessToken, 'hello', 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 removeVideo(server.url, server.accessToken, '4da6fde3-88f7-4d16-b119-108df5630b06', 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 removeVideo(server.url, userAccessToken, video.uuid, 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 res = await removeVideo(server.url, server.accessToken, 'hello', HttpStatusCode.BAD_REQUEST_400)
- const error = res.body as PeerTubeProblemDocument
+ const body = await server.videos.remove({ id: 'hello', expectedStatus: HttpStatusCode.BAD_REQUEST_400 })
+ const error = body as PeerTubeProblemDocument
expect(error.docs).to.equal('https://docs.joinpeertube.org/api-rest-reference.html#operation/delVideo')
@@ -832,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.videos.remove({ id: video.uuid })
})
})
diff --git a/server/tests/api/live/live-constraints.ts b/server/tests/api/live/live-constraints.ts
index cc635de33..20346113d 100644
--- a/server/tests/api/live/live-constraints.ts
+++ b/server/tests/api/live/live-constraints.ts
@@ -2,31 +2,24 @@
import 'mocha'
import * as chai from 'chai'
-import { VideoDetails, VideoPrivacy } from '@shared/models'
+import { VideoPrivacy } from '@shared/models'
import {
checkLiveCleanup,
cleanupTests,
- createLive,
+ ConfigCommand,
+ createMultipleServers,
doubleFollow,
- flushAndRunMultipleServers,
- generateUser,
- getCustomConfigResolutions,
- getVideo,
- runAndTestFfmpegStreamError,
- ServerInfo,
+ PeerTubeServer,
setAccessTokensToServers,
setDefaultVideoChannel,
- updateCustomSubConfig,
- updateUser,
wait,
- waitJobs,
- waitUntilLivePublished
+ waitJobs
} from '../../../../shared/extra-utils'
const expect = chai.expect
describe('Test live constraints', function () {
- let servers: ServerInfo[] = []
+ let servers: PeerTubeServer[] = []
let userId: number
let userAccessToken: string
let userChannelId: number
@@ -39,15 +32,13 @@ 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].live.create({ token: userAccessToken, fields: liveAttributes })
+ return uuid
}
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.videos.get({ id: videoId })
expect(video.isLive).to.be.false
expect(video.duration).to.be.greaterThan(0)
}
@@ -57,14 +48,12 @@ describe('Test live constraints', function () {
async function waitUntilLivePublishedOnAllServers (videoId: string) {
for (const server of servers) {
- await waitUntilLivePublished(server.url, server.accessToken, videoId)
+ await server.live.waitUntilPublished({ videoId })
}
}
function updateQuota (options: { total: number, daily: number }) {
- return updateUser({
- url: servers[0].url,
- accessToken: servers[0].accessToken,
+ return servers[0].users.update({
userId,
videoQuota: options.total,
videoQuotaDaily: options.daily
@@ -74,24 +63,26 @@ 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)
await setDefaultVideoChannel(servers)
- await updateCustomSubConfig(servers[0].url, servers[0].accessToken, {
- live: {
- enabled: true,
- allowReplay: true,
- transcoding: {
- enabled: false
+ await servers[0].config.updateCustomSubConfig({
+ newConfig: {
+ live: {
+ enabled: true,
+ allowReplay: true,
+ transcoding: {
+ enabled: false
+ }
}
}
})
{
- const res = await generateUser(servers[0], 'user1')
+ const res = await servers[0].users.generate('user1')
userId = res.userId
userChannelId = res.userChannelId
userAccessToken = res.token
@@ -107,7 +98,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].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 () {
@@ -117,7 +108,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].live.runAndTestStreamError({ token: userAccessToken, videoId: userVideoLiveoId, shouldHaveError: true })
await waitUntilLivePublishedOnAllServers(userVideoLiveoId)
await waitJobs(servers)
@@ -134,7 +125,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].live.runAndTestStreamError({ token: userAccessToken, videoId: userVideoLiveoId, shouldHaveError: true })
await waitUntilLivePublishedOnAllServers(userVideoLiveoId)
await waitJobs(servers)
@@ -151,26 +142,28 @@ 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].live.runAndTestStreamError({ token: userAccessToken, videoId: userVideoLiveoId, shouldHaveError: false })
})
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].config.updateCustomSubConfig({
+ newConfig: {
+ live: {
enabled: true,
- resolutions: getCustomConfigResolutions(true)
+ allowReplay: true,
+ maxDuration: 1,
+ transcoding: {
+ enabled: true,
+ resolutions: ConfigCommand.getCustomConfigResolutions(true)
+ }
}
}
})
const userVideoLiveoId = await createLiveWrapper(true)
- await runAndTestFfmpegStreamError(servers[0].url, userAccessToken, userVideoLiveoId, 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 71b7d28a8..f07d4cfec 100644
--- a/server/tests/api/live/live-permanent.ts
+++ b/server/tests/api/live/live-permanent.ts
@@ -2,59 +2,50 @@
import 'mocha'
import * as chai from 'chai'
-import { LiveVideoCreate, VideoDetails, VideoPrivacy, VideoState } from '@shared/models'
+import { LiveVideoCreate, VideoPrivacy, VideoState } from '@shared/models'
import {
cleanupTests,
- createLive,
+ ConfigCommand,
+ createMultipleServers,
doubleFollow,
- flushAndRunMultipleServers,
- getCustomConfigResolutions,
- getLive,
- getPlaylistsCount,
- getVideo,
- sendRTMPStreamInVideo,
- ServerInfo,
+ PeerTubeServer,
setAccessTokensToServers,
setDefaultVideoChannel,
stopFfmpeg,
- updateCustomSubConfig,
- updateLive,
wait,
- waitJobs,
- waitUntilLivePublished,
- waitUntilLiveWaiting
+ waitJobs
} from '../../../../shared/extra-utils'
const expect = chai.expect
describe('Permanent live', function () {
- let servers: ServerInfo[] = []
+ let servers: PeerTubeServer[] = []
let videoUUID: string
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 res = await createLive(servers[0].url, servers[0].accessToken, attributes)
- return res.body.video.uuid
+ const { uuid } = await servers[0].live.create({ fields: attributes })
+ return uuid
}
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.videos.get({ id: videoId })
+ expect(video.state.id).to.equal(state)
}
}
before(async function () {
this.timeout(120000)
- servers = await flushAndRunMultipleServers(2)
+ servers = await createMultipleServers(2)
// Get the access tokens
await setAccessTokensToServers(servers)
@@ -63,14 +54,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].config.updateCustomSubConfig({
+ newConfig: {
+ live: {
enabled: true,
- resolutions: getCustomConfigResolutions(true)
+ allowReplay: true,
+ maxDuration: -1,
+ transcoding: {
+ enabled: true,
+ resolutions: ConfigCommand.getCustomConfigResolutions(true)
+ }
}
}
})
@@ -82,15 +75,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].live.get({ videoId: videoUUID })
+ expect(live.permanentLive).to.be.false
}
- await updateLive(servers[0].url, servers[0].accessToken, videoUUID, { permanentLive: true })
+ await servers[0].live.update({ 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].live.get({ videoId: videoUUID })
+ expect(live.permanentLive).to.be.true
}
})
@@ -99,8 +92,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].live.get({ videoId: videoUUID })
+ expect(live.permanentLive).to.be.true
await waitJobs(servers)
})
@@ -108,16 +101,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].live.sendRTMPStreamInVideo({ videoId: videoUUID })
for (const server of servers) {
- await waitUntilLivePublished(server.url, server.accessToken, videoUUID)
+ await server.live.waitUntilPublished({ 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].live.waitUntilWaiting({ videoId: videoUUID })
await waitJobs(servers)
})
@@ -129,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.videos.get({ id: videoUUID })
expect(videoDetails.streamingPlaylists).to.have.lengthOf(1)
}
})
@@ -145,31 +136,33 @@ 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].config.updateCustomSubConfig({
+ newConfig: {
+ live: {
enabled: true,
- resolutions: getCustomConfigResolutions(false)
+ allowReplay: true,
+ maxDuration: -1,
+ transcoding: {
+ enabled: true,
+ resolutions: ConfigCommand.getCustomConfigResolutions(false)
+ }
}
}
})
- const command = await sendRTMPStreamInVideo(servers[0].url, servers[0].accessToken, videoUUID)
+ const ffmpegCommand = await servers[0].live.sendRTMPStreamInVideo({ videoId: videoUUID })
for (const server of servers) {
- await waitUntilLivePublished(server.url, server.accessToken, videoUUID)
+ await server.live.waitUntilPublished({ videoId: videoUUID })
}
await checkVideoState(videoUUID, VideoState.PUBLISHED)
- const count = await getPlaylistsCount(servers[0], videoUUID)
+ const count = await servers[0].live.countPlaylists({ 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 3d4736c8f..bd15396ec 100644
--- a/server/tests/api/live/live-save-replay.ts
+++ b/server/tests/api/live/live-save-replay.ts
@@ -3,97 +3,85 @@
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 {
- addVideoToBlacklist,
checkLiveCleanup,
cleanupTests,
- createLive,
+ ConfigCommand,
+ createMultipleServers,
doubleFollow,
- flushAndRunMultipleServers,
- getCustomConfigResolutions,
- getVideo,
- getVideosList,
- removeVideo,
- sendRTMPStreamInVideo,
- ServerInfo,
+ PeerTubeServer,
setAccessTokensToServers,
setDefaultVideoChannel,
stopFfmpeg,
testFfmpegStreamError,
- updateCustomSubConfig,
- updateVideo,
wait,
- waitJobs,
- waitUntilLiveEnded,
- waitUntilLivePublished,
- waitUntilLiveSaved
-} from '../../../../shared/extra-utils'
+ waitJobs
+} from '@shared/extra-utils'
+import { HttpStatusCode, 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
async function createLiveWrapper (saveReplay: boolean) {
if (liveVideoUUID) {
try {
- await removeVideo(servers[0].url, servers[0].accessToken, 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 res = await createLive(servers[0].url, servers[0].accessToken, attributes)
- return res.body.video.uuid
+ const { uuid } = await servers[0].live.create({ fields: attributes })
+ 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.videos.list()
+ expect(data).to.have.lengthOf(length)
+ expect(total).to.equal(length)
- if (getStatus) {
- await getVideo(server.url, videoId, getStatus)
+ if (expectedStatus) {
+ await server.videos.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.videos.get({ id: videoId })
+ expect(video.state.id).to.equal(state)
}
}
async function waitUntilLivePublishedOnAllServers (videoId: string) {
for (const server of servers) {
- await waitUntilLivePublished(server.url, server.accessToken, videoId)
+ await server.live.waitUntilPublished({ videoId })
}
}
async function waitUntilLiveSavedOnAllServers (videoId: string) {
for (const server of servers) {
- await waitUntilLiveSaved(server.url, server.accessToken, videoId)
+ await server.live.waitUntilSaved({ videoId })
}
}
before(async function () {
this.timeout(120000)
- servers = await flushAndRunMultipleServers(2)
+ servers = await createMultipleServers(2)
// Get the access tokens
await setAccessTokensToServers(servers)
@@ -102,14 +90,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].config.updateCustomSubConfig({
+ newConfig: {
+ live: {
+ enabled: true,
+ allowReplay: true,
+ maxDuration: -1,
+ transcoding: {
+ enabled: false,
+ resolutions: ConfigCommand.getCustomConfigResolutions(true)
+ }
}
}
})
@@ -135,7 +125,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].live.sendRTMPStreamInVideo({ videoId: liveVideoUUID })
await waitUntilLivePublishedOnAllServers(liveVideoUUID)
@@ -151,7 +141,7 @@ describe('Save replay setting', function () {
await stopFfmpeg(ffmpegCommand)
for (const server of servers) {
- await waitUntilLiveEnded(server.url, server.accessToken, liveVideoUUID)
+ await server.live.waitUntilEnded({ videoId: liveVideoUUID })
}
await waitJobs(servers)
@@ -168,7 +158,7 @@ describe('Save replay setting', function () {
liveVideoUUID = await createLiveWrapper(false)
- ffmpegCommand = await sendRTMPStreamInVideo(servers[0].url, servers[0].accessToken, liveVideoUUID)
+ ffmpegCommand = await servers[0].live.sendRTMPStreamInVideo({ videoId: liveVideoUUID })
await waitUntilLivePublishedOnAllServers(liveVideoUUID)
@@ -176,7 +166,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].blacklist.add({ videoId: liveVideoUUID, reason: 'bad live', unfederate: true }),
testFfmpegStreamError(ffmpegCommand, true)
])
@@ -184,8 +174,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].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)
@@ -197,7 +187,7 @@ describe('Save replay setting', function () {
liveVideoUUID = await createLiveWrapper(false)
- ffmpegCommand = await sendRTMPStreamInVideo(servers[0].url, servers[0].accessToken, liveVideoUUID)
+ ffmpegCommand = await servers[0].live.sendRTMPStreamInVideo({ videoId: liveVideoUUID })
await waitUntilLivePublishedOnAllServers(liveVideoUUID)
@@ -206,7 +196,7 @@ describe('Save replay setting', function () {
await Promise.all([
testFfmpegStreamError(ffmpegCommand, true),
- removeVideo(servers[0].url, servers[0].accessToken, liveVideoUUID)
+ servers[0].videos.remove({ id: liveVideoUUID })
])
await wait(5000)
@@ -233,7 +223,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].live.sendRTMPStreamInVideo({ videoId: liveVideoUUID })
await waitUntilLivePublishedOnAllServers(liveVideoUUID)
await waitJobs(servers)
@@ -258,13 +248,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].videos.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.videos.get({ id: liveVideoUUID })
+ expect(video.name).to.equal('video updated')
+ expect(video.isLive).to.be.false
}
})
@@ -277,14 +267,14 @@ describe('Save replay setting', function () {
liveVideoUUID = await createLiveWrapper(true)
- ffmpegCommand = await sendRTMPStreamInVideo(servers[0].url, servers[0].accessToken, 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([
- addVideoToBlacklist(servers[0].url, servers[0].accessToken, liveVideoUUID, 'bad live', true),
+ servers[0].blacklist.add({ videoId: liveVideoUUID, reason: 'bad live', unfederate: true }),
testFfmpegStreamError(ffmpegCommand, true)
])
@@ -292,8 +282,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].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)
@@ -305,14 +295,14 @@ describe('Save replay setting', function () {
liveVideoUUID = await createLiveWrapper(true)
- ffmpegCommand = await sendRTMPStreamInVideo(servers[0].url, servers[0].accessToken, 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([
- removeVideo(servers[0].url, servers[0].accessToken, 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 e00909ade..2a1f9f108 100644
--- a/server/tests/api/live/live-socket-messages.ts
+++ b/server/tests/api/live/live-socket-messages.ts
@@ -2,47 +2,42 @@
import 'mocha'
import * as chai from 'chai'
-import { getLiveNotificationSocket } from '@shared/extra-utils/socket/socket-io'
import { VideoPrivacy, VideoState } from '@shared/models'
import {
cleanupTests,
- createLive,
+ createMultipleServers,
doubleFollow,
- flushAndRunMultipleServers,
- getVideoIdFromUUID,
- sendRTMPStreamInVideo,
- ServerInfo,
+ PeerTubeServer,
setAccessTokensToServers,
setDefaultVideoChannel,
stopFfmpeg,
- updateCustomSubConfig,
- viewVideo,
wait,
waitJobs,
- waitUntilLiveEnded,
waitUntilLivePublishedOnAllServers
} from '../../../../shared/extra-utils'
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)
await setDefaultVideoChannel(servers)
- await updateCustomSubConfig(servers[0].url, servers[0].accessToken, {
- live: {
- enabled: true,
- allowReplay: true,
- transcoding: {
- enabled: false
+ await servers[0].config.updateCustomSubConfig({
+ newConfig: {
+ live: {
+ enabled: true,
+ allowReplay: true,
+ transcoding: {
+ enabled: false
+ }
}
}
})
@@ -56,12 +51,12 @@ 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 res = await createLive(servers[0].url, servers[0].accessToken, liveAttributes)
- return res.body.video.uuid
+ const { uuid } = await servers[0].live.create({ fields: liveAttributes })
+ return uuid
}
it('Should correctly send a message when the live starts and ends', async function () {
@@ -74,22 +69,22 @@ describe('Test live', function () {
await waitJobs(servers)
{
- const videoId = await getVideoIdFromUUID(servers[0].url, liveVideoUUID)
+ const videoId = await servers[0].videos.getId({ uuid: liveVideoUUID })
- const localSocket = getLiveNotificationSocket(servers[0].url)
+ const localSocket = servers[0].socketIO.getLiveNotificationSocket()
localSocket.on('state-change', data => localStateChanges.push(data.state))
localSocket.emit('subscribe', { videoId })
}
{
- const videoId = await getVideoIdFromUUID(servers[1].url, liveVideoUUID)
+ const videoId = await servers[1].videos.getId({ uuid: liveVideoUUID })
- const remoteSocket = getLiveNotificationSocket(servers[1].url)
+ const remoteSocket = servers[1].socketIO.getLiveNotificationSocket()
remoteSocket.on('state-change', data => remoteStateChanges.push(data.state))
remoteSocket.emit('subscribe', { videoId })
}
- const command = await sendRTMPStreamInVideo(servers[0].url, servers[0].accessToken, liveVideoUUID)
+ const ffmpegCommand = await servers[0].live.sendRTMPStreamInVideo({ videoId: liveVideoUUID })
await waitUntilLivePublishedOnAllServers(servers, liveVideoUUID)
await waitJobs(servers)
@@ -99,10 +94,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.live.waitUntilEnded({ videoId: liveVideoUUID })
}
await waitJobs(servers)
@@ -122,22 +117,22 @@ describe('Test live', function () {
await waitJobs(servers)
{
- const videoId = await getVideoIdFromUUID(servers[0].url, liveVideoUUID)
+ const videoId = await servers[0].videos.getId({ uuid: liveVideoUUID })
- const localSocket = getLiveNotificationSocket(servers[0].url)
+ const localSocket = servers[0].socketIO.getLiveNotificationSocket()
localSocket.on('views-change', data => { localLastVideoViews = data.views })
localSocket.emit('subscribe', { videoId })
}
{
- const videoId = await getVideoIdFromUUID(servers[1].url, liveVideoUUID)
+ const videoId = await servers[1].videos.getId({ uuid: liveVideoUUID })
- const remoteSocket = getLiveNotificationSocket(servers[1].url)
+ const remoteSocket = servers[1].socketIO.getLiveNotificationSocket()
remoteSocket.on('views-change', data => { remoteLastVideoViews = data.views })
remoteSocket.emit('subscribe', { videoId })
}
- const command = await sendRTMPStreamInVideo(servers[0].url, servers[0].accessToken, liveVideoUUID)
+ const ffmpegCommand = await servers[0].live.sendRTMPStreamInVideo({ videoId: liveVideoUUID })
await waitUntilLivePublishedOnAllServers(servers, liveVideoUUID)
await waitJobs(servers)
@@ -145,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].videos.view({ id: liveVideoUUID })
+ await servers[1].videos.view({ id: liveVideoUUID })
await waitJobs(servers)
await wait(5000)
@@ -155,7 +150,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 () {
@@ -166,13 +161,13 @@ describe('Test live', function () {
const liveVideoUUID = await createLiveWrapper()
await waitJobs(servers)
- const videoId = await getVideoIdFromUUID(servers[0].url, liveVideoUUID)
+ const videoId = await servers[0].videos.getId({ uuid: liveVideoUUID })
- const socket = getLiveNotificationSocket(servers[0].url)
+ const socket = servers[0].socketIO.getLiveNotificationSocket()
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].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 a44d21ffa..5e3a79c64 100644
--- a/server/tests/api/live/live-views.ts
+++ b/server/tests/api/live/live-views.ts
@@ -3,20 +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,
- createLive,
+ createMultipleServers,
doubleFollow,
- flushAndRunMultipleServers,
- getVideo,
- sendRTMPStreamInVideo,
- ServerInfo,
+ PeerTubeServer,
setAccessTokensToServers,
setDefaultVideoChannel,
stopFfmpeg,
- updateCustomSubConfig,
- viewVideo,
wait,
waitJobs,
waitUntilLivePublishedOnAllServers
@@ -25,23 +20,25 @@ 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)
await setDefaultVideoChannel(servers)
- await updateCustomSubConfig(servers[0].url, servers[0].accessToken, {
- live: {
- enabled: true,
- allowReplay: true,
- transcoding: {
- enabled: false
+ await servers[0].config.updateCustomSubConfig({
+ newConfig: {
+ live: {
+ enabled: true,
+ allowReplay: true,
+ transcoding: {
+ enabled: false
+ }
}
}
})
@@ -56,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.videos.get({ id: liveVideoId })
expect(video.views).to.equal(expected)
}
}
@@ -68,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 res = await createLive(servers[0].url, servers[0].accessToken, liveAttributes)
- liveVideoId = res.body.video.uuid
+ const live = await servers[0].live.create({ fields: liveAttributes })
+ liveVideoId = live.uuid
- command = await sendRTMPStreamInVideo(servers[0].url, servers[0].accessToken, liveVideoId)
+ command = await servers[0].live.sendRTMPStreamInVideo({ videoId: liveVideoId })
await waitUntilLivePublishedOnAllServers(servers, liveVideoId)
await waitJobs(servers)
})
@@ -87,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].videos.view({ id: liveVideoId })
+ await servers[0].videos.view({ id: liveVideoId })
await wait(7000)
@@ -109,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].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 50397924e..4676a840a 100644
--- a/server/tests/api/live/live.ts
+++ b/server/tests/api/live/live.ts
@@ -4,73 +4,68 @@ 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 {
- addVideoToBlacklist,
- buildServerDirectory,
checkLiveCleanup,
checkLiveSegmentHash,
checkResolutionsInMasterPlaylist,
cleanupTests,
- createLive,
+ createMultipleServers,
doubleFollow,
- flushAndRunMultipleServers,
- getLive,
- getMyVideosWithFilter,
- getPlaylist,
- getVideo,
- getVideosList,
- getVideosWithFilters,
killallServers,
+ LiveCommand,
makeRawRequest,
- removeVideo,
- reRunServer,
+ PeerTubeServer,
sendRTMPStream,
- sendRTMPStreamInVideo,
- ServerInfo,
setAccessTokensToServers,
setDefaultVideoChannel,
stopFfmpeg,
testFfmpegStreamError,
testImage,
- updateCustomSubConfig,
- updateLive,
- uploadVideoAndGetId,
wait,
waitJobs,
- waitUntilLiveEnded,
- waitUntilLivePublished,
- waitUntilLivePublishedOnAllServers,
- waitUntilLiveSegmentGeneration
-} from '../../../../shared/extra-utils'
+ waitUntilLivePublishedOnAllServers
+} from '@shared/extra-utils'
+import {
+ HttpStatusCode,
+ LiveVideo,
+ LiveVideoCreate,
+ VideoDetails,
+ VideoPrivacy,
+ VideoState,
+ VideoStreamingPlaylistType
+} from '@shared/models'
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)
await setDefaultVideoChannel(servers)
- await updateCustomSubConfig(servers[0].url, servers[0].accessToken, {
- live: {
- enabled: true,
- allowReplay: true,
- transcoding: {
- enabled: false
+ await servers[0].config.updateCustomSubConfig({
+ newConfig: {
+ live: {
+ enabled: true,
+ allowReplay: true,
+ transcoding: {
+ enabled: false
+ }
}
}
})
// Server 1 and server 2 follow each other
await doubleFollow(servers[0], servers[1])
+
+ commands = servers.map(s => s.live)
})
describe('Live creation, update and delete', function () {
@@ -85,7 +80,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',
@@ -98,14 +93,13 @@ 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].create({ fields: attributes })
+ liveVideoUUID = live.uuid
await waitJobs(servers)
for (const server of servers) {
- const resVideo = await getVideo(server.url, liveVideoUUID)
- const video: VideoDetails = resVideo.body
+ const video = await server.videos.get({ id: liveVideoUUID })
expect(video.category.id).to.equal(1)
expect(video.licence.id).to.equal(2)
@@ -113,8 +107,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
@@ -129,8 +123,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.live.get({ videoId: liveVideoUUID })
if (server.url === servers[0].url) {
expect(live.rtmpUrl).to.equal('rtmp://' + server.hostname + ':' + servers[0].rtmpPort + '/live')
@@ -149,20 +142,18 @@ 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
}
- const res = await createLive(servers[0].url, servers[0].accessToken, attributes)
- const videoId = res.body.video.uuid
+ const live = await commands[0].create({ fields: attributes })
+ const videoId = live.uuid
await waitJobs(servers)
for (const server of servers) {
- const resVideo = await getVideo(server.url, videoId)
- const video: VideoDetails = resVideo.body
-
+ const video = await server.videos.get({ id: videoId })
expect(video.privacy.id).to.equal(VideoPrivacy.UNLISTED)
expect(video.nsfw).to.be.true
@@ -173,28 +164,27 @@ 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.videos.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 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].update({ 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].update({ 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.live.get({ videoId: liveVideoUUID })
if (server.url === servers[0].url) {
expect(live.rtmpUrl).to.equal('rtmp://' + server.hostname + ':' + servers[0].rtmpPort + '/live')
@@ -211,77 +201,75 @@ 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].videos.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 getLive(server.url, server.accessToken, liveVideoUUID, 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 })
}
})
})
describe('Live filters', function () {
- let command: any
+ let ffmpegCommand: any
let liveVideoId: string
let vodVideoId: string
before(async function () {
this.timeout(120000)
- vodVideoId = (await uploadVideoAndGetId({ server: servers[0], videoName: '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 resLive = await createLive(servers[0].url, servers[0].accessToken, liveOptions)
- liveVideoId = resLive.body.video.uuid
+ const liveOptions = { name: 'live', privacy: VideoPrivacy.PUBLIC, channelId: servers[0].store.channel.id }
+ const live = await commands[0].create({ fields: liveOptions })
+ liveVideoId = live.uuid
- command = await sendRTMPStreamInVideo(servers[0].url, servers[0].accessToken, liveVideoId)
+ ffmpegCommand = await servers[0].live.sendRTMPStreamInVideo({ videoId: liveVideoId })
await waitUntilLivePublishedOnAllServers(servers, liveVideoId)
await waitJobs(servers)
})
it('Should only display lives', async function () {
- const res = await getVideosWithFilters(servers[0].url, { isLive: true })
+ const { data, total } = await servers[0].videos.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].videos.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 () {
this.timeout(60000)
- await stopFfmpeg(command)
+ 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].videos.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].videos.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].videos.remove({ id: vodVideoId })
+ await servers[0].videos.remove({ id: liveVideoId })
})
})
@@ -296,18 +284,17 @@ 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
}
- const res = await createLive(servers[0].url, servers[0].accessToken, liveAttributes)
- const uuid = res.body.video.uuid
+ const { uuid } = await commands[0].create({ fields: liveAttributes })
- const resLive = await getLive(servers[0].url, servers[0].accessToken, uuid)
- const resVideo = await getVideo(servers[0].url, uuid)
+ const live = await commands[0].get({ videoId: uuid })
+ const video = await servers[0].videos.get({ id: uuid })
- return Object.assign(resVideo.body, resLive.body) as LiveVideo & VideoDetails
+ return Object.assign(video, live)
}
it('Should not allow a stream without the appropriate path', async function () {
@@ -335,13 +322,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)
+ const { total, data } = await server.videos.list()
- expect(res.body.total).to.equal(1)
- expect(res.body.data).to.have.lengthOf(1)
-
- 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
}
@@ -352,7 +338,7 @@ describe('Test live', function () {
liveVideo = await createLiveWrapper()
- await addVideoToBlacklist(servers[0].url, servers[0].accessToken, liveVideo.uuid)
+ await servers[0].blacklist.add({ videoId: liveVideo.uuid })
const command = sendRTMPStream(rtmpUrl + '/live', liveVideo.streamKey)
await testFfmpegStreamError(command, true)
@@ -363,7 +349,7 @@ describe('Test live', function () {
liveVideo = await createLiveWrapper()
- await removeVideo(servers[0].url, servers[0].accessToken, liveVideo.uuid)
+ await servers[0].videos.remove({ id: liveVideo.uuid })
const command = sendRTMPStream(rtmpUrl + '/live', liveVideo.streamKey)
await testFfmpegStreamError(command, true)
@@ -376,24 +362,21 @@ 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
}
- const res = await createLive(servers[0].url, servers[0].accessToken, liveAttributes)
- return res.body.video.uuid
+ const { uuid } = await commands[0].create({ fields: liveAttributes })
+ return uuid
}
async function testVideoResolutions (liveVideoId: string, resolutions: number[]) {
for (const server of servers) {
- const resList = await getVideosList(server.url)
- const videos: Video[] = resList.body.data
+ const { data } = await server.videos.list()
+ expect(data.find(v => v.uuid === liveVideoId)).to.exist
- expect(videos.find(v => v.uuid === liveVideoId)).to.exist
-
- const resVideo = await getVideo(server.url, liveVideoId)
- const video: VideoDetails = resVideo.body
+ const video = await server.videos.get({ id: liveVideoId })
expect(video.streamingPlaylists).to.have.lengthOf(1)
@@ -403,39 +386,48 @@ 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 waitUntilLiveSegmentGeneration(servers[0], video.uuid, i, 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
+ const subPlaylist = await servers[0].streamingPlaylists.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
+ })
}
}
}
function updateConf (resolutions: number[]) {
- return updateCustomSubConfig(servers[0].url, servers[0].accessToken, {
- live: {
- enabled: true,
- allowReplay: true,
- maxDuration: -1,
- transcoding: {
+ return servers[0].config.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)
+ }
}
}
}
@@ -451,13 +443,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 () {
@@ -467,13 +459,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 () {
@@ -484,14 +476,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].waitUntilEnded({ videoId: liveVideoId })
await waitJobs(servers)
@@ -504,8 +496,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.videos.get({ id: liveVideoId })
expect(video.state.id).to.equal(VideoState.PUBLISHED)
expect(video.duration).to.be.greaterThan(1)
@@ -530,7 +521,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].servers.buildDirectory(join('streaming-playlists', 'hls', video.uuid, filename))
const probe = await ffprobePromise(segmentPath)
const videoStream = await getVideoStreamFromFile(segmentPath, probe)
@@ -557,13 +548,13 @@ 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
}
- const res = await createLive(servers[0].url, servers[0].accessToken, liveAttributes)
- return res.body.video.uuid
+ const { uuid } = await commands[0].create({ fields: liveAttributes })
+ return uuid
}
before(async function () {
@@ -573,20 +564,20 @@ 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].waitUntilPublished({ videoId: liveVideoId }),
+ commands[0].waitUntilPublished({ videoId: liveVideoReplayId })
])
- await waitUntilLiveSegmentGeneration(servers[0], liveVideoId, 0, 2)
- await waitUntilLiveSegmentGeneration(servers[0], liveVideoReplayId, 0, 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] ])
- await reRunServer(servers[0])
+ await servers[0].run()
await wait(5000)
})
@@ -594,13 +585,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].waitUntilEnded({ 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].waitUntilPublished({ videoId: liveVideoReplayId })
})
})
diff --git a/server/tests/api/moderation/abuses.ts b/server/tests/api/moderation/abuses.ts
index fb765e7e3..8d6360eb3 100644
--- a/server/tests/api/moderation/abuses.ts
+++ b/server/tests/api/moderation/abuses.ts
@@ -3,70 +3,37 @@
import 'mocha'
import * as chai from 'chai'
import {
- AbuseFilter,
- AbuseMessage,
- AbusePredefinedReasonsString,
- AbuseState,
- Account,
- AdminAbuse,
- UserAbuse,
- VideoComment
-} from '@shared/models'
-import {
- addAbuseMessage,
- addVideoCommentThread,
+ AbusesCommand,
cleanupTests,
- createUser,
- deleteAbuse,
- deleteAbuseMessage,
- deleteVideoComment,
- flushAndRunMultipleServers,
- generateUserAccessToken,
- getAccount,
- getAdminAbusesList,
- getUserAbusesList,
- getVideoCommentThreads,
- getVideoIdFromUUID,
- getVideosList,
- immutableAssign,
- listAbuseMessages,
- removeUser,
- removeVideo,
- reportAbuse,
- ServerInfo,
+ createMultipleServers,
+ doubleFollow,
+ PeerTubeServer,
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'
+ waitJobs
+} from '@shared/extra-utils'
+import { AbuseMessage, AbusePredefinedReasonsString, AbuseState, AdminAbuse, UserAbuse } from '@shared/models'
const expect = chai.expect
describe('Test abuses', function () {
- let servers: ServerInfo[] = []
+ let servers: PeerTubeServer[] = []
let abuseServer1: AdminAbuse
let abuseServer2: AdminAbuse
+ let commands: AbusesCommand[]
before(async function () {
this.timeout(50000)
// Run servers
- servers = await flushAndRunMultipleServers(2)
+ servers = await createMultipleServers(2)
// Get the access tokens
await setAccessTokensToServers(servers)
// Server 1 and server 2 follow each other
await doubleFollow(servers[0], servers[1])
+
+ commands = servers.map(s => s.abuses)
})
describe('Video abuses', function () {
@@ -75,179 +42,189 @@ 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].videos.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].videos.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
+ const { data } = await servers[0].videos.list()
+ expect(data.length).to.equal(2)
- expect(videos.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].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 () {
- 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].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)
})
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].store.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 () {
this.timeout(10000)
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 })
+ const videoId = await servers[0].videos.getId({ uuid: servers[1].store.video.uuid })
+ 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].store.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].store.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 () {
this.timeout(10000)
{
- 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' })
+ 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)
- 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
{
- await addAccountToServerBlocklist(servers[0].url, servers[0].accessToken, accountToBlock)
+ await servers[0].blocklist.addToServerBlocklist({ account: 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)
+ await servers[0].blocklist.removeFromServerBlocklist({ account: 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)
}
})
@@ -255,35 +232,35 @@ describe('Test abuses', function () {
const serverToBlock = servers[1].host
{
- await addServerToServerBlocklist(servers[0].url, servers[0].accessToken, servers[1].host)
+ await servers[0].blocklist.addToServerBlocklist({ server: serverToBlock })
- 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)
+ await servers[0].blocklist.removeFromServerBlocklist({ server: 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)
}
})
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].videos.remove({ id: abuseServer2.video.uuid })
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
@@ -295,39 +272,36 @@ 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)
+ await servers[0].users.create({ ...user })
+ const userAccessToken = await servers[0].login.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'
}
- 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 { id } = await servers[0].videos.upload({ token: userAccessToken, attributes })
+ const video3Id = 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].store.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")
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")
}
})
@@ -337,20 +311,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,
- videoId: servers[0].video.id,
+ const createRes = await commands[0].report({
+ videoId: servers[0].store.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 +333,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
- }
+ async function list (query: Parameters[0]) {
+ const body = await commands[0].getAdminList(query)
- Object.assign(options, query)
-
- const res = await getAdminAbusesList(options)
-
- return res.body.data as AdminAbuse[]
+ return body.data
}
expect(await list({ id: 56 })).to.have.lengthOf(0)
@@ -424,24 +389,24 @@ describe('Test abuses', function () {
describe('Comment abuses', function () {
- async function getComment (url: string, videoIdArg: number | string) {
+ async function getComment (server: PeerTubeServer, videoIdArg: number | string) {
const videoId = typeof videoIdArg === 'string'
- ? await getVideoIdFromUUID(url, videoIdArg)
+ ? await server.videos.getId({ uuid: videoIdArg })
: videoIdArg
- const res = await getVideoCommentThreads(url, videoId, 0, 5)
+ const { data } = await server.comments.listThreads({ videoId })
- return res.body.data[0] as VideoComment
+ return data[0]
}
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].store.video = await servers[0].videos.quickUpload({ name: 'server 1' })
+ servers[1].store.video = await servers[1].videos.quickUpload({ name: '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].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)
})
@@ -449,23 +414,23 @@ 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].store.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)
})
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 comment = await getComment(servers[0], servers[0].store.video.id)
+ 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')
@@ -477,98 +442,102 @@ 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)
}
{
- 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)
}
})
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].store.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)
})
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].store.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].store.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 () {
this.timeout(10000)
- const commentServer2 = await getComment(servers[0].url, servers[1].video.id)
+ const commentServer2 = await getComment(servers[0], servers[1].store.video.id)
- await deleteVideoComment(servers[0].url, servers[0].accessToken, servers[1].video.uuid, commentServer2.id)
+ await servers[0].comments.delete({ videoId: servers[1].store.video.uuid, commentId: commentServer2.id })
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,72 +548,60 @@ 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 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 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 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')
}
})
})
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: PeerTubeServer, targetName: string, targetServer: PeerTubeServer) {
+ return server.accounts.get({ accountName: targetName + '@' + targetServer.host })
}
before(async function () {
this.timeout(50000)
- await createUser({ url: servers[0].url, accessToken: servers[0].accessToken, username: 'user_1', password: 'donald' })
+ await servers[0].users.create({ username: 'user_1', password: 'donald' })
- const token = await generateUserAccessToken(servers[1], 'user_2')
- await uploadVideo(servers[1].url, token, { 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)
})
@@ -652,22 +609,22 @@ 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 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,96 +638,100 @@ 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)
}
})
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 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 () {
this.timeout(10000)
- const account = await getAccountFromServer(servers[1].url, 'user_2', servers[1])
- await removeUser(servers[1].url, account.userId, servers[1].accessToken)
+ const account = await getAccountFromServer(servers[1], 'user_2', servers[1])
+ await servers[1].users.remove({ userId: account.userId })
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 +739,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')
})
})
@@ -800,20 +759,20 @@ describe('Test abuses', function () {
let userAccessToken: string
before(async function () {
- userAccessToken = await generateUserAccessToken(servers[0], 'user_42')
+ userAccessToken = await servers[0].users.generateUserAndToken('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].store.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' })
+ const videoId = await servers[0].videos.getId({ uuid: servers[1].store.video.uuid })
+ 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 +780,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 })
+ const body = await commands[0].getUserList({ token: userAccessToken, id: abuseId1 })
+ expect(body.total).to.equal(1)
- expect(res.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'
- })
+ const body = await commands[0].getUserList({ token: userAccessToken, search: 'server 2' })
+ expect(body.total).to.equal(1)
- expect(res.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)
+ await commands[0].update({ abuseId: abuseId1, body: { state: AbuseState.REJECTED } })
- const res = await getUserAbusesList({
- url: servers[0].url,
- token: userAccessToken,
- state: AbuseState.REJECTED
- })
+ const body = await commands[0].getUserList({ token: userAccessToken, state: AbuseState.REJECTED })
+ expect(body.total).to.equal(1)
- expect(res.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')
+ userToken = await servers[0].users.generateUserAndToken('user_43')
- const res = await reportAbuse({
- url: servers[0].url,
- token: userAccessToken,
- videoId: servers[0].video.id,
- reason: 'user 43 reason 1'
- })
-
- abuseId = res.body.abuse.id
+ const body = await commands[0].report({ token: userToken, videoId: servers[0].store.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 +858,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 +889,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/moderation/blocklist-notification.ts b/server/tests/api/moderation/blocklist-notification.ts
index 4fb3c95f2..75b15c298 100644
--- a/server/tests/api/moderation/blocklist-notification.ts
+++ b/server/tests/api/moderation/blocklist-notification.ts
@@ -2,47 +2,22 @@
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 {
- cleanupTests,
- createUser,
- doubleFollow,
- flushAndRunMultipleServers,
- ServerInfo,
- 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'
+import { cleanupTests, createMultipleServers, doubleFollow, PeerTubeServer, setAccessTokensToServers, waitJobs } from '@shared/extra-utils'
+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: 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)
for (const type of expected) {
- expect(notifications.find(n => n.type === type)).to.exist
+ expect(data.find(n => n.type === type)).to.exist
}
}
describe('Test blocklist', function () {
- let servers: ServerInfo[]
+ let servers: PeerTubeServer[]
let videoUUID: string
let userToken1: string
@@ -51,30 +26,34 @@ 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].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 markAsReadAllNotifications(servers[0].url, userToken1)
- await markAsReadAllNotifications(servers[0].url, userToken2)
+ await servers[0].notifications.markAsReadAll({ token: userToken1 })
+ await servers[0].notifications.markAsReadAll({ token: userToken2 })
{
- const res = await uploadVideo(servers[0].url, userToken1, { name: 'video' })
- videoUUID = res.body.video.uuid
+ const { uuid } = await servers[0].videos.upload({ token: userToken1, attributes: { name: 'video' } })
+ videoUUID = uuid
await waitJobs(servers)
}
{
- await addVideoCommentThread(servers[1].url, remoteUserToken, videoUUID, '@user2@' + servers[0].host + ' hello')
+ await servers[1].comments.createThread({
+ token: remoteUserToken,
+ videoId: videoUUID,
+ text: '@user2@' + servers[0].host + ' hello'
+ })
}
{
- 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].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)
@@ -83,36 +62,34 @@ describe('Test blocklist', function () {
before(async function () {
this.timeout(60000)
- servers = await flushAndRunMultipleServers(2)
+ servers = await createMultipleServers(2)
await setAccessTokensToServers(servers)
{
const user = { username: 'user1', password: 'password' }
- await createUser({
- url: servers[0].url,
- accessToken: servers[0].accessToken,
+ await servers[0].users.create({
username: user.username,
password: user.password,
videoQuota: -1,
videoQuotaDaily: -1
})
- userToken1 = await userLogin(servers[0], user)
- await uploadVideo(servers[0].url, userToken1, { 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 createUser({ url: servers[0].url, accessToken: servers[0].accessToken, username: user.username, password: user.password })
+ await servers[0].users.create({ username: user.username, password: user.password })
- userToken2 = await userLogin(servers[0], user)
+ userToken2 = await servers[0].login.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].users.create({ username: user.username, password: user.password })
- remoteUserToken = await userLogin(servers[1], user)
+ remoteUserToken = await servers[1].login.getAccessToken(user)
}
await doubleFollow(servers[0], servers[1])
@@ -128,26 +105,26 @@ 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 () {
this.timeout(10000)
- await addAccountToAccountBlocklist(servers[0].url, userToken1, 'user3@' + servers[1].host)
+ await servers[0].blocklist.addToMyBlocklist({ token: userToken1, account: 'user3@' + servers[1].host })
await waitJobs(servers)
})
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 removeAccountFromAccountBlocklist(servers[0].url, userToken1, 'user3@' + servers[1].host)
+ await servers[0].blocklist.removeFromMyBlocklist({ token: userToken1, account: 'user3@' + servers[1].host })
})
})
@@ -161,26 +138,26 @@ 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 () {
this.timeout(10000)
- await addServerToAccountBlocklist(servers[0].url, userToken1, servers[1].host)
+ await servers[0].blocklist.addToMyBlocklist({ token: userToken1, server: servers[1].host })
await waitJobs(servers)
})
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 removeServerFromAccountBlocklist(servers[0].url, userToken1, servers[1].host)
+ await servers[0].blocklist.removeFromMyBlocklist({ token: userToken1, server: servers[1].host })
})
})
@@ -195,27 +172,27 @@ 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)
}
})
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].blocklist.addToServerBlocklist({ account: 'user3@' + servers[1].host })
await waitJobs(servers)
})
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 removeAccountFromServerBlocklist(servers[0].url, servers[0].accessToken, 'user3@' + servers[1].host)
+ await servers[0].blocklist.removeFromServerBlocklist({ account: 'user3@' + servers[1].host })
})
})
@@ -230,25 +207,25 @@ 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)
}
})
it('Should block an account', async function () {
this.timeout(10000)
- await addServerToServerBlocklist(servers[0].url, servers[0].accessToken, servers[1].host)
+ await servers[0].blocklist.addToServerBlocklist({ server: servers[1].host })
await waitJobs(servers)
})
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 793abbcb4..089af8b15 100644
--- a/server/tests/api/moderation/blocklist.ts
+++ b/server/tests/api/moderation/blocklist.ts
@@ -3,106 +3,67 @@
import 'mocha'
import * as chai from 'chai'
import {
- addAccountToAccountBlocklist,
- addAccountToServerBlocklist,
- addServerToAccountBlocklist,
- addServerToServerBlocklist,
- addVideoCommentReply,
- addVideoCommentThread,
+ BlocklistCommand,
cleanupTests,
- createUser,
- deleteVideoComment,
+ CommentsCommand,
+ createMultipleServers,
doubleFollow,
- findCommentId,
- flushAndRunMultipleServers,
- follow,
- getAccountBlocklistByAccount,
- getAccountBlocklistByServer,
- getServerBlocklistByAccount,
- getServerBlocklistByServer,
- getUserNotifications,
- getVideoCommentThreads,
- getVideosList,
- getVideosListWithToken,
- getVideoThreadComments,
- removeAccountFromAccountBlocklist,
- removeAccountFromServerBlocklist,
- removeServerFromAccountBlocklist,
- removeServerFromServerBlocklist,
- ServerInfo,
+ PeerTubeServer,
setAccessTokensToServers,
- unfollow,
- uploadVideo,
- userLogin,
waitJobs
} from '@shared/extra-utils'
-import {
- AccountBlock,
- ServerBlock,
- UserNotification,
- UserNotificationType,
- Video,
- VideoComment,
- VideoCommentThreadTree
-} from '@shared/models'
+import { UserNotificationType } from '@shared/models'
const expect = chai.expect
-async function checkAllVideos (url: string, token: string) {
+async function checkAllVideos (server: PeerTubeServer, token: string) {
{
- const res = await getVideosListWithToken(url, token)
-
- expect(res.body.data).to.have.lengthOf(5)
+ const { data } = await server.videos.listWithToken({ token })
+ expect(data).to.have.lengthOf(5)
}
{
- const res = await getVideosList(url)
-
- expect(res.body.data).to.have.lengthOf(5)
+ const { data } = await server.videos.list()
+ expect(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: PeerTubeServer, token: string, videoUUID: string) {
+ const { data } = await server.comments.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.comments.getThread({ videoId: videoUUID, threadId: thread.id, token })
expect(tree.children).to.have.lengthOf(1)
}
}
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 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.comments
+
+ const { threadId, createdAt } = await command.createThread({ token: comment.token, videoId: comment.videoUUID, text: comment.text })
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.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)
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 ])
}
describe('Test blocklist', function () {
- let servers: ServerInfo[]
+ let servers: PeerTubeServer[]
let videoUUID1: string
let videoUUID2: string
let videoUUID3: string
@@ -110,62 +71,73 @@ describe('Test blocklist', function () {
let userModeratorToken: string
let userToken2: string
+ let command: BlocklistCommand
+ let commentsCommand: CommentsCommand[]
+
before(async function () {
this.timeout(120000)
- servers = await flushAndRunMultipleServers(3)
+ servers = await createMultipleServers(3)
await setAccessTokensToServers(servers)
+ command = servers[0].blocklist
+ commentsCommand = servers.map(s => s.comments)
+
{
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].users.create({ username: user.username, password: user.password })
- userToken1 = await userLogin(servers[0], user)
- await uploadVideo(servers[0].url, userToken1, { 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 createUser({ url: servers[0].url, accessToken: servers[0].accessToken, username: user.username, password: user.password })
+ await servers[0].users.create({ username: user.username, password: user.password })
- userModeratorToken = await userLogin(servers[0], user)
+ userModeratorToken = await servers[0].login.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].users.create({ username: user.username, password: user.password })
- userToken2 = await userLogin(servers[1], user)
- await uploadVideo(servers[1].url, userToken2, { name: 'video user 2' })
+ userToken2 = await servers[1].login.getAccessToken(user)
+ await servers[1].videos.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].videos.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].videos.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].videos.upload({ attributes: { name: 'video 2 server 1' } })
+ videoUUID3 = uuid
}
await doubleFollow(servers[0], servers[1])
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)
@@ -175,55 +147,60 @@ describe('Test 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 () {
- 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 () {
- const res = await getVideosListWithToken(servers[0].url, servers[0].accessToken)
+ const { data } = await servers[0].videos.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
})
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 () {
- const res = await getVideosListWithToken(servers[0].url, servers[0].accessToken)
+ const { data } = await servers[0].videos.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
})
it('Should hide its comments', async function () {
- const resThreads = await getVideoCommentThreads(servers[0].url, videoUUID1, 0, 25, '-createdAt', servers[0].accessToken)
+ const { data } = await commentsCommand[0].listThreads({
+ token: servers[0].accessToken,
+ videoId: videoUUID1,
+ start: 0,
+ count: 25,
+ sort: '-createdAt'
+ })
- const threads: VideoComment[] = resThreads.body.data
- expect(threads).to.have.lengthOf(1)
- expect(threads[0].totalReplies).to.equal(1)
+ expect(data).to.have.lengthOf(1)
+ expect(data[0].totalReplies).to.equal(1)
- const t = threads.find(t => t.text === 'comment user 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)
}
})
@@ -248,17 +225,15 @@ 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 () {
{
- 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')
@@ -267,12 +242,10 @@ describe('Test blocklist', function () {
}
{
- const res = await getAccountBlocklistByAccount(servers[0].url, servers[0].accessToken, 1, 2, 'createdAt')
- const blocks: AccountBlock[] = res.body.data
+ const body = await command.listMyAccountBlocklist({ 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('root')
expect(block.byAccount.name).to.equal('root')
expect(block.blockedAccount.displayName).to.equal('user1')
@@ -285,32 +258,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
+ const { data } = await commentsCommand[1].listThreads({ videoId: videoUUID3, count: 25, sort: '-createdAt' })
- expect(threads).to.have.lengthOf(2)
- expect(threads[0].text).to.equal('uploader')
- expect(threads[1].text).to.equal('comment user 2')
+ expect(data).to.have.lengthOf(2)
+ expect(data[0].text).to.equal('uploader')
+ expect(data[1].text).to.equal('comment user 2')
- const resReplies = await getVideoThreadComments(servers[1].url, videoUUID3, threads[0].id)
-
- 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)
@@ -319,55 +289,45 @@ 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.comments.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.comments.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)
}
})
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 () {
- const res = await getVideosListWithToken(servers[0].url, servers[0].accessToken)
+ const { data } = await servers[0].videos.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
})
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.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) {
- 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')
+ expect(data).to.have.lengthOf(2)
+ expect(data[0].text).to.equal('uploader')
+ expect(data[1].text).to.equal('comment user 2')
- const resReplies = await getVideoThreadComments(server.url, videoUUID3, threads[0].id)
-
- const tree: VideoCommentThreadTree = resReplies.body
+ 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)
@@ -376,11 +336,11 @@ 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 () {
- 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 () {
@@ -404,46 +364,45 @@ 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 () {
- 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 () {
- const res = await getVideosListWithToken(servers[0].url, servers[0].accessToken)
+ const { data } = await servers[0].videos.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
})
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 () {
@@ -466,27 +425,25 @@ 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
+ const body = await command.listMyServerBlocklist({ start: 0, count: 1, sort: 'createdAt' })
+ expect(body.total).to.equal(1)
- expect(res.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 () {
- 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 () {
@@ -515,54 +472,50 @@ 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)
}
})
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 () {
for (const token of [ userModeratorToken, servers[0].accessToken ]) {
- const res = await getVideosListWithToken(servers[0].url, token)
+ const { data } = await servers[0].videos.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
}
})
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 () {
for (const token of [ userModeratorToken, servers[0].accessToken ]) {
- const res = await getVideosListWithToken(servers[0].url, token)
+ const { data } = await servers[0].videos.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
}
})
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)
@@ -571,9 +524,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)
}
}
@@ -600,12 +551,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
+ const body = await command.listServerAccountBlocklist({ 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('peertube')
expect(block.byAccount.name).to.equal('peertube')
expect(block.blockedAccount.displayName).to.equal('user2')
@@ -614,12 +563,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')
@@ -629,28 +576,26 @@ 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 () {
for (const token of [ userModeratorToken, servers[0].accessToken ]) {
- const res = await getVideosListWithToken(servers[0].url, token)
+ const { data } = await servers[0].videos.listWithToken({ token })
+ 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
}
})
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 () {
for (const token of [ userModeratorToken, servers[0].accessToken ]) {
- await checkAllComments(servers[0].url, token, videoUUID1)
+ await checkAllComments(servers[0], token, videoUUID1)
}
})
@@ -677,31 +622,33 @@ 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)
}
})
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 () {
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].videos.list(),
+ servers[0].videos.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
@@ -712,14 +659,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 () {
@@ -742,48 +688,44 @@ describe('Test blocklist', function () {
{
const now = new Date()
- await unfollow(servers[1].url, servers[1].accessToken, servers[0])
+ await servers[1].follows.unfollow({ target: servers[0] })
await waitJobs(servers)
- await follow(servers[1].url, [ servers[0].host ], servers[1].accessToken)
+ await servers[1].follows.follow({ hosts: [ servers[0].host ] })
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].notifications.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)
}
})
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
+ const body = await command.listServerServerBlocklist({ start: 0, count: 1, sort: 'createdAt' })
+ expect(body.total).to.equal(1)
- expect(res.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 () {
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)
}
})
@@ -807,18 +749,16 @@ describe('Test blocklist', function () {
{
const now = new Date()
- await unfollow(servers[1].url, servers[1].accessToken, servers[0])
+ await servers[1].follows.unfollow({ target: servers[0] })
await waitJobs(servers)
- await follow(servers[1].url, [ servers[0].host ], servers[1].accessToken)
+ await servers[1].follows.follow({ hosts: [ servers[0].host ] })
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].notifications.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/moderation/video-blacklist.ts b/server/tests/api/moderation/video-blacklist.ts
index 52cac20d9..d5838191a 100644
--- a/server/tests/api/moderation/video-blacklist.ts
+++ b/server/tests/api/moderation/video-blacklist.ts
@@ -4,44 +4,30 @@ import 'mocha'
import * as chai from 'chai'
import { orderBy } from 'lodash'
import {
- addVideoToBlacklist,
+ BlacklistCommand,
cleanupTests,
- createUser,
- flushAndRunMultipleServers,
- getBlacklistedVideosList,
- getMyUserInformation,
- getMyVideos,
- getVideosList,
+ createMultipleServers,
+ doubleFollow,
+ FIXTURE_URLS,
killallServers,
- removeVideoFromBlacklist,
- reRunServer,
- searchVideo,
- ServerInfo,
+ PeerTubeServer,
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'
+ waitJobs
+} from '@shared/extra-utils'
+import { UserAdminFlag, UserRole, VideoBlacklist, VideoBlacklistType } from '@shared/models'
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) {
- const res = await getVideosList(server.url)
+ async function blacklistVideosOnServer (server: PeerTubeServer) {
+ const { data } = await server.videos.list()
- const videos = res.body.data
- for (const video of videos) {
- await addVideoToBlacklist(server.url, server.accessToken, video.id, 'super reason')
+ for (const video of data) {
+ await server.blacklist.add({ videoId: video.id, reason: 'super reason' })
}
}
@@ -49,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)
@@ -58,12 +44,14 @@ 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].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].blacklist
+
// Blacklist the two videos on server 1
await blacklistVideosOnServer(servers[0])
})
@@ -72,48 +60,47 @@ 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].videos.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)
}
{
- const res = await searchVideo(servers[0].url, 'name')
+ const body = await servers[0].search.searchVideos({ search: 'video' })
- 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 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].videos.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)
}
{
- const res = await searchVideo(servers[1].url, 'video')
+ const body = await servers[1].search.searchVideos({ search: 'video' })
- 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)
}
})
})
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 })
+ const body = await command.list()
+ 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)
@@ -124,79 +111,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')
})
@@ -206,12 +180,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].videos.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')
}
@@ -223,39 +197,38 @@ 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].videos.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 () {
// 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 () {
- const res = await getVideosList(servers[0].url)
- expect(res.body.total).to.equal(1)
+ const { total, data } = await servers[0].videos.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 () {
- 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)
@@ -270,12 +243,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].videos.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].videos.upload({ attributes: { name: 'Video 4' } })
+ video4UUID = uuid
}
await waitJobs(servers)
@@ -284,51 +257,51 @@ 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)
{
- const res = await getVideosList(servers[0].url)
- expect(res.body.data.find(v => v.uuid === video3UUID)).to.be.undefined
+ const { data } = await servers[0].videos.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].videos.list()
+ expect(data.find(v => v.uuid === video3UUID)).to.not.be.undefined
}
})
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)
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.videos.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].videos.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.videos.list()
+ expect(data.find(v => v.uuid === video4UUID)).to.be.undefined
}
})
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)
@@ -339,13 +312,13 @@ 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)
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.videos.list()
+ expect(data.find(v => v.uuid === video4UUID)).to.not.be.undefined
}
})
@@ -359,7 +332,7 @@ describe('Test video blacklist', function () {
before(async function () {
this.timeout(20000)
- killallServers([ servers[0] ])
+ await killallServers([ servers[0] ])
const config = {
auto_blacklist: {
@@ -370,106 +343,79 @@ describe('Test video blacklist', function () {
}
}
}
- await reRunServer(servers[0], config)
+ await servers[0].run(config)
{
const user = { username: 'user_without_flag', password: 'password' }
- await createUser({
- url: servers[0].url,
- accessToken: servers[0].accessToken,
+ await servers[0].users.create({
username: user.username,
adminFlags: UserAdminFlag.NONE,
password: user.password,
role: UserRole.USER
})
- userWithoutFlag = await userLogin(servers[0], user)
+ userWithoutFlag = await servers[0].login.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].users.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].users.create({
username: user.username,
adminFlags: UserAdminFlag.BYPASS_VIDEO_AUTO_BLACKLIST,
password: user.password,
role: UserRole.USER
})
- userWithFlag = await userLogin(servers[0], user)
+ userWithFlag = await servers[0].login.getAccessToken(user)
}
await waitJobs(servers)
})
it('Should auto blacklist a video on upload', async function () {
- await uploadVideo(servers[0].url, userWithoutFlag, { name: 'blacklisted' })
+ await servers[0].videos.upload({ token: userWithoutFlag, attributes: { 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 () {
this.timeout(15000)
const attributes = {
- targetUrl: getGoodVideoUrl(),
+ targetUrl: FIXTURE_URLS.goodVideo,
name: 'URL import',
channelId: channelOfUserWithoutFlag
}
- await importVideo(servers[0].url, userWithoutFlag, attributes)
+ await servers[0].imports.importVideo({ token: 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 () {
const attributes = {
- magnetUri: getMagnetURI(),
+ magnetUri: FIXTURE_URLS.magnet,
name: 'Torrent import',
channelId: channelOfUserWithoutFlag
}
- await importVideo(servers[0].url, userWithoutFlag, attributes)
+ await servers[0].imports.importVideo({ token: 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' })
+ await servers[0].videos.upload({ token: userWithFlag, attributes: { 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/admin-notifications.ts b/server/tests/api/notifications/admin-notifications.ts
index cfe0bd2bb..b36ba11a9 100644
--- a/server/tests/api/notifications/admin-notifications.ts
+++ b/server/tests/api/notifications/admin-notifications.ts
@@ -2,21 +2,21 @@
import 'mocha'
import { expect } from 'chai'
-import { MockJoinPeerTubeVersions } from '@shared/extra-utils/mock-servers/joinpeertube-versions'
-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 {
CheckerBaseParams,
checkNewPeerTubeVersion,
checkNewPluginVersion,
- prepareNotificationsTest
-} from '../../../../shared/extra-utils/users/user-notifications'
-import { UserNotification, UserNotificationType } from '../../../../shared/models/users'
+ cleanupTests,
+ MockJoinPeerTubeVersions,
+ MockSmtpServer,
+ PeerTubeServer,
+ prepareNotificationsTest,
+ 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[] = []
@@ -58,17 +58,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.plugins.install({ npmName: 'peertube-plugin-hello-world' })
+ await server.plugins.install({ npmName: 'peertube-theme-background-red' })
})
describe('Latest PeerTube version notification', function () {
@@ -127,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.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')
@@ -149,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.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 d2badf237..cbb46e510 100644
--- a/server/tests/api/notifications/comments-notifications.ts
+++ b/server/tests/api/notifications/comments-notifications.ts
@@ -3,30 +3,22 @@
import 'mocha'
import * as chai from 'chai'
import {
- addAccountToAccountBlocklist,
- addVideoCommentReply,
- addVideoCommentThread,
checkCommentMention,
CheckerBaseParams,
checkNewCommentOnMyVideo,
cleanupTests,
- getVideoCommentThreads,
- getVideoThreadComments,
MockSmtpServer,
+ PeerTubeServer,
prepareNotificationsTest,
- removeAccountFromAccountBlocklist,
- ServerInfo,
- updateMyUser,
- 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 servers: PeerTubeServer[] = []
+ let userToken: string
let userNotifications: UserNotification[] = []
let emails: object[] = []
@@ -40,7 +32,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
})
@@ -53,18 +45,17 @@ describe('Test comments notifications', function () {
server: servers[0],
emails,
socketNotifications: userNotifications,
- token: userAccessToken
+ token: userToken
}
})
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].videos.upload({ attributes: { name: 'super video' } })
- const resComment = await addVideoCommentThread(servers[0].url, servers[0].accessToken, uuid, 'comment')
- const commentId = resComment.body.comment.id
+ 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')
@@ -73,11 +64,10 @@ 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 uuid = resVideo.body.video.uuid
+ const { uuid } = await servers[0].videos.upload({ token: userToken, attributes: { name: 'super video' } })
- const resComment = await addVideoCommentThread(servers[0].url, userAccessToken, uuid, 'comment')
- const commentId = resComment.body.comment.id
+ const created = await servers[0].comments.createThread({ token: userToken, videoId: uuid, text: 'comment' })
+ const commentId = created.id
await waitJobs(servers)
await checkNewCommentOnMyVideo(baseParams, uuid, commentId, commentId, 'absence')
@@ -86,28 +76,26 @@ 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].blocklist.addToMyBlocklist({ token: userToken, account: 'root' })
- const resVideo = await uploadVideo(servers[0].url, userAccessToken, { name: 'super video' })
- const uuid = resVideo.body.video.uuid
+ const { uuid } = await servers[0].videos.upload({ token: userToken, attributes: { name: 'super video' } })
- const resComment = await addVideoCommentThread(servers[0].url, servers[0].accessToken, uuid, 'comment')
- const commentId = resComment.body.comment.id
+ 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 removeAccountFromAccountBlocklist(servers[0].url, userAccessToken, '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 resVideo = await uploadVideo(servers[0].url, userAccessToken, { name: 'super video' })
- const uuid = resVideo.body.video.uuid
+ const { uuid } = await servers[0].videos.upload({ token: userToken, attributes: { name: 'super video' } })
- const resComment = await addVideoCommentThread(servers[0].url, servers[0].accessToken, uuid, 'comment')
- const commentId = resComment.body.comment.id
+ const created = await servers[0].comments.createThread({ videoId: uuid, text: 'comment' })
+ const commentId = created.id
await waitJobs(servers)
await checkNewCommentOnMyVideo(baseParams, uuid, commentId, commentId, 'presence')
@@ -116,33 +104,29 @@ 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 uuid = resVideo.body.video.uuid
+ const { uuid } = await servers[0].videos.upload({ token: userToken, attributes: { name: 'super video' } })
await waitJobs(servers)
- await addVideoCommentThread(servers[1].url, servers[1].accessToken, uuid, 'comment')
+ await servers[1].comments.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].comments.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 uuid = resVideo.body.video.uuid
+ const { uuid } = await servers[0].videos.upload({ token: userToken, attributes: { name: 'super video' } })
- const resThread = await addVideoCommentThread(servers[0].url, servers[0].accessToken, uuid, 'comment')
- const threadId = resThread.body.comment.id
+ const { id: threadId } = await servers[0].comments.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].comments.addReply({ videoId: uuid, toCommentId: threadId, text: 'reply' })
await waitJobs(servers)
await checkNewCommentOnMyVideo(baseParams, uuid, commentId, threadId, 'presence')
@@ -151,24 +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 resVideo = await uploadVideo(servers[0].url, userAccessToken, { name: 'super video' })
- const uuid = resVideo.body.video.uuid
+ const { uuid } = await servers[0].videos.upload({ token: userToken, attributes: { name: 'super video' } })
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].comments.createThread({ videoId: uuid, text: 'comment' })
+ const threadId = created.id
+ await servers[1].comments.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].comments.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].comments.getThread({ videoId: uuid, threadId })
expect(tree.children).to.have.lengthOf(1)
const commentId = tree.children[0].comment.id
@@ -179,10 +161,9 @@ 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 uuid = resVideo.body.video.uuid
+ const { uuid } = await servers[0].videos.upload({ token: userToken, attributes: { name: 'cool video' } })
- await addVideoCommentThread(servers[0].url, servers[0].accessToken, uuid, commentText)
+ await servers[0].comments.createThread({ videoId: uuid, text: commentText })
await waitJobs(servers)
@@ -199,30 +180,19 @@ describe('Test comments notifications', function () {
server: servers[0],
emails,
socketNotifications: userNotifications,
- token: userAccessToken
+ 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].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 resVideo = await uploadVideo(servers[0].url, userAccessToken, { name: 'super video' })
- const uuid = resVideo.body.video.uuid
+ const { uuid } = await servers[0].videos.upload({ token: userToken, attributes: { name: 'super video' } })
- 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].comments.createThread({ videoId: uuid, text: '@user_1 hello' })
await waitJobs(servers)
await checkCommentMention(baseParams, uuid, commentId, commentId, 'super root name', 'absence')
@@ -231,11 +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 resVideo = await uploadVideo(servers[0].url, servers[0].accessToken, { name: 'super video' })
- const uuid = resVideo.body.video.uuid
+ const { uuid } = await servers[0].videos.upload({ attributes: { name: 'super video' } })
- const resComment = await addVideoCommentThread(servers[0].url, userAccessToken, uuid, '@user_1 hello')
- const commentId = resComment.body.comment.id
+ 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')
@@ -244,29 +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 addAccountToAccountBlocklist(servers[0].url, userAccessToken, 'root')
+ await servers[0].blocklist.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].videos.upload({ attributes: { name: 'super video' } })
- 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].comments.createThread({ videoId: uuid, text: '@user_1 hello' })
await waitJobs(servers)
await checkCommentMention(baseParams, uuid, commentId, commentId, 'super root name', 'absence')
- await removeAccountFromAccountBlocklist(servers[0].url, userAccessToken, '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 resVideo = await uploadVideo(servers[0].url, servers[0].accessToken, { name: 'super video' })
- const uuid = resVideo.body.video.uuid
+ const { uuid } = await servers[0].videos.upload({ attributes: { name: 'super video' } })
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].comments.createThread({ videoId: uuid, text: '@user_1 hello' })
await waitJobs(servers)
await checkCommentMention(baseParams, uuid, threadId, threadId, 'super root 2 name', 'absence')
@@ -275,17 +239,14 @@ 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].videos.upload({ attributes: { name: 'super video' } })
- 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].comments.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].comments.addReply({ videoId: uuid, toCommentId: threadId, text: 'hello 2 @user_1' })
await waitJobs(servers)
await checkCommentMention(baseParams, uuid, commentId, threadId, 'super root name', 'presence')
@@ -294,29 +255,27 @@ 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].videos.upload({ attributes: { name: 'super video' } })
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].comments.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].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 addVideoCommentReply(servers[1].url, servers[1].accessToken, uuid, server2ThreadId, text2)
+ await servers[1].comments.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].comments.getThread({ videoId: uuid, threadId: server1ThreadId })
expect(tree.children).to.have.lengthOf(1)
const commentId = tree.children[0].comment.id
@@ -327,13 +286,11 @@ 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].videos.upload({ attributes: { name: 'super video' } })
- 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].comments.createThread({ videoId: uuid, text: '@user_1 hello 1' })
- await addVideoCommentReply(servers[0].url, servers[0].accessToken, uuid, threadId, '@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 3425480ae..6f74709b3 100644
--- a/server/tests/api/notifications/moderation-notifications.ts
+++ b/server/tests/api/notifications/moderation-notifications.ts
@@ -2,33 +2,6 @@
import 'mocha'
import { buildUUID } from '@server/helpers/uuid'
-import { AbuseState } from '@shared/models'
-import {
- addAbuseMessage,
- addVideoCommentThread,
- addVideoToBlacklist,
- cleanupTests,
- createUser,
- follow,
- generateUserAccessToken,
- getAccount,
- getCustomConfig,
- getVideoCommentThreads,
- getVideoIdFromUUID,
- immutableAssign,
- MockInstancesIndex,
- registerUser,
- removeVideoFromBlacklist,
- reportAbuse,
- unfollow,
- updateAbuse,
- updateCustomConfig,
- updateCustomSubConfig,
- wait
-} from '../../../../shared/extra-utils'
-import { ServerInfo, uploadVideo } from '../../../../shared/extra-utils/index'
-import { MockSmtpServer } from '../../../../shared/extra-utils/miscs/email'
-import { waitJobs } from '../../../../shared/extra-utils/server/jobs'
import {
checkAbuseStateChange,
checkAutoInstanceFollowing,
@@ -43,15 +16,18 @@ import {
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'
+ cleanupTests,
+ MockInstancesIndex,
+ MockSmtpServer,
+ PeerTubeServer,
+ prepareNotificationsTest,
+ 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[] = []
@@ -86,10 +62,9 @@ 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].videos.upload({ token: userAccessToken, attributes: { name } })
- await reportAbuse({ url: servers[0].url, token: servers[0].accessToken, 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')
@@ -99,13 +74,12 @@ 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].videos.upload({ token: userAccessToken, attributes: { name } })
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' })
+ 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')
@@ -115,14 +89,16 @@ 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 resComment = await addVideoCommentThread(servers[0].url, userAccessToken, video.id, 'comment abuse ' + buildUUID())
- const comment = resComment.body.comment
+ 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()
+ })
await waitJobs(servers)
- await reportAbuse({ url: servers[0].url, token: servers[0].accessToken, 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')
@@ -132,15 +108,19 @@ 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
- await addVideoCommentThread(servers[0].url, userAccessToken, video.id, 'comment abuse ' + buildUUID())
+ const video = await servers[0].videos.upload({ token: userAccessToken, attributes: { name } })
+
+ await servers[0].comments.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
- await reportAbuse({ url: servers[1].url, token: servers[1].accessToken, commentId, reason: 'super reason' })
+ const { data } = await servers[1].comments.listThreads({ videoId: video.uuid })
+ const commentId = data[0].id
+ await servers[1].abuses.report({ commentId, reason: 'super reason' })
await waitJobs(servers)
await checkNewCommentAbuseForModerators(baseParams, video.uuid, name, 'presence')
@@ -150,10 +130,10 @@ 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].users.create({ username, password: 'donald' })
+ const accountId = account.id
- await reportAbuse({ url: servers[0].url, token: servers[0].accessToken, accountId, reason: 'super reason' })
+ await servers[0].abuses.report({ accountId, reason: 'super reason' })
await waitJobs(servers)
await checkNewAccountAbuseForModerators(baseParams, username, 'presence')
@@ -163,13 +143,13 @@ describe('Test moderation notifications', function () {
this.timeout(20000)
const username = 'user' + new Date().getTime()
- const tmpToken = await generateUserAccessToken(servers[0], username)
- await uploadVideo(servers[0].url, tmpToken, { 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 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' })
+ 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')
@@ -189,17 +169,16 @@ 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].videos.upload({ token: userAccessToken, attributes: { name } })
- 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].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 updateAbuse(servers[0].url, servers[0].accessToken, abuseId, { state: AbuseState.ACCEPTED })
+ await servers[0].abuses.update({ abuseId, body: { state: AbuseState.ACCEPTED } })
await waitJobs(servers)
await checkAbuseStateChange(baseParams, abuseId, AbuseState.ACCEPTED, 'presence')
@@ -208,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 updateAbuse(servers[0].url, servers[0].accessToken, abuseId, { state: AbuseState.REJECTED })
+ await servers[0].abuses.update({ abuseId, body: { state: AbuseState.REJECTED } })
await waitJobs(servers)
await checkAbuseStateChange(baseParams, abuseId, AbuseState.REJECTED, 'presence')
@@ -237,17 +216,16 @@ 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].videos.upload({ token: userAccessToken, attributes: { name } })
{
- 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].abuses.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].abuses.report({ token: userAccessToken, videoId: video.id, reason: 'super reason 2' })
+ abuseId2 = body.abuse.id
}
})
@@ -255,7 +233,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].abuses.addMessage({ abuseId, message })
await waitJobs(servers)
await checkNewAbuseMessage(baseParamsUser, abuseId, message, 'user_1@example.com', 'presence')
@@ -265,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 addAbuseMessage(servers[0].url, servers[0].accessToken, abuseId, message)
+ await servers[0].abuses.addMessage({ abuseId, message })
await waitJobs(servers)
await checkNewAbuseMessage(baseParamsAdmin, abuseId, message, 'admin' + servers[0].internalServerNumber + '@example.com', 'absence')
@@ -275,7 +253,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].abuses.addMessage({ token: userAccessToken, abuseId: abuseId2, message })
await waitJobs(servers)
await checkNewAbuseMessage(baseParamsAdmin, abuseId2, message, 'admin' + servers[0].internalServerNumber + '@example.com', 'presence')
@@ -285,7 +263,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].abuses.addMessage({ token: userAccessToken, abuseId: abuseId2, message })
await waitJobs(servers)
await checkNewAbuseMessage(baseParamsUser, abuseId2, message, 'user_1@example.com', 'absence')
@@ -308,10 +286,9 @@ 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].videos.upload({ token: userAccessToken, attributes: { name } })
- await addVideoToBlacklist(servers[0].url, servers[0].accessToken, uuid)
+ await servers[0].blacklist.add({ videoId: uuid })
await waitJobs(servers)
await checkNewBlacklistOnMyVideo(baseParams, uuid, name, 'blacklist')
@@ -321,13 +298,12 @@ 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].videos.upload({ token: userAccessToken, attributes: { name } })
- await addVideoToBlacklist(servers[0].url, servers[0].accessToken, uuid)
+ await servers[0].blacklist.add({ videoId: uuid })
await waitJobs(servers)
- await removeVideoFromBlacklist(servers[0].url, servers[0].accessToken, uuid)
+ await servers[0].blacklist.remove({ videoId: uuid })
await waitJobs(servers)
await wait(500)
@@ -350,14 +326,14 @@ 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].users.register({ username: 'user_45' })
await waitJobs(servers)
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')
})
})
@@ -392,20 +368,20 @@ 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].follows.follow({ hosts: [ servers[0].url ] })
await waitJobs(servers)
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 () {
this.timeout(40000)
- await unfollow(servers[2].url, servers[2].accessToken, servers[0])
+ await servers[2].follows.unfollow({ target: servers[0] })
await waitJobs(servers)
const config = {
@@ -415,9 +391,9 @@ describe('Test moderation notifications', function () {
}
}
}
- await updateCustomSubConfig(servers[0].url, servers[0].accessToken, config)
+ await servers[0].config.updateCustomSubConfig({ newConfig: config })
- await follow(servers[2].url, [ servers[0].url ], servers[2].accessToken)
+ await servers[2].follows.follow({ hosts: [ servers[0].url ] })
await waitJobs(servers)
@@ -426,19 +402,19 @@ 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 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].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 unfollow(servers[0].url, servers[0].accessToken, servers[1])
+ await servers[0].follows.unfollow({ target: servers[1] })
- await updateCustomSubConfig(servers[0].url, servers[0].accessToken, config)
+ await servers[0].config.updateCustomSubConfig({ newConfig: config })
await wait(5000)
await waitJobs(servers)
@@ -448,8 +424,8 @@ 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 unfollow(servers[0].url, servers[0].accessToken, servers[1])
+ await servers[0].config.updateCustomSubConfig({ newConfig: config })
+ await servers[0].follows.unfollow({ target: servers[1] })
})
})
@@ -484,9 +460,11 @@ describe('Test moderation notifications', function () {
token: userAccessToken
}
- const resCustomConfig = await getCustomConfig(servers[0].url, servers[0].accessToken)
- currentCustomConfig = resCustomConfig.body
- const autoBlacklistTestsCustomConfig = immutableAssign(currentCustomConfig, {
+ currentCustomConfig = await servers[0].config.getCustomConfig()
+
+ const autoBlacklistTestsCustomConfig = {
+ ...currentCustomConfig,
+
autoBlacklist: {
videos: {
ofUsers: {
@@ -494,13 +472,14 @@ 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].config.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].subscriptions.add({ targetUri: 'user_1_channel@localhost:' + servers[0].port })
+ await servers[1].subscriptions.add({ targetUri: 'user_1_channel@localhost:' + servers[0].port })
})
@@ -508,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].videos.upload({ token: userAccessToken, attributes: { name: videoName } })
+ videoUUID = uuid
await waitJobs(servers)
await checkVideoAutoBlacklistForModerators(adminBaseParamsServer1, videoUUID, videoName, 'presence')
@@ -530,7 +509,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].blacklist.remove({ videoId: videoUUID })
await waitJobs(servers)
@@ -555,19 +534,18 @@ 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].videos.upload({ token: userAccessToken, attributes })
- await removeVideoFromBlacklist(servers[0].url, servers[0].accessToken, uuid)
+ await servers[0].blacklist.remove({ videoId: uuid })
await waitJobs(servers)
await checkNewBlacklistOnMyVideo(userBaseParams, uuid, name, 'unblacklist')
@@ -588,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].videos.upload({ token: userAccessToken, attributes })
await wait(6000)
await checkVideoIsPublished(userBaseParams, name, uuid, 'absence')
@@ -612,18 +589,17 @@ 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].videos.upload({ attributes: { name } })
await waitJobs(servers)
await checkVideoAutoBlacklistForModerators(adminBaseParamsServer1, uuid, name, 'absence')
})
after(async () => {
- await updateCustomConfig(servers[0].url, servers[0].accessToken, currentCustomConfig)
+ await servers[0].config.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].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 b81995449..fa4b53db6 100644
--- a/server/tests/api/notifications/notifications-api.ts
+++ b/server/tests/api/notifications/notifications-api.ts
@@ -2,28 +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/miscs/email'
import {
CheckerBaseParams,
checkNewVideoFromSubscription,
+ cleanupTests,
getAllNotificationsSettings,
- getUserNotifications,
- markAsReadAllNotifications,
- markAsReadNotifications,
+ MockSmtpServer,
+ PeerTubeServer,
prepareNotificationsTest,
- updateMyNotificationSettings
-} from '../../../../shared/extra-utils/users/user-notifications'
-import { User, UserNotification, UserNotificationSettingValue } from '../../../../shared/models/users'
+ waitJobs
+} from '@shared/extra-utils'
+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 userAccessToken: string
+ let userToken: string
let emails: object[] = []
before(async function () {
@@ -31,14 +27,14 @@ 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 addUserSubscription(server.url, userAccessToken, '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 uploadRandomVideo(server, false)
+ await server.videos.randomUpload({ wait: false })
}
await waitJobs([ server ])
@@ -47,49 +43,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.notifications.list({ token: userToken, start: 2, count: 3 })
+ const ids = data.map(n => n.id)
- await markAsReadNotifications(server.url, userAccessToken, ids)
+ await server.notifications.markAsRead({ token: userToken, ids })
})
it('Should have the notifications marked as read', async function () {
- const res = await getUserNotifications(server.url, userAccessToken, 0, 10)
+ const { data } = await server.notifications.list({ token: userToken, start: 0, count: 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
+ 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.notifications.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.notifications.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.notifications.markAsReadAll({ token: userToken })
- const res = await getUserNotifications(server.url, userAccessToken, 0, 10, true)
+ const body = await server.notifications.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)
})
})
@@ -101,97 +94,100 @@ 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.notifications.updateMySettings({
+ token: userToken,
+ settings: { ...getAllNotificationsSettings(), newVideoFromSubscription: UserNotificationSettingValue.NONE }
+ })
{
- const res = await getMyUserInformation(server.url, userAccessToken)
- const info = res.body as User
+ const info = await server.users.getMyInfo({ token: userToken })
expect(info.notificationSettings.newVideoFromSubscription).to.equal(UserNotificationSettingValue.NONE)
}
- const { name, uuid } = await uploadRandomVideo(server)
+ const { name, uuid } = await server.videos.randomUpload()
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 () {
this.timeout(20000)
- await updateMyNotificationSettings(server.url, userAccessToken, immutableAssign(getAllNotificationsSettings(), {
- newVideoFromSubscription: UserNotificationSettingValue.WEB
- }))
+ await server.notifications.updateMySettings({
+ token: userToken,
+ settings: { ...getAllNotificationsSettings(), newVideoFromSubscription: UserNotificationSettingValue.WEB }
+ })
{
- const res = await getMyUserInformation(server.url, userAccessToken)
- const info = res.body as User
+ const info = await server.users.getMyInfo({ token: userToken })
expect(info.notificationSettings.newVideoFromSubscription).to.equal(UserNotificationSettingValue.WEB)
}
- const { name, uuid } = await uploadRandomVideo(server)
+ const { name, uuid } = await server.videos.randomUpload()
{
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')
}
})
it('Should only have mail notifications', async function () {
this.timeout(20000)
- await updateMyNotificationSettings(server.url, userAccessToken, immutableAssign(getAllNotificationsSettings(), {
- newVideoFromSubscription: UserNotificationSettingValue.EMAIL
- }))
+ await server.notifications.updateMySettings({
+ token: userToken,
+ settings: { ...getAllNotificationsSettings(), newVideoFromSubscription: UserNotificationSettingValue.EMAIL }
+ })
{
- const res = await getMyUserInformation(server.url, userAccessToken)
- const info = res.body as User
+ const info = await server.users.getMyInfo({ token: userToken })
expect(info.notificationSettings.newVideoFromSubscription).to.equal(UserNotificationSettingValue.EMAIL)
}
- const { name, uuid } = await uploadRandomVideo(server)
+ const { name, uuid } = await server.videos.randomUpload()
{
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')
}
})
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.notifications.updateMySettings({
+ token: userToken,
+ settings: {
+ ...getAllNotificationsSettings(),
+ newVideoFromSubscription: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL
+ }
+ })
{
- const res = await getMyUserInformation(server.url, userAccessToken)
- const info = res.body as User
+ const info = await server.users.getMyInfo({ token: userToken })
expect(info.notificationSettings.newVideoFromSubscription).to.equal(
UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL
)
}
- const { name, uuid } = await uploadRandomVideo(server)
+ 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 e981c1718..ca592d466 100644
--- a/server/tests/api/notifications/user-notifications.ts
+++ b/server/tests/api/notifications/user-notifications.ts
@@ -3,35 +3,27 @@
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/miscs/email'
-import { waitJobs } from '../../../../shared/extra-utils/server/jobs'
import {
CheckerBaseParams,
checkMyVideoImportIsFinished,
checkNewActorFollow,
checkNewVideoFromSubscription,
checkVideoIsPublished,
- 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'
+ cleanupTests,
+ FIXTURE_URLS,
+ MockSmtpServer,
+ PeerTubeServer,
+ prepareNotificationsTest,
+ uploadRandomVideoOnServers,
+ wait,
+ waitJobs
+} from '@shared/extra-utils'
+import { UserNotification, UserNotificationType, VideoPrivacy } from '@shared/models'
const expect = chai.expect
describe('Test user notifications', function () {
- let servers: ServerInfo[] = []
+ let servers: PeerTubeServer[] = []
let userAccessToken: string
let userNotifications: UserNotification[] = []
let adminNotifications: UserNotification[] = []
@@ -69,7 +61,7 @@ describe('Test user notifications', function () {
await uploadRandomVideoOnServers(servers, 1)
- const notification = await getLastNotification(servers[0].url, userAccessToken)
+ const notification = await servers[0].notifications.getLastest({ token: userAccessToken })
expect(notification).to.be.undefined
expect(emails).to.have.lengthOf(0)
@@ -79,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 addUserSubscription(servers[0].url, userAccessToken, '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)
@@ -89,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 addUserSubscription(servers[0].url, userAccessToken, '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)
@@ -106,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)
@@ -125,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)
@@ -144,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)
@@ -161,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].videos.update({ id: uuid, attributes: { privacy: VideoPrivacy.PUBLIC } })
await waitJobs(servers)
await checkNewVideoFromSubscription(baseParams, name, uuid, 'presence')
@@ -175,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].videos.update({ id: uuid, attributes: { privacy: VideoPrivacy.PUBLIC } })
await waitJobs(servers)
await checkNewVideoFromSubscription(baseParams, name, uuid, 'presence')
@@ -187,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].videos.update({ id: uuid, attributes: { privacy: VideoPrivacy.UNLISTED } })
await checkNewVideoFromSubscription(baseParams, name, uuid, 'absence')
})
@@ -198,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].videos.update({ id: uuid, attributes: { privacy: VideoPrivacy.UNLISTED } })
await waitJobs(servers)
await checkNewVideoFromSubscription(baseParams, name, uuid, 'absence')
@@ -213,14 +205,13 @@ describe('Test user notifications', function () {
name,
channelId,
privacy: VideoPrivacy.PUBLIC,
- targetUrl: getGoodVideoUrl()
+ targetUrl: FIXTURE_URLS.goodVideo
}
- const res = await importVideo(servers[0].url, servers[0].accessToken, attributes)
- const uuid = res.body.video.uuid
+ const { video } = await servers[0].imports.importVideo({ attributes })
await waitJobs(servers)
- await checkNewVideoFromSubscription(baseParams, name, uuid, 'presence')
+ await checkNewVideoFromSubscription(baseParams, name, video.uuid, 'presence')
})
})
@@ -251,7 +242,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].notifications.getLastest({ token: userAccessToken })
if (notification) {
expect(notification.type).to.not.equal(UserNotificationType.MY_VIDEO_PUBLISHED)
}
@@ -284,14 +275,13 @@ describe('Test user notifications', function () {
name,
channelId,
privacy: VideoPrivacy.PUBLIC,
- targetUrl: getGoodVideoUrl(),
+ targetUrl: FIXTURE_URLS.goodVideo,
waitTranscoding: true
}
- const res = await importVideo(servers[1].url, servers[1].accessToken, attributes)
- const uuid = res.body.video.uuid
+ const { video } = await servers[1].imports.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 () {
@@ -304,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)
@@ -322,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)
@@ -353,13 +343,12 @@ describe('Test user notifications', function () {
name,
channelId,
privacy: VideoPrivacy.PRIVATE,
- targetUrl: getBadVideoUrl()
+ targetUrl: FIXTURE_URLS.badVideo
}
- const res = await importVideo(servers[0].url, servers[0].accessToken, attributes)
- const uuid = res.body.video.uuid
+ const { video } = await servers[0].imports.importVideo({ attributes })
await waitJobs(servers)
- await checkMyVideoImportIsFinished(baseParams, name, uuid, 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 () {
@@ -371,13 +360,12 @@ describe('Test user notifications', function () {
name,
channelId,
privacy: VideoPrivacy.PRIVATE,
- targetUrl: getGoodVideoUrl()
+ targetUrl: FIXTURE_URLS.goodVideo
}
- const res = await importVideo(servers[0].url, servers[0].accessToken, attributes)
- const uuid = res.body.video.uuid
+ const { video } = await servers[0].imports.importVideo({ attributes })
await waitJobs(servers)
- await checkMyVideoImportIsFinished(baseParams, name, uuid, getGoodVideoUrl(), true, 'presence')
+ await checkMyVideoImportIsFinished(baseParams, name, video.uuid, FIXTURE_URLS.goodVideo, true, 'presence')
})
})
@@ -394,47 +382,42 @@ describe('Test user notifications', function () {
token: userAccessToken
}
- await updateMyUser({
- url: servers[0].url,
- accessToken: servers[0].accessToken,
- displayName: 'super root name'
- })
+ await servers[0].users.updateMe({ displayName: 'super root name' })
- await updateMyUser({
- url: servers[0].url,
- accessToken: userAccessToken,
+ await servers[0].users.updateMe({
+ token: userAccessToken,
displayName: myUserName
})
- await updateMyUser({
- url: servers[1].url,
- accessToken: servers[1].accessToken,
- displayName: 'super root 2 name'
- })
+ await servers[1].users.updateMe({ displayName: 'super root 2 name' })
- await updateVideoChannel(servers[0].url, userAccessToken, 'user_1_channel', { displayName: myChannelName })
+ await servers[0].channels.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 () {
this.timeout(50000)
- await addUserSubscription(servers[0].url, servers[0].accessToken, '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 removeUserSubscription(servers[0].url, servers[0].accessToken, '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 addUserSubscription(servers[1].url, servers[1].accessToken, '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 removeUserSubscription(servers[1].url, servers[1].accessToken, '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 4253124c8..5fd464ded 100644
--- a/server/tests/api/redundancy/manage-redundancy.ts
+++ b/server/tests/api/redundancy/manage-redundancy.ts
@@ -1,32 +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 {
cleanupTests,
+ createMultipleServers,
doubleFollow,
- flushAndRunMultipleServers,
- getLocalIdByUUID,
- ServerInfo,
+ PeerTubeServer,
+ RedundancyCommand,
setAccessTokensToServers,
- uploadVideo,
- uploadVideoAndGetId,
- 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'
+ waitJobs
+} from '@shared/extra-utils'
+import { VideoPrivacy, VideoRedundanciesTarget } from '@shared/models'
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[] = []
+ let commands: RedundancyCommand[]
+
before(async function () {
this.timeout(120000)
@@ -50,40 +48,38 @@ describe('Test manage videos redundancy', function () {
}
}
}
- servers = await flushAndRunMultipleServers(3, config)
+ servers = await createMultipleServers(3, config)
// Get the access tokens
await setAccessTokensToServers(servers)
+ commands = servers.map(s => s.redundancy)
+
{
- 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].videos.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].videos.upload({ attributes: { name: 'video 2 server 2' } })
+ video2Server2UUID = uuid
}
await waitJobs(servers)
// 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)
}
})
@@ -91,31 +87,22 @@ describe('Test manage videos redundancy', function () {
this.timeout(120000)
await waitJobs(servers)
- await waitUntilLog(servers[0], 'Duplicated ', 10)
+ await servers[0].servers.waitUntilLog('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'
- })
+ const body = await commands[1].listVideos({ target: 'my-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)
@@ -139,28 +126,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,81 +163,67 @@ 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')
}
})
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].videos.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].videos.getId({ 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 servers[0].servers.waitUntilLog('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 +240,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 +267,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
+ const videos = body.data
+
expect(videos).to.have.lengthOf(2)
- expect(videos[0].name).to.equal('video 2 server 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
- })
- }
-
- const res = await listVideoRedundancies({
- url: servers[0].url,
- accessToken: servers[0].accessToken,
- 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)
+ for (const redundancyId of redundanciesToRemove) {
+ await commands[0].removeVideo({ redundancyId })
}
+
+ const body = await commands[0].listVideos({
+ target: 'remote-videos',
+ sort: '-name',
+ start: 0,
+ count: 5
+ })
+
+ 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 1cb1603bc..933a2c776 100644
--- a/server/tests/api/redundancy/redundancy-constraints.ts
+++ b/server/tests/api/redundancy/redundancy-constraints.ts
@@ -1,29 +1,14 @@
/* 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 { expect } from 'chai'
+import { cleanupTests, createSingleServer, killallServers, PeerTubeServer, setAccessTokensToServers, waitJobs } from '@shared/extra-utils'
import { VideoPrivacy } from '@shared/models'
-import {
- cleanupTests,
- flushAndRunServer,
- follow,
- killallServers,
- reRunServer,
- ServerInfo,
- setAccessTokensToServers,
- updateVideo,
- uploadVideo,
- waitUntilLog
-} from '../../../../shared/extra-utils'
-import { waitJobs } from '../../../../shared/extra-utils/server/jobs'
-
-const expect = chai.expect
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: {
@@ -43,38 +28,30 @@ 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.videos.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.videos.update({ id, attributes: { name: videoName, privacy: VideoPrivacy.PUBLIC } })
}
async function getTotalRedundanciesLocalServer () {
- const res = await listVideoRedundancies({
- url: localServer.url,
- accessToken: localServer.accessToken,
- target: 'my-videos'
- })
+ const body = await localServer.redundancy.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.redundancy.listVideos({ target: 'remote-videos' })
- return res.body.total
+ return body.total
}
before(async function () {
this.timeout(120000)
{
- remoteServer = await flushAndRunServer(1, remoteServerConfig)
+ remoteServer = await createSingleServer(1, remoteServerConfig)
}
{
@@ -85,7 +62,7 @@ describe('Test redundancy constraints', function () {
}
}
}
- localServer = await flushAndRunServer(2, config)
+ localServer = await createSingleServer(2, config)
}
servers = [ remoteServer, localServer ]
@@ -93,14 +70,14 @@ 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.videos.upload({ attributes: { name: 'video 1 server 2' } })
await waitJobs(servers)
// Server 1 and server 2 follow each other
- await follow(remoteServer.url, [ localServer.url ], remoteServer.accessToken)
+ await remoteServer.follows.follow({ hosts: [ localServer.url ] })
await waitJobs(servers)
- await updateRedundancy(remoteServer.url, remoteServer.accessToken, localServer.host, true)
+ await remoteServer.redundancy.updateRedundancy({ host: localServer.host, redundancyAllowed: true })
await waitJobs(servers)
})
@@ -109,7 +86,7 @@ describe('Test redundancy constraints', function () {
this.timeout(120000)
await waitJobs(servers)
- await waitUntilLog(remoteServer, 'Duplicated ', 5)
+ await remoteServer.servers.waitUntilLog('Duplicated ', 5)
await waitJobs(servers)
{
@@ -134,11 +111,11 @@ describe('Test redundancy constraints', function () {
}
}
await killallServers([ localServer ])
- await reRunServer(localServer, config)
+ await localServer.run(config)
await uploadWrapper('video 2 server 2')
- await waitUntilLog(remoteServer, 'Duplicated ', 10)
+ await remoteServer.servers.waitUntilLog('Duplicated ', 10)
await waitJobs(servers)
{
@@ -163,11 +140,11 @@ describe('Test redundancy constraints', function () {
}
}
await killallServers([ localServer ])
- await reRunServer(localServer, config)
+ await localServer.run(config)
await uploadWrapper('video 3 server 2')
- await waitUntilLog(remoteServer, 'Duplicated ', 15)
+ await remoteServer.servers.waitUntilLog('Duplicated ', 15)
await waitJobs(servers)
{
@@ -184,11 +161,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 follow(localServer.url, [ remoteServer.url ], localServer.accessToken)
+ await localServer.follows.follow({ hosts: [ remoteServer.url ] })
await waitJobs(servers)
await uploadWrapper('video 4 server 2')
- await waitUntilLog(remoteServer, '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 0e0a73b9d..a6559d304 100644
--- a/server/tests/api/redundancy/redundancy.ts
+++ b/server/tests/api/redundancy/redundancy.ts
@@ -5,51 +5,29 @@ 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 {
checkSegmentHash,
checkVideoFilesWereRemoved,
cleanupTests,
+ createMultipleServers,
doubleFollow,
- flushAndRunMultipleServers,
- getFollowingListPaginationAndSort,
- getVideo,
- getVideoWithToken,
- immutableAssign,
killallServers,
makeGetRequest,
- removeVideo,
- reRunServer,
+ PeerTubeServer,
root,
- ServerInfo,
setAccessTokensToServers,
- unfollow,
- updateVideo,
- uploadVideo,
- viewVideo,
wait,
- 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 { 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'
+ waitJobs
+} from '@shared/extra-utils'
+import { HttpStatusCode, VideoPrivacy, VideoRedundancyStrategy, VideoRedundancyStrategyWithManual } from '@shared/models'
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) {
@@ -60,16 +38,18 @@ 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) {
strategies.push(
- immutableAssign({
+ {
min_lifetime: '1 hour',
strategy: strategy,
- size: '400KB'
- }, additionalParams)
+ size: '400KB',
+
+ ...additionalParams
+ }
)
}
@@ -90,17 +70,17 @@ async function flushAndRunServers (strategy: VideoRedundancyStrategy | null, add
}
}
- servers = await flushAndRunMultipleServers(3, config)
+ servers = await createMultipleServers(3, config)
// Get the access tokens
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].videos.upload({ attributes: { name: 'video 1 server 2' } })
+ video1Server2UUID = uuid
+ video1Server2Id = id
- await viewVideo(servers[1].url, video1Server2UUID)
+ await servers[1].videos.view({ id: video1Server2UUID })
}
await waitJobs(servers)
@@ -124,9 +104,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.videos.getWithToken({ id: videoUUID })
- const video: VideoDetails = res.body
for (const f of video.files) {
checkMagnetWebseeds(f, webseeds, server)
}
@@ -142,22 +121,20 @@ 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.videos.get({ id: videoUUID })
for (const file of video.files) {
checkMagnetWebseeds(file, webseeds, server)
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
})
@@ -184,8 +161,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.videos.getWithToken({ id: videoUUID })
expect(video.streamingPlaylists).to.be.an('array')
expect(video.streamingPlaylists).to.have.lengthOf(1)
@@ -197,8 +173,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.videos.get({ id: videoUUID })
expect(video.streamingPlaylists).to.have.lengthOf(1)
expect(video.streamingPlaylists[0].redundancies).to.have.lengthOf(1)
@@ -211,11 +186,11 @@ 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].videos.get({ id: videoUUID })
+ const hlsPlaylist = video.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 = [
@@ -244,9 +219,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].stats.get()
expect(data.videosRedundancy).to.have.lengthOf(statsLength)
const stat = data.videosRedundancy[0]
@@ -272,14 +245,20 @@ async function checkStatsWithoutRedundancy (strategy: VideoRedundancyStrategyWit
expect(stat.totalVideos).to.equal(0)
}
-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
+async function findServerFollows () {
+ 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}`)
+ return { server2, server3 }
+}
+
+async function enableRedundancyOnServer1 () {
+ await servers[0].redundancy.updateRedundancy({ host: servers[1].host, redundancyAllowed: true })
+
+ const { server2, server3 } = await findServerFollows()
+
expect(server3).to.not.be.undefined
expect(server3.following.hostRedundancyAllowed).to.be.false
@@ -288,12 +267,9 @@ async function enableRedundancyOnServer1 () {
}
async function disableRedundancyOnServer1 () {
- await updateRedundancy(servers[0].url, servers[0].accessToken, servers[1].host, false)
+ await servers[0].redundancy.updateRedundancy({ host: servers[1].host, redundancyAllowed: 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
@@ -310,7 +286,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 () {
@@ -327,7 +303,7 @@ describe('Test videos redundancy', function () {
this.timeout(80000)
await waitJobs(servers)
- await waitUntilLog(servers[0], 'Duplicated ', 5)
+ await servers[0].servers.waitUntilLog('Duplicated ', 5)
await waitJobs(servers)
await check2Webseeds()
@@ -346,7 +322,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 () {
@@ -360,7 +336,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 () {
@@ -377,7 +353,7 @@ describe('Test videos redundancy', function () {
this.timeout(80000)
await waitJobs(servers)
- await waitUntilLog(servers[0], 'Duplicated ', 5)
+ await servers[0].servers.waitUntilLog('Duplicated ', 5)
await waitJobs(servers)
await check2Webseeds()
@@ -388,7 +364,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].follows.unfollow({ target: servers[1] })
await waitJobs(servers)
await wait(5000)
@@ -396,7 +372,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 () {
@@ -410,7 +386,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 () {
@@ -438,8 +414,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].videos.view({ id: video1Server2UUID })
+ await servers[2].videos.view({ id: video1Server2UUID })
await wait(10000)
await waitJobs(servers)
@@ -449,7 +425,7 @@ describe('Test videos redundancy', function () {
this.timeout(80000)
await waitJobs(servers)
- await waitUntilLog(servers[0], 'Duplicated ', 5)
+ await servers[0].servers.waitUntilLog('Duplicated ', 5)
await waitJobs(servers)
await check2Webseeds()
@@ -460,12 +436,12 @@ 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].videos.remove({ id: video1Server2UUID })
await waitJobs(servers)
for (const server of servers) {
- await checkVideoFilesWereRemoved(video1Server2UUID, server.internalServerNumber)
+ await checkVideoFilesWereRemoved(video1Server2UUID, server)
}
})
@@ -480,7 +456,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 () {
@@ -506,14 +482,14 @@ 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].videos.view({ id: video1Server2UUID })
+ await servers[2].videos.view({ id: video1Server2UUID })
await wait(10000)
await waitJobs(servers)
await waitJobs(servers)
- await waitUntilLog(servers[0], 'Duplicated ', 1)
+ await servers[0].servers.waitUntilLog('Duplicated ', 1)
await waitJobs(servers)
await check1PlaylistRedundancies()
@@ -523,12 +499,12 @@ 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].videos.remove({ id: video1Server2UUID })
await waitJobs(servers)
for (const server of servers) {
- await checkVideoFilesWereRemoved(video1Server2UUID, server.internalServerNumber)
+ await checkVideoFilesWereRemoved(video1Server2UUID, server)
}
})
@@ -541,7 +517,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 () {
@@ -551,18 +527,14 @@ 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].redundancy.addVideo({ videoId: video1Server2Id })
})
it('Should have 2 webseeds on the first video', async function () {
this.timeout(80000)
await waitJobs(servers)
- await waitUntilLog(servers[0], 'Duplicated ', 5)
+ await servers[0].servers.waitUntilLog('Duplicated ', 5)
await waitJobs(servers)
await check2Webseeds()
@@ -573,22 +545,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].redundancy.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].redundancy.removeVideo({ redundancyId: r.id })
}
await waitJobs(servers)
@@ -597,7 +562,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 () {
@@ -608,10 +573,9 @@ 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 res = await getVideo(server.url, video1Server2UUID)
- const video: VideoDetails = res.body
+ const video = await server.videos.get({ id: video1Server2UUID })
for (const f of video.files) {
expect(f.magnetUri).to.contain(str)
@@ -619,10 +583,9 @@ 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 res = await getVideo(server.url, video1Server2UUID)
- const video: VideoDetails = res.body
+ const video = await server.videos.get({ id: video1Server2UUID })
for (const f of video.files) {
expect(f.magnetUri).to.not.contain(str)
@@ -633,7 +596,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()
})
@@ -656,7 +619,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)
@@ -675,25 +638,25 @@ 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()
await waitJobs(servers)
- await waitUntilLog(servers[0], 'Duplicated ', 5)
+ await servers[0].servers.waitUntilLog('Duplicated ', 5)
await waitJobs(servers)
await check2Webseeds(video1Server2UUID)
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].videos.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].videos.update({ id: video2Server2UUID, attributes: { privacy: VideoPrivacy.PUBLIC } })
})
it('Should cache video 2 webseeds on the first video', async function () {
@@ -725,8 +688,8 @@ describe('Test videos redundancy', function () {
await waitJobs(servers)
- killallServers([ servers[0] ])
- await reRunServer(servers[0], {
+ await killallServers([ servers[0] ])
+ await servers[0].run({
redundancy: {
videos: {
check_interval: '1 second',
@@ -737,7 +700,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-activitypub-video-channels.ts b/server/tests/api/search/search-activitypub-video-channels.ts
index e83eb7171..426cbc8e1 100644
--- a/server/tests/api/search/search-activitypub-video-channels.ts
+++ b/server/tests/api/search/search-activitypub-video-channels.ts
@@ -1,69 +1,63 @@
/* 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,
- createUser,
- deleteVideoChannel,
- flushAndRunMultipleServers,
- getVideoChannelsList,
- getVideoChannelVideos,
- ServerInfo,
+ createMultipleServers,
+ PeerTubeServer,
+ SearchCommand,
setAccessTokensToServers,
- updateMyUser,
- updateVideo,
- 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
describe('Test ActivityPub video channels search', function () {
- let servers: ServerInfo[]
+ let servers: PeerTubeServer[]
let userServer2Token: string
let videoServer2UUID: string
let channelIdServer2: number
+ let command: SearchCommand
before(async function () {
this.timeout(120000)
- servers = await flushAndRunMultipleServers(2)
+ servers = await createMultipleServers(2)
await setAccessTokensToServers(servers)
{
- await createUser({ url: servers[0].url, accessToken: servers[0].accessToken, 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 addVideoChannel(servers[0].url, servers[0].accessToken, channel)
+ await servers[0].channels.create({ attributes: channel })
}
{
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)
+ 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 resChannel = await addVideoChannel(servers[1].url, userServer2Token, channel)
- channelIdServer2 = resChannel.body.videoChannel.id
+ const created = await servers[1].channels.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].videos.upload({ token: userServer2Token, attributes })
+ videoServer2UUID = uuid
}
await waitJobs(servers)
+
+ command = servers[0].search
})
it('Should not find a remote video channel', async function () {
@@ -71,21 +65,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 +90,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 +104,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,23 +123,23 @@ 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')
}
})
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].channels.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 () {
@@ -153,34 +147,43 @@ 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].videos.listByChannel({
+ token: null,
+ handle: '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].videos.listByChannel({
+ handle: '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 () {
this.timeout(60000)
- await updateVideoChannel(servers[1].url, userServer2Token, 'channel1_server2', { displayName: 'channel updated' })
- await updateMyUser({ url: servers[1].url, accessToken: userServer2Token, displayName: 'user updated' })
+ await servers[1].channels.update({
+ token: userServer2Token,
+ channelName: 'channel1_server2',
+ attributes: { displayName: 'channel updated' }
+ })
+ await servers[1].users.updateMe({ token: userServer2Token, displayName: 'user updated' })
await waitJobs(servers)
// Expire video channel
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
@@ -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].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)
@@ -199,31 +202,31 @@ 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)
- const videoChannelName = 'channel1_server2@localhost:' + servers[1].port
- const res = await getVideoChannelVideos(servers[0].url, servers[0].accessToken, videoChannelName, 0, 5, '-createdAt')
+ const handle = 'channel1_server2@localhost:' + servers[1].port
+ const { total, data } = await servers[0].videos.listByChannel({ handle, 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 () {
this.timeout(60000)
- await deleteVideoChannel(servers[1].url, userServer2Token, 'channel1_server2')
+ await servers[1].channels.delete({ token: userServer2Token, channelName: 'channel1_server2' })
await waitJobs(servers)
// Expire video
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..33ca7be12 100644
--- a/server/tests/api/search/search-activitypub-video-playlists.ts
+++ b/server/tests/api/search/search-activitypub-video-playlists.ts
@@ -3,113 +3,102 @@
import 'mocha'
import * as chai from 'chai'
import {
- addVideoInPlaylist,
cleanupTests,
- createVideoPlaylist,
- deleteVideoPlaylist,
- flushAndRunMultipleServers,
- getVideoPlaylistsList,
- searchVideoPlaylists,
- ServerInfo,
+ createMultipleServers,
+ PeerTubeServer,
+ SearchCommand,
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
describe('Test ActivityPub playlists search', function () {
- let servers: ServerInfo[]
+ let servers: PeerTubeServer[]
let playlistServer1UUID: string
let playlistServer2UUID: string
let video2Server2: string
+ let command: SearchCommand
+
before(async function () {
this.timeout(120000)
- servers = await flushAndRunMultipleServers(2)
+ servers = await createMultipleServers(2)
await setAccessTokensToServers(servers)
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].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 res = await createVideoPlaylist({ url: servers[0].url, token: servers[0].accessToken, playlistAttrs: attributes })
- playlistServer1UUID = res.body.videoPlaylist.uuid
+ const created = await servers[0].playlists.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].playlists.addElement({ playlistId: playlistServer1UUID, attributes: { videoId } })
}
}
{
- 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].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 res = await createVideoPlaylist({ url: servers[1].url, token: servers[1].accessToken, playlistAttrs: attributes })
- playlistServer2UUID = res.body.videoPlaylist.uuid
+ const created = await servers[1].playlists.create({ attributes })
+ playlistServer2UUID = created.uuid
- await addVideoInPlaylist({
- url: servers[1].url,
- token: servers[1].accessToken,
- playlistId: playlistServer2UUID,
- elementAttrs: { videoId }
- })
+ await servers[1].playlists.addElement({ playlistId: playlistServer2UUID, attributes: { videoId } })
}
await waitJobs(servers)
+
+ command = servers[0].search
})
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 +109,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,32 +128,27 @@ 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)
}
})
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].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')
})
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].playlists.addElement({ playlistId: playlistServer2UUID, attributes: { videoId: video2Server2 } })
await waitJobs(servers)
// Expire playlist
@@ -172,23 +156,23 @@ 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)
})
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].playlists.delete({ playlistId: playlistServer2UUID })
await waitJobs(servers)
// Expiration
@@ -196,14 +180,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..b3cfcacca 100644
--- a/server/tests/api/search/search-activitypub-videos.ts
+++ b/server/tests/api/search/search-activitypub-videos.ts
@@ -1,92 +1,90 @@
/* 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,
- ServerInfo,
+ createMultipleServers,
+ PeerTubeServer,
+ SearchCommand,
setAccessTokensToServers,
- updateVideo,
- uploadVideo,
- wait
-} from '../../../../shared/extra-utils'
-import { waitJobs } from '../../../../shared/extra-utils/server/jobs'
-import { Video, VideoPrivacy } from '../../../../shared/models/videos'
+ wait,
+ waitJobs
+} from '@shared/extra-utils'
+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
+ let command: SearchCommand
+
before(async function () {
this.timeout(120000)
- servers = await flushAndRunMultipleServers(2)
+ servers = await createMultipleServers(2)
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].videos.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].videos.upload({ attributes: { name: 'video 1 on server 2' } })
+ videoServer2UUID = uuid
}
await waitJobs(servers)
+
+ command = servers[0].search
})
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)
+ const body1 = await command.searchVideos({ search })
+ const body2 = await command.searchVideos({ search, token: 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')
+ 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,20 +95,20 @@ 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')
}
})
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].videos.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 () {
@@ -120,8 +118,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].channels.create({ attributes: channelAttributes })
+ const videoChannelId = created.id
const attributes = {
name: 'updated',
@@ -129,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].videos.update({ id: videoServer2UUID, attributes })
await waitJobs(servers)
// Expire video
@@ -137,16 +135,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)
@@ -155,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].videos.remove({ id: videoServer2UUID })
await waitJobs(servers)
// Expire video
@@ -163,14 +161,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..4da2d0ece 100644
--- a/server/tests/api/search/search-channels.ts
+++ b/server/tests/api/search/search-channels.ts
@@ -2,44 +2,39 @@
import 'mocha'
import * as chai from 'chai'
-import { searchVideoChannel, advancedVideoChannelSearch } from '@shared/extra-utils/search/video-channels'
-import {
- addVideoChannel,
- cleanupTests,
- createUser,
- flushAndRunServer,
- ServerInfo,
- setAccessTokensToServers
-} from '../../../../shared/extra-utils'
+import { cleanupTests, createSingleServer, PeerTubeServer, SearchCommand, 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 ])
{
- await createUser({ url: server.url, accessToken: server.accessToken, username: 'user1', password: 'password' })
+ await server.users.create({ username: 'user1', password: 'password' })
const channel = {
name: 'squall_channel',
displayName: 'Squall channel'
}
- await addVideoChannel(server.url, server.accessToken, channel)
+ await server.channels.create({ attributes: channel })
}
+
+ command = server.search
})
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 +44,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 +60,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..feb35411f 100644
--- a/server/tests/api/search/search-index.ts
+++ b/server/tests/api/search/search-index.ts
@@ -2,36 +2,27 @@
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,
- ServerInfo,
- setAccessTokensToServers,
- updateCustomSubConfig,
- uploadVideo
-} 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
describe('Test videos search', function () {
- let server: ServerInfo = null
const localVideoName = 'local video' + new Date().toISOString()
+ 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 uploadVideo(server.url, server.accessToken, { name: localVideoName })
+ await server.videos.upload({ attributes: { name: localVideoName } })
+
+ command = server.search
})
describe('Default search', async function () {
@@ -39,101 +30,107 @@ 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.config.updateCustomSubConfig({
+ newConfig: {
+ search: {
+ searchIndex: {
+ enabled: true,
+ isDefaultSearch: false,
+ disableLocalSearch: false
+ }
}
}
})
- 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 () {
- await updateCustomSubConfig(server.url, server.accessToken, {
- search: {
- searchIndex: {
- enabled: true,
- isDefaultSearch: true,
- disableLocalSearch: false
+ await server.config.updateCustomSubConfig({
+ newConfig: {
+ search: {
+ searchIndex: {
+ enabled: true,
+ isDefaultSearch: true,
+ disableLocalSearch: false
+ }
}
}
})
- 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 () {
- await updateCustomSubConfig(server.url, server.accessToken, {
- search: {
- searchIndex: {
- enabled: true,
- isDefaultSearch: false,
- disableLocalSearch: true
+ await server.config.updateCustomSubConfig({
+ newConfig: {
+ search: {
+ searchIndex: {
+ enabled: true,
+ isDefaultSearch: false,
+ disableLocalSearch: true
+ }
}
}
})
- 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')
@@ -169,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)
}
})
@@ -206,37 +203,44 @@ 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 () {
let nsfwUUID: string
{
- await updateCustomSubConfig(server.url, server.accessToken, { instance: { defaultNSFWPolicy: 'display' } })
+ await server.config.updateCustomSubConfig({
+ newConfig: {
+ 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
}
{
- await updateCustomSubConfig(server.url, server.accessToken, { instance: { defaultNSFWPolicy: 'do_not_list' } })
+ await server.config.updateCustomSubConfig({
+ newConfig: {
+ 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 +251,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 +276,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 +326,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..22e9b8fca 100644
--- a/server/tests/api/search/search-playlists.ts
+++ b/server/tests/api/search/search-playlists.ts
@@ -2,82 +2,71 @@
import 'mocha'
import * as chai from 'chai'
-import { VideoPlaylist, VideoPlaylistPrivacy } from '@shared/models'
import {
- addVideoInPlaylist,
- advancedVideoPlaylistSearch,
cleanupTests,
- createVideoPlaylist,
- flushAndRunServer,
- searchVideoPlaylists,
- ServerInfo,
+ createSingleServer,
+ PeerTubeServer,
+ SearchCommand,
setAccessTokensToServers,
- setDefaultVideoChannel,
- uploadVideoAndGetId
-} from '../../../../shared/extra-utils'
+ setDefaultVideoChannel
+} from '@shared/extra-utils'
+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 ])
- const videoId = (await uploadVideoAndGetId({ server: server, videoName: '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 res = await createVideoPlaylist({ url: server.url, token: server.accessToken, playlistAttrs: attributes })
+ const created = await server.playlists.create({ attributes })
- await addVideoInPlaylist({
- url: server.url,
- token: server.accessToken,
- playlistId: res.body.videoPlaylist.id,
- elementAttrs: { 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 res = await createVideoPlaylist({ url: server.url, token: server.accessToken, playlistAttrs: attributes })
+ const created = await server.playlists.create({ attributes })
- await addVideoInPlaylist({
- url: server.url,
- token: server.accessToken,
- playlistId: res.body.videoPlaylist.id,
- elementAttrs: { 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 createVideoPlaylist({ url: server.url, token: server.accessToken, playlistAttrs: attributes })
+ await server.playlists.create({ attributes })
}
+
+ command = server.search
})
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 +76,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 +91,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 +106,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..965766742 100644
--- a/server/tests/api/search/search-videos.ts
+++ b/server/tests/api/search/search-videos.ts
@@ -2,37 +2,31 @@
import 'mocha'
import * as chai from 'chai'
-import { VideoPrivacy } from '@shared/models'
import {
- advancedVideosSearch,
cleanupTests,
- createLive,
- flushAndRunServer,
- immutableAssign,
- searchVideo,
- sendRTMPStreamInVideo,
- ServerInfo,
+ createSingleServer,
+ PeerTubeServer,
+ SearchCommand,
setAccessTokensToServers,
setDefaultVideoChannel,
stopFfmpeg,
- updateCustomSubConfig,
- 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
describe('Test videos search', function () {
- let server: ServerInfo = null
+ let server: PeerTubeServer = null
let startDate: string
let videoUUID: string
+ let command: SearchCommand
+
before(async function () {
this.timeout(60000)
- server = await flushAndRunServer(1)
+ server = await createSingleServer(1)
await setAccessTokensToServers([ server ])
await setDefaultVideoChannel([ server ])
@@ -46,57 +40,49 @@ describe('Test videos search', function () {
nsfw: false,
language: 'fr'
}
- await uploadVideo(server.url, server.accessToken, attributes1)
+ await server.videos.upload({ attributes: attributes1 })
- const attributes2 = immutableAssign(attributes1, { name: attributes1.name + ' - 2', fixture: 'video_short.mp4' })
- await uploadVideo(server.url, server.accessToken, attributes2)
+ const attributes2 = { ...attributes1, name: attributes1.name + ' - 2', fixture: 'video_short.mp4' }
+ await server.videos.upload({ attributes: attributes2 })
{
- const attributes3 = immutableAssign(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 attributes3 = { ...attributes1, name: attributes1.name + ' - 3', language: undefined }
+ const { id, uuid } = await server.videos.upload({ attributes: attributes3 })
+ videoUUID = uuid
- await createVideoCaption({
- url: server.url,
- accessToken: server.accessToken,
+ await server.captions.add({
language: 'en',
- videoId,
+ videoId: id,
fixture: 'subtitle-good2.vtt',
mimeType: 'application/octet-stream'
})
- await createVideoCaption({
- url: server.url,
- accessToken: server.accessToken,
+ await server.captions.add({
language: 'aa',
- videoId,
+ videoId: id,
fixture: 'subtitle-good2.vtt',
mimeType: 'application/octet-stream'
})
}
- const attributes4 = immutableAssign(attributes1, { name: attributes1.name + ' - 4', language: 'pl', nsfw: true })
- await uploadVideo(server.url, server.accessToken, attributes4)
+ const attributes4 = { ...attributes1, name: attributes1.name + ' - 4', language: 'pl', nsfw: true }
+ await server.videos.upload({ attributes: attributes4 })
await wait(1000)
startDate = new Date().toISOString()
- const attributes5 = immutableAssign(attributes1, { name: attributes1.name + ' - 5', licence: 2, language: undefined })
- await uploadVideo(server.url, server.accessToken, attributes5)
+ const attributes5 = { ...attributes1, name: attributes1.name + ' - 5', licence: 2, language: undefined }
+ await server.videos.upload({ attributes: attributes5 })
- const attributes6 = immutableAssign(attributes1, { name: attributes1.name + ' - 6', tags: [ 't1', 't2' ] })
- await uploadVideo(server.url, server.accessToken, attributes6)
+ const attributes6 = { ...attributes1, name: attributes1.name + ' - 6', tags: [ 't1', 't2' ] }
+ await server.videos.upload({ attributes: attributes6 })
- const attributes7 = immutableAssign(attributes1, {
- name: attributes1.name + ' - 7',
- originallyPublishedAt: '2019-02-12T09:58:08.286Z'
- })
- await uploadVideo(server.url, server.accessToken, attributes7)
+ const attributes7 = { ...attributes1, name: attributes1.name + ' - 7', originallyPublishedAt: '2019-02-12T09:58:08.286Z' }
+ await server.videos.upload({ attributes: attributes7 })
- const attributes8 = immutableAssign(attributes1, { name: attributes1.name + ' - 8', licence: 4 })
- await uploadVideo(server.url, server.accessToken, attributes8)
+ const attributes8 = { ...attributes1, name: attributes1.name + ' - 8', licence: 4 }
+ await server.videos.upload({ attributes: attributes8 })
}
{
@@ -107,9 +93,9 @@ describe('Test videos search', function () {
licence: 2,
language: 'en'
}
- await uploadVideo(server.url, server.accessToken, attributes)
+ await server.videos.upload({ attributes: attributes })
- await uploadVideo(server.url, server.accessToken, immutableAssign(attributes, { name: attributes.name + ' duplicate' }))
+ await server.videos.upload({ attributes: { ...attributes, name: attributes.name + ' duplicate' } })
}
{
@@ -120,7 +106,7 @@ describe('Test videos search', function () {
licence: 3,
language: 'pl'
}
- await uploadVideo(server.url, server.accessToken, attributes)
+ await server.videos.upload({ attributes: attributes })
}
{
@@ -129,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, immutableAssign(attributes1, { category: 2 }))
+ await server.videos.upload({ attributes: attributes1 })
+ await server.videos.upload({ attributes: { ...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 server.videos.upload({ attributes: { ...attributes1, tags: [ 'cccc', 'dddd' ] } })
+ await server.videos.upload({ attributes: { ...attributes1, tags: [ 'eeee', 'ffff' ] } })
}
{
@@ -141,24 +127,26 @@ describe('Test videos search', function () {
name: 'aaaa 2',
category: 1
}
- await uploadVideo(server.url, server.accessToken, attributes1)
- await uploadVideo(server.url, server.accessToken, immutableAssign(attributes1, { category: 2 }))
+ await server.videos.upload({ attributes: attributes1 })
+ await server.videos.upload({ attributes: { ...attributes1, category: 2 } })
}
+
+ command = server.search
})
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 +155,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 +172,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 +187,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 +206,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 +224,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 +246,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 +264,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 +285,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 +311,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 +330,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 +350,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 +372,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 +391,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')
})
@@ -398,99 +408,102 @@ describe('Test videos search', function () {
}
{
- const query = immutableAssign(baseQuery, { originallyPublishedStartDate: '2019-02-11T09:58:08.286Z' })
- const res = await advancedVideosSearch(server.url, query)
+ const query = { ...baseQuery, originallyPublishedStartDate: '2019-02-11T09:58:08.286Z' }
+ 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 query = { ...baseQuery, originallyPublishedEndDate: '2019-03-11T09:58:08.286Z' }
+ 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 query = { ...baseQuery, originallyPublishedEndDate: '2019-01-11T09:58:08.286Z' }
+ 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 query = { ...baseQuery, originallyPublishedStartDate: '2019-03-11T09:58:08.286Z' }
+ const body = await command.advancedVideoSearch({ search: query })
- expect(res.body.total).to.equal(0)
+ 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 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, {
+ const query = {
+ ...baseQuery,
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 () {
this.timeout(30000)
{
- const options = {
+ const newConfig = {
search: {
searchIndex: { enabled: false }
},
live: { enabled: true }
}
- await updateCustomSubConfig(server.url, server.accessToken, options)
+ await server.config.updateCustomSubConfig({ newConfig })
}
{
- 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)
}
{
- 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.live
- const command = await sendRTMPStreamInVideo(server.url, server.accessToken, liveVideoId)
- await waitUntilLivePublished(server.url, server.accessToken, liveVideoId)
+ const liveAttributes = { name: 'live', privacy: VideoPrivacy.PUBLIC, channelId: server.store.channel.id }
+ const live = await liveCommand.create({ fields: liveAttributes })
- const res = await advancedVideosSearch(server.url, { isLive: true })
+ const ffmpegCommand = await liveCommand.sendRTMPStreamInVideo({ videoId: live.id })
+ await liveCommand.waitUntilPublished({ videoId: live.id })
- expect(res.body.total).to.equal(1)
- expect(res.body.data[0].name).to.equal('live')
+ const body = await command.advancedVideoSearch({ search: { isLive: true } })
- await stopFfmpeg(command)
+ expect(body.total).to.equal(1)
+ expect(body.data[0].name).to.equal('live')
+
+ await stopFfmpeg(ffmpegCommand)
}
})
diff --git a/server/tests/api/server/auto-follows.ts b/server/tests/api/server/auto-follows.ts
index 1519b263f..ce7b51925 100644
--- a/server/tests/api/server/auto-follows.ts
+++ b/server/tests/api/server/auto-follows.ts
@@ -3,64 +3,45 @@
import 'mocha'
import * as chai from 'chai'
import {
- acceptFollower,
cleanupTests,
- flushAndRunMultipleServers,
+ createMultipleServers,
MockInstancesIndex,
- ServerInfo,
+ PeerTubeServer,
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) {
+async function checkFollow (follower: PeerTubeServer, following: PeerTubeServer, 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.follows.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 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')
- const follow = follows.find(f => {
- return 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)
+async function server1Follows2 (servers: PeerTubeServer[]) {
+ await servers[0].follows.follow({ hosts: [ servers[1].host ] })
await waitJobs(servers)
}
-async function resetFollows (servers: ServerInfo[]) {
+async function resetFollows (servers: PeerTubeServer[]) {
try {
- await unfollow(servers[0].url, servers[0].accessToken, servers[1])
- await unfollow(servers[1].url, servers[1].accessToken, servers[0])
+ await servers[0].follows.unfollow({ target: servers[1] })
+ await servers[1].follows.unfollow({ target: servers[0] })
} catch { /* empty */
}
@@ -71,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)
@@ -105,7 +86,7 @@ describe('Test auto follows', function () {
}
}
}
- await updateCustomSubConfig(servers[1].url, servers[1].accessToken, config)
+ await servers[1].config.updateCustomSubConfig({ newConfig: config })
await server1Follows2(servers)
@@ -130,14 +111,14 @@ describe('Test auto follows', function () {
}
}
}
- await updateCustomSubConfig(servers[1].url, servers[1].accessToken, 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 acceptFollower(servers[1].url, servers[1].accessToken, 'peertube@' + servers[0].host)
+ await servers[1].follows.acceptFollower({ follower: 'peertube@' + servers[0].host })
await waitJobs(servers)
await checkFollow(servers[0], servers[1], true)
@@ -147,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].config.updateCustomSubConfig({ newConfig: config })
})
})
@@ -184,7 +165,7 @@ describe('Test auto follows', function () {
}
}
}
- await updateCustomSubConfig(servers[0].url, servers[0].accessToken, 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 80fa7fce6..16cbcd5c3 100644
--- a/server/tests/api/server/bulk.ts
+++ b/server/tests/api/server/bulk.ts
@@ -2,91 +2,83 @@
import 'mocha'
import * as chai from 'chai'
-import { Video, VideoComment } from '@shared/models'
import {
- addVideoCommentReply,
- addVideoCommentThread,
- bulkRemoveCommentsOf,
+ BulkCommand,
cleanupTests,
- createUser,
+ createMultipleServers,
doubleFollow,
- flushAndRunMultipleServers,
- getVideoCommentThreads,
- getVideosList,
- ServerInfo,
+ PeerTubeServer,
setAccessTokensToServers,
- uploadVideo,
- userLogin,
waitJobs
-} from '../../../../shared/extra-utils/index'
+} from '@shared/extra-utils'
const expect = chai.expect
describe('Test bulk actions', function () {
const commentsUser3: { videoId: number, commentId: number }[] = []
- let servers: ServerInfo[] = []
- let user1AccessToken: string
- let user2AccessToken: string
- let user3AccessToken: string
+ let servers: PeerTubeServer[] = []
+ let user1Token: string
+ let user2Token: string
+ let user3Token: string
+
+ let bulkCommand: BulkCommand
before(async function () {
this.timeout(30000)
- servers = await flushAndRunMultipleServers(2)
+ servers = await createMultipleServers(2)
// Get the access tokens
await setAccessTokensToServers(servers)
{
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].users.create({ username: user.username, password: user.password })
- user1AccessToken = await userLogin(servers[0], user)
+ user1Token = await servers[0].login.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].users.create({ username: user.username, password: user.password })
- user2AccessToken = await userLogin(servers[0], user)
+ user2Token = await servers[0].login.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].users.create({ username: user.username, password: user.password })
- user3AccessToken = await userLogin(servers[1], user)
+ user3Token = await servers[1].login.getAccessToken(user)
}
await doubleFollow(servers[0], servers[1])
+
+ bulkCommand = new BulkCommand(servers[0])
})
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].videos.list()
// 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')
+ for (const video of data) {
+ 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
}
}
{
- const res = await getVideosList(servers[1].url)
- const videos = res.body.data as Video[]
+ const { data } = await servers[1].videos.list()
// 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')
+ for (const video of data) {
+ 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) {
expect(comment).to.not.exist
@@ -100,30 +92,31 @@ 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, user1AccessToken, { 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 uploadVideo(servers[1].url, servers[1].accessToken, { name: 'video 1 server 2' })
+ await servers[1].videos.upload({ attributes: { name: 'video 1 server 2' } })
await waitJobs(servers)
{
- 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')
+ const { data } = await servers[0].videos.list()
+ for (const video of data) {
+ 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 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')
+ const { data } = await servers[1].videos.list()
- const res = await addVideoCommentThread(servers[1].url, user3AccessToken, video.id, 'comment by user 3')
- commentsUser3.push({ videoId: video.id, commentId: res.body.comment.id })
+ for (const video of data) {
+ await servers[1].comments.createThread({ videoId: video.id, text: 'comment by root server 2' })
+
+ 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 })
}
}
@@ -133,9 +126,8 @@ 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,
- token: user1AccessToken,
+ await bulkCommand.removeCommentsOf({
+ token: user1Token,
attributes: {
accountName: 'user2',
scope: 'my-videos'
@@ -145,18 +137,14 @@ describe('Test bulk actions', function () {
await waitJobs(servers)
for (const server of servers) {
- const res = await getVideosList(server.url)
+ const { data } = await server.videos.list()
- 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')
+ for (const video of data) {
+ 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
- } else {
- expect(comment).to.exist
- }
+ if (video.name === 'video 3 server 1') expect(comment).to.not.exist
+ else expect(comment).to.exist
}
}
})
@@ -164,9 +152,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'
@@ -182,7 +168,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].comments.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/config.ts b/server/tests/api/server/config.ts
index 19bf9582c..fd61e95df 100644
--- a/server/tests/api/server/config.ts
+++ b/server/tests/api/server/config.ts
@@ -2,31 +2,20 @@
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 {
cleanupTests,
- deleteCustomConfig,
- flushAndRunServer,
- getAbout,
- getConfig,
- getCustomConfig,
+ createSingleServer,
killallServers,
makeGetRequest,
parallelTests,
- registerUser,
- reRunServer,
- ServerInfo,
- setAccessTokensToServers,
- updateCustomConfig,
- uploadVideo
-} from '../../../../shared/extra-utils'
-import { ServerConfig } from '../../../../shared/models'
-import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
+ PeerTubeServer,
+ setAccessTokensToServers
+} from '@shared/extra-utils'
+import { CustomConfig, HttpStatusCode } 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.'
@@ -213,18 +202,17 @@ function checkUpdatedConfig (data: CustomConfig) {
}
describe('Test config', function () {
- let server = null
+ let server: PeerTubeServer = null
before(async function () {
this.timeout(30000)
- server = await flushAndRunServer(1)
+ server = await createSingleServer(1)
await setAccessTokensToServers([ server ])
})
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.config.getConfig()
expect(data.signup.allowed).to.be.true
})
@@ -233,35 +221,32 @@ 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.users.register({ username: 'user1' }),
+ server.users.register({ username: 'user2' }),
+ server.users.register({ username: 'user3' })
])
- const res = await getConfig(server.url)
- const data: ServerConfig = res.body
+ const data = await server.config.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.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 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.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 res = await getCustomConfig(server.url, server.accessToken)
- const data = res.body as CustomConfig
+ const data = await server.config.getCustomConfig()
checkInitialConfig(server, data)
})
@@ -438,19 +423,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.config.updateCustomConfig({ newCustomConfig })
+ const data = await server.config.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.config.getConfig()
expect(data.video.file.extensions).to.have.length.above(4)
expect(data.video.file.extensions).to.contain('.mp4')
@@ -463,26 +445,24 @@ 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.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 () {
this.timeout(10000)
- killallServers([ server ])
+ await killallServers([ server ])
- await reRunServer(server)
+ await server.run()
- const res = await getCustomConfig(server.url, server.accessToken)
- const data = res.body
+ const data = await server.config.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.config.getAbout()
expect(data.instance.name).to.equal('PeerTube updated')
expect(data.instance.shortDescription).to.equal('my short description')
@@ -504,11 +484,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.config.deleteCustomConfig()
+ const data = await server.config.getCustomConfig()
checkInitialConfig(server, data)
})
@@ -519,26 +497,26 @@ 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
}
- killallServers([ server ])
+ await killallServers([ server ])
const config = {
security: {
frameguard: { enabled: false }
}
}
- server = await reRunServer(server, config)
+ await server.run(config)
{
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 8851ad55e..c555661ad 100644
--- a/server/tests/api/server/contact-form.ts
+++ b/server/tests/api/server/contact-form.ts
@@ -1,18 +1,25 @@
/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */
-import * as chai from 'chai'
import 'mocha'
-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 { sendContactForm } from '../../../../shared/extra-utils/server/contact-form'
-import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
+import * as chai from 'chai'
+import {
+ cleanupTests,
+ ContactFormCommand,
+ createSingleServer,
+ MockSmtpServer,
+ PeerTubeServer,
+ setAccessTokensToServers,
+ wait,
+ waitJobs
+} from '@shared/extra-utils'
+import { HttpStatusCode } from '@shared/models'
const expect = chai.expect
describe('Test contact form', function () {
- let server: ServerInfo
+ let server: PeerTubeServer
const emails: object[] = []
+ let command: ContactFormCommand
before(async function () {
this.timeout(30000)
@@ -25,15 +32,16 @@ describe('Test contact form', function () {
port
}
}
- server = await flushAndRunServer(1, overrideConfig)
+ server = await createSingleServer(1, overrideConfig)
await setAccessTokensToServers([ server ])
+
+ command = server.contactForm
})
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 +66,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 +85,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/server/tests/api/server/email.ts b/server/tests/api/server/email.ts
index 92768d9df..ae86b380f 100644
--- a/server/tests/api/server/email.ts
+++ b/server/tests/api/server/email.ts
@@ -2,32 +2,13 @@
import 'mocha'
import * as chai from 'chai'
-import {
- addVideoToBlacklist,
- askResetPassword,
- askSendVerifyEmail,
- blockUser,
- cleanupTests,
- createUser,
- flushAndRunServer,
- removeVideoFromBlacklist,
- reportAbuse,
- resetPassword,
- ServerInfo,
- setAccessTokensToServers,
- unblockUser,
- uploadVideo,
- userLogin,
- verifyEmail
-} from '../../../../shared/extra-utils'
-import { MockSmtpServer } from '../../../../shared/extra-utils/miscs/email'
-import { waitJobs } from '../../../../shared/extra-utils/server/jobs'
-import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
+import { cleanupTests, createSingleServer, MockSmtpServer, PeerTubeServer, setAccessTokensToServers, waitJobs } from '@shared/extra-utils'
+import { HttpStatusCode } from '@shared/models'
const expect = chai.expect
describe('Test emails', function () {
- let server: ServerInfo
+ let server: PeerTubeServer
let userId: number
let userId2: number
let userAccessToken: string
@@ -58,31 +39,29 @@ describe('Test emails', function () {
port: emailPort
}
}
- server = await flushAndRunServer(1, overrideConfig)
+ server = await createSingleServer(1, overrideConfig)
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.users.create({ username: user.username, password: user.password })
+ userId = created.id
- userAccessToken = await userLogin(server, user)
+ userAccessToken = await server.login.getAccessToken(user)
}
{
- 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.videos.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.videos.upload({ attributes })
+ videoUUID = uuid
+ videoId = id
}
})
@@ -91,7 +70,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.users.askResetPassword({ email: 'user_1@example.com' })
await waitJobs(server)
expect(emails).to.have.lengthOf(1)
@@ -117,34 +96,40 @@ 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.users.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.users.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.users.resetPassword({
+ userId,
+ verificationString,
+ password: 'super_password3',
+ expectedStatus: HttpStatusCode.FORBIDDEN_403
+ })
})
it('Should login with this new password', async function () {
user.password = 'super_password2'
- await userLogin(server, user)
+ await server.login.getAccessToken(user)
})
})
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.users.create({ username: 'create_password', password: '' })
await waitJobs(server)
expect(emails).to.have.lengthOf(2)
@@ -170,15 +155,24 @@ 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.users.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.users.resetPassword({
+ userId: userId2,
+ verificationString: verificationString2,
+ password: 'newly_created_password'
+ })
})
it('Should login with this new password', async function () {
- await userLogin(server, {
+ await server.login.getAccessToken({
username: 'create_password',
password: 'newly_created_password'
})
@@ -190,7 +184,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.abuses.report({ videoId, reason })
await waitJobs(server)
expect(emails).to.have.lengthOf(3)
@@ -211,7 +205,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.users.banUser({ userId, reason })
await waitJobs(server)
expect(emails).to.have.lengthOf(4)
@@ -229,7 +223,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.users.unbanUser({ userId })
await waitJobs(server)
expect(emails).to.have.lengthOf(5)
@@ -249,7 +243,7 @@ describe('Test emails', function () {
this.timeout(10000)
const reason = 'my super reason'
- await addVideoToBlacklist(server.url, server.accessToken, videoUserUUID, reason)
+ await server.blacklist.add({ videoId: videoUserUUID, reason })
await waitJobs(server)
expect(emails).to.have.lengthOf(6)
@@ -267,7 +261,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.blacklist.remove({ videoId: videoUserUUID })
await waitJobs(server)
expect(emails).to.have.lengthOf(7)
@@ -292,7 +286,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.users.askSendVerifyEmail({ email: 'user_1@example.com' })
await waitJobs(server)
expect(emails).to.have.lengthOf(8)
@@ -318,11 +312,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.users.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.users.verifyEmail({ userId, verificationString })
})
})
diff --git a/server/tests/api/server/follow-constraints.ts b/server/tests/api/server/follow-constraints.ts
index 3f2f71f46..471f5d8d0 100644
--- a/server/tests/api/server/follow-constraints.ts
+++ b/server/tests/api/server/follow-constraints.ts
@@ -1,56 +1,41 @@
/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */
-import * as chai from 'chai'
import 'mocha'
-import {
- cleanupTests,
- doubleFollow,
- flushAndRunMultipleServers,
- getAccountVideos,
- getVideo,
- getVideoChannelVideos,
- getVideoWithToken,
- ServerInfo,
- setAccessTokensToServers,
- uploadVideo
-} 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'
+import * as chai from 'chai'
+import { cleanupTests, createMultipleServers, doubleFollow, PeerTubeServer, setAccessTokensToServers } from '@shared/extra-utils'
+import { HttpStatusCode, 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 userAccessToken: string
+ let userToken: string
before(async function () {
this.timeout(90000)
- servers = await flushAndRunMultipleServers(2)
+ servers = await createMultipleServers(2)
// Get the access tokens
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].videos.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].videos.upload({ attributes: { name: 'video server 2' } })
+ video2UUID = uuid
}
const user = {
username: 'user1',
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)
+ await servers[0].users.create({ username: user.username, password: user.password })
+ userToken = await servers[0].login.getAccessToken(user)
await doubleFollow(servers[0], servers[1])
})
@@ -60,81 +45,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].videos.get({ id: video1UUID })
})
it('Should get the remote video', async function () {
- await getVideo(servers[0].url, video2UUID, HttpStatusCode.OK_200)
+ await servers[0].videos.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].videos.listByAccount({ handle: '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].videos.listByAccount({ handle: '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 handle = 'root_channel@localhost:' + servers[0].port
+ const { total, data } = await servers[0].videos.listByChannel({ handle })
- 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 handle = 'root_channel@localhost:' + servers[1].port
+ const { total, data } = await servers[0].videos.listByChannel({ handle })
- 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].videos.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].videos.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].videos.listByAccount({ token: userToken, handle: '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].videos.listByAccount({ token: userToken, handle: '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 handle = 'root_channel@localhost:' + servers[0].port
+ const { total, data } = await servers[0].videos.listByChannel({ token: userToken, handle })
- 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 handle = 'root_channel@localhost:' + servers[1].port
+ const { total, data } = await servers[0].videos.listByChannel({ token: userToken, handle })
- 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)
})
})
})
@@ -144,19 +129,18 @@ describe('Test follow constraints', function () {
before(async function () {
this.timeout(30000)
- await unfollow(servers[0].url, servers[0].accessToken, 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 getVideo(servers[0].url, video1UUID, HttpStatusCode.OK_200)
+ await servers[0].videos.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].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'
expect(error.type).to.equal(doc)
@@ -171,73 +155,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].videos.listByAccount({
+ token: null,
+ handle: '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].videos.listByAccount({
+ token: null,
+ handle: '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 handle = 'root_channel@localhost:' + servers[0].port
+ const { total, data } = await servers[0].videos.listByChannel({ token: null, handle })
- 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 handle = 'root_channel@localhost:' + servers[1].port
+ const { total, data } = await servers[0].videos.listByChannel({ token: null, handle })
- 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].videos.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].videos.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].videos.listByAccount({ token: userToken, handle: '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].videos.listByAccount({ token: userToken, handle: '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 handle = 'root_channel@localhost:' + servers[0].port
+ const { total, data } = await servers[0].videos.listByChannel({ token: userToken, handle })
- 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 handle = 'root_channel@localhost:' + servers[1].port
+ const { total, data } = await servers[0].videos.listByChannel({ token: userToken, handle })
- 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-moderation.ts b/server/tests/api/server/follows-moderation.ts
index 73c212a32..921f51043 100644
--- a/server/tests/api/server/follows-moderation.ts
+++ b/server/tests/api/server/follows-moderation.ts
@@ -1,77 +1,66 @@
/* 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,
- ServerInfo,
+ createMultipleServers,
+ FollowsCommand,
+ PeerTubeServer,
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'
+ 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)
+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)
+ ]
- 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')
- }
+ for (const fn of fns) {
+ const body = await fn({ start: 0, count: 5, sort: 'createdAt' })
+ expect(body.total).to.equal(1)
- {
- const res = await getFollowersListPaginationAndSort({ url: servers[1].url, start: 0, count: 5, sort: 'createdAt' })
- expect(res.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')
}
}
-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)
- }
+async function checkNoFollowers (servers: PeerTubeServer[]) {
+ const fns = [
+ servers[0].follows.getFollowings.bind(servers[0].follows),
+ servers[1].follows.getFollowers.bind(servers[1].follows)
+ ]
- {
- const res = await getFollowersListPaginationAndSort({ url: servers[1].url, start: 0, count: 5, sort: 'createdAt' })
- expect(res.body.total).to.equal(0)
+ 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 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)
+
+ commands = servers.map(s => s.follows)
})
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({ hosts: [ servers[1].url ] })
await waitJobs(servers)
})
@@ -83,7 +72,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)
})
@@ -104,9 +93,9 @@ describe('Test follows moderation', function () {
}
}
- await updateCustomSubConfig(servers[1].url, servers[1].accessToken, subConfig)
+ await servers[1].config.updateCustomSubConfig({ newConfig: subConfig })
- await follow(servers[0].url, [ servers[1].url ], servers[0].accessToken)
+ await commands[0].follow({ hosts: [ servers[1].url ] })
await waitJobs(servers)
await checkNoFollowers(servers)
@@ -124,9 +113,9 @@ describe('Test follows moderation', function () {
}
}
- await updateCustomSubConfig(servers[1].url, servers[1].accessToken, subConfig)
+ await servers[1].config.updateCustomSubConfig({ newConfig: subConfig })
- await follow(servers[0].url, [ servers[1].url ], servers[0].accessToken)
+ await commands[0].follow({ hosts: [ servers[1].url ] })
await waitJobs(servers)
await checkServer1And2HasFollowers(servers)
@@ -135,7 +124,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 = {
@@ -147,10 +136,10 @@ 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].config.updateCustomSubConfig({ newConfig: subConfig })
+ await servers[2].config.updateCustomSubConfig({ newConfig: subConfig })
- await follow(servers[0].url, [ servers[1].url ], servers[0].accessToken)
+ await commands[0].follow({ hosts: [ servers[1].url ] })
await waitJobs(servers)
await checkServer1And2HasFollowers(servers, 'pending')
@@ -159,7 +148,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 +157,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({ hosts: [ 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..832ba561a 100644
--- a/server/tests/api/server/follows.ts
+++ b/server/tests/api/server/follows.ts
@@ -3,325 +3,374 @@
import 'mocha'
import * as chai from 'chai'
import {
- addVideoCommentReply,
- addVideoCommentThread,
cleanupTests,
completeVideoCheck,
- createUser,
- createVideoCaption,
+ createMultipleServers,
dateIsValid,
- deleteVideoComment,
expectAccountFollows,
- flushAndRunMultipleServers,
- follow,
- getFollowersListPaginationAndSort,
- getFollowingListPaginationAndSort,
- getVideoCommentThreads,
- getVideosList,
- getVideoThreadComments,
- listVideoCaptions,
- rateVideo,
- ServerInfo,
+ expectChannelsFollows,
+ PeerTubeServer,
setAccessTokensToServers,
testCaptionFile,
- unfollow,
- uploadVideo,
- userLogin,
waitJobs
} from '@shared/extra-utils'
-import { Video, VideoCaption, VideoComment, VideoCommentThreadTree, VideoPrivacy } from '@shared/models'
+import { VideoCreateResult, VideoPrivacy } from '@shared/models'
const expect = chai.expect
describe('Test 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)
})
- 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
+ describe('Data propagation after follow', function () {
- expect(res.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' })
+ ])
+
+ for (const body of bodies) {
+ expect(body.total).to.equal(0)
+
+ const follows = body.data
+ expect(follows).to.be.an('array')
+ expect(follows).to.have.lengthOf(0)
+ }
+ }
+ })
+
+ it('Should have server 1 following root account of server 2 and server 3', async function () {
+ this.timeout(30000)
+
+ await servers[0].follows.follow({
+ hosts: [ servers[2].url ],
+ handles: [ 'root@' + servers[1].host ]
+ })
+
+ await waitJobs(servers)
+ })
+
+ 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)
+
+ let follows = body.data
expect(follows).to.be.an('array')
- expect(follows.length).to.equal(0)
- }
- })
+ expect(follows).to.have.lengthOf(1)
- 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 body2 = await servers[0].follows.getFollowings({ start: 1, count: 1, sort: 'createdAt' })
+ follows = follows.concat(body2.data)
- expect(res.body.total).to.equal(0)
+ const server2Follow = follows.find(f => f.following.host === servers[1].host)
+ const server3Follow = follows.find(f => f.following.host === servers[2].host)
+
+ expect(server2Follow).to.not.be.undefined
+ expect(server2Follow.following.name).to.equal('root')
+ expect(server2Follow.state).to.equal('accepted')
+
+ expect(server3Follow).to.not.be.undefined
+ expect(server3Follow.following.name).to.equal('peertube')
+ expect(server3Follow.state).to.equal('accepted')
+ })
+
+ 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).to.be.an('array')
+ expect(follows).to.have.lengthOf(0)
+ }
+ })
+
+ 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.length).to.equal(0)
- }
- })
-
- 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 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
-
- expect(res.body.total).to.equal(2)
- 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 server2Follow = follows.find(f => f.following.host === 'localhost:' + servers[1].port)
- const server3Follow = follows.find(f => f.following.host === 'localhost:' + servers[2].port)
-
- expect(server2Follow).to.not.be.undefined
- expect(server3Follow).to.not.be.undefined
- expect(server2Follow.state).to.equal('accepted')
- expect(server3Follow.state).to.equal('accepted')
- })
-
- it('Should search/filter followings on server 1', async 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
-
- expect(res.body.total).to.equal(1)
- 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 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 res = await getFollowingListPaginationAndSort({
- url,
- start,
- count,
- sort,
- search,
- state: 'accepted',
- actorType: 'Application'
- })
- expect(res.body.total).to.equal(1)
- expect(res.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 res = await getFollowingListPaginationAndSort({ url, start, count, sort, search: 'bla' })
- const follows = res.body.data
-
- expect(res.body.total).to.equal(0)
- expect(follows.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
-
- expect(res.body.total).to.equal(0)
- expect(follows).to.be.an('array')
- expect(follows.length).to.equal(0)
- }
- })
-
- 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 follows = res.body.data
- expect(res.body.total).to.equal(1)
- expect(follows).to.be.an('array')
- expect(follows.length).to.equal(1)
+ expect(follows).to.have.lengthOf(1)
expect(follows[0].follower.host).to.equal('localhost:' + servers[0].port)
- }
- })
+ })
- it('Should search/filter followers on server 2', async function () {
- const url = servers[2].url
- const start = 0
- const count = 5
- const sort = 'createdAt'
+ 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 search = servers[0].port + ''
+ 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 res = await getFollowersListPaginationAndSort({ url, start, count, sort, search })
- const follows = res.body.data
+ const search = ':' + servers[1].port
- expect(res.body.total).to.equal(1)
- expect(follows.length).to.equal(1)
- expect(follows[0].following.host).to.equal('localhost:' + servers[2].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 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 servers[0].follows.getFollowings({ start, count, sort, search: 'root' })
+ 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 servers[0].follows.getFollowings({ start, count, sort, search: 'bla' })
+ 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 search = servers[0].port + ''
+
+ {
+ const body = await servers[2].follows.getFollowers({ 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[2].host)
+ }
+
+ {
+ 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 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)
+ }
+
+ {
+ 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 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 res = await getFollowersListPaginationAndSort({
- url,
- start,
- count,
- sort,
- search,
- state: 'accepted',
- actorType: 'Application'
- })
- expect(res.body.total).to.equal(1)
- expect(res.body.data).to.have.lengthOf(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).to.have.lengthOf(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: 1, following: 0 })
+ await expectAccountFollows({ server: servers[0], handle: 'peertube@' + servers[2].host, followers: 1, following: 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 })
+
+ 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 unfollow server 3 on server 1', async function () {
+ this.timeout(15000)
+
+ 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).to.be.an('array')
+ expect(follows).to.have.lengthOf(1)
+
+ expect(follows[0].following.host).to.equal(servers[1].host)
+ })
+
+ 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)
+
+ const follows = body.data
+ expect(follows).to.be.an('array')
+ expect(follows).to.have.lengthOf(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[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 })
+
+ 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 })
+ })
+
+ 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].videos.upload({ attributes: { name: 'server2' } })
+ await servers[2].videos.upload({ attributes: { name: 'server3' } })
+
+ await waitJobs(servers)
+
+ {
+ const { total, data } = await servers[0].videos.list()
+ expect(total).to.equal(1)
+ expect(data[0].name).to.equal('server2')
}
{
- 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 { total, data } = await servers[1].videos.list()
+ expect(total).to.equal(1)
+ expect(data[0].name).to.equal('server2')
}
- }
- {
- const res = await getFollowersListPaginationAndSort({ url, start, count, sort, search: 'bla' })
- const follows = res.body.data
+ {
+ const { total, data } = await servers[2].videos.list()
+ expect(total).to.equal(1)
+ expect(data[0].name).to.equal('server3')
+ }
+ })
- expect(res.body.total).to.equal(0)
- expect(follows.length).to.equal(0)
- }
+ it('Should remove account follow', async function () {
+ this.timeout(15000)
+
+ await servers[0].follows.unfollow({ target: 'root@' + servers[1].host })
+
+ await waitJobs(servers)
+ })
+
+ 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 })
+
+ {
+ const { total, data } = await servers[0].follows.getFollowings()
+ expect(total).to.equal(0)
+ expect(data).to.have.lengthOf(0)
+ }
+
+ {
+ const { total, data } = await servers[0].videos.list()
+ expect(total).to.equal(0)
+ expect(data).to.have.lengthOf(0)
+ }
+ })
+
+ it('Should follow a channel', async function () {
+ this.timeout(15000)
+
+ await servers[0].follows.follow({
+ handles: [ 'root_channel@' + servers[1].host ]
+ })
+
+ await waitJobs(servers)
+
+ 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)
+ }
+ })
})
- 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
-
- expect(res.body.total).to.equal(0)
- expect(follows).to.be.an('array')
- expect(follows.length).to.equal(0)
- })
-
- 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)
-
- // 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(servers[2].url, 'peertube@localhost:' + servers[0].port, 0, 1)
- await expectAccountFollows(servers[2].url, 'peertube@localhost:' + servers[2].port, 1, 0)
- })
-
- it('Should unfollow server 3 on server 1', async function () {
- this.timeout(5000)
-
- await unfollow(servers[0].url, servers[0].accessToken, 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
-
- expect(res.body.total).to.equal(1)
- expect(follows).to.be.an('array')
- expect(follows.length).to.equal(1)
-
- expect(follows[0].following.host).to.equal('localhost:' + servers[1].port)
- })
-
- 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 follows = res.body.data
- expect(res.body.total).to.equal(0)
- expect(follows).to.be.an('array')
- expect(follows.length).to.equal(0)
- })
-
- 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(servers[1].url, 'peertube@localhost:' + servers[0].port, 0, 1)
- await expectAccountFollows(servers[1].url, 'peertube@localhost:' + servers[1].port, 1, 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)
- })
-
- 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 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')
-
- res = await getVideosList(servers[1].url)
- expect(res.body.total).to.equal(1)
- expect(res.body.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')
- })
-
- 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)
@@ -334,100 +383,75 @@ 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].videos.upload({ attributes: { name: 'server3-2' } })
+ await servers[2].videos.upload({ attributes: { name: 'server3-3' } })
+ 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 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].users.generateUserAndToken('captain')
- const resVideos = await getVideosList(servers[2].url)
- video4 = resVideos.body.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')
- }
-
- {
- {
- 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 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 text2 = 'my super answer to answer of thread 1'
- await addVideoCommentReply(servers[2].url, servers[2].accessToken, video4.id, childCommentId, text2)
-
- const text3 = 'my second answer to thread 1'
- await addVideoCommentReply(servers[2].url, servers[2].accessToken, video4.id, threadId, 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 text1 = 'answer to deleted'
- await addVideoCommentReply(servers[2].url, servers[2].accessToken, video4.id, threadId, 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 text3 = 'my second answer to deleted'
- await addVideoCommentReply(servers[2].url, servers[2].accessToken, video4.id, childCommentId, text3)
-
- await deleteVideoComment(servers[2].url, servers[2].accessToken, video4.id, threadId)
- await deleteVideoComment(servers[2].url, servers[2].accessToken, video4.id, childCommentId)
- }
- }
-
- {
- await createVideoCaption({
- url: servers[2].url,
- accessToken: servers[2].accessToken,
- language: 'ar',
- videoId: video4.id,
- fixture: 'subtitle-good2.vtt'
- })
- }
+ await servers[2].videos.rate({ id: video4.id, rating: 'like' })
+ await servers[2].videos.rate({ token: userAccessToken, id: video4.id, rating: 'dislike' })
}
+ {
+ await servers[2].comments.createThread({ videoId: video4.id, text: 'my super first comment' })
+
+ 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 { id: threadId } = await servers[2].comments.createThread({ videoId: video4.id, text: 'will be deleted' })
+ await servers[2].comments.addReplyToLastThread({ text: 'answer to deleted' })
+
+ const { id: replyId } = await servers[2].comments.addReplyToLastThread({ text: 'will also be deleted' })
+
+ await servers[2].comments.addReplyToLastReply({ text: 'my second answer to deleted' })
+
+ await servers[2].comments.delete({ videoId: video4.id, commentId: threadId })
+ await servers[2].comments.delete({ videoId: video4.id, commentId: replyId })
+ }
+
+ await servers[2].captions.add({
+ language: 'ar',
+ videoId: video4.id,
+ fixture: 'subtitle-good2.vtt'
+ })
+
await waitJobs(servers)
// Server 1 follows server 3
- await follow(servers[0].url, [ servers[2].url ], servers[0].accessToken)
+ await servers[0].follows.follow({ hosts: [ servers[2].url ] })
await waitJobs(servers)
})
- 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)
+ 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(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@' + 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(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@' + 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 () {
- const res = await getVideosList(servers[0].url)
- expect(res.body.total).to.equal(7)
+ const { total, data } = await servers[0].videos.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
@@ -444,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,
@@ -468,33 +492,31 @@ describe('Test follows', function () {
}
]
}
- await completeVideoCheck(servers[0].url, video4, checkAttributes)
+ await completeVideoCheck(servers[0], video4, checkAttributes)
})
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].comments.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)
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
const threadId = comment.threadId
- const res2 = await getVideoThreadComments(servers[0].url, video4.id, threadId)
-
- const tree: VideoCommentThreadTree = res2.body
+ 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)
@@ -512,7 +534,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
@@ -522,9 +544,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].comments.getThread({ videoId: video4.id, threadId: deletedComment.threadId })
const [ commentRoot, deletedChildRoot ] = tree.children
expect(deletedChildRoot).to.not.be.undefined
@@ -549,11 +569,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].captions.list({ 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$'))
@@ -563,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 unfollow(servers[0].url, servers[0].accessToken, servers[2])
+ await servers[0].follows.unfollow({ target: servers[2] })
await waitJobs(servers)
- const res = await getVideosList(servers[0].url)
- expect(res.body.total).to.equal(1)
+ 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 d57d72f5e..2f3950354 100644
--- a/server/tests/api/server/handle-down.ts
+++ b/server/tests/api/server/handle-down.ts
@@ -1,51 +1,31 @@
/* 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 {
cleanupTests,
- closeAllSequelize,
+ CommentsCommand,
completeVideoCheck,
- flushAndRunMultipleServers,
- getVideo,
- getVideosList,
- immutableAssign,
+ createMultipleServers,
killallServers,
- reRunServer,
- ServerInfo,
+ PeerTubeServer,
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 { HttpStatusCode, 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
let commentIdServer2: number
- let missedVideo1: Video
- let missedVideo2: Video
- let unlistedVideo: Video
+ let missedVideo1: VideoCreateResult
+ let missedVideo2: VideoCreateResult
+ let unlistedVideo: VideoCreateResult
const videoIdsServer1: string[] = []
@@ -62,17 +42,18 @@ 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
+ let commentCommands: CommentsCommand[]
+
before(async function () {
this.timeout(30000)
- servers = await flushAndRunMultipleServers(3)
+ servers = await createMultipleServers(3)
+ commentCommands = servers.map(s => s.comments)
checkAttributes = {
name: 'my super name for server 1',
@@ -106,9 +87,7 @@ describe('Test handle downs', function () {
}
]
}
- unlistedCheckAttributes = immutableAssign(checkAttributes, {
- privacy: VideoPrivacy.UNLISTED
- })
+ unlistedCheckAttributes = { ...checkAttributes, privacy: VideoPrivacy.UNLISTED }
// Get the access tokens
await setAccessTokensToServers(servers)
@@ -118,58 +97,53 @@ 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].follows.follow({ hosts: [ servers[0].url ] })
+ await servers[2].follows.follow({ hosts: [ servers[0].url ] })
await waitJobs(servers)
// Upload a video to server 1
- await uploadVideo(servers[0].url, servers[0].accessToken, videoAttributes)
+ await servers[0].videos.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.videos.list()
+ expect(data).to.be.an('array')
+ expect(data).to.have.lengthOf(1)
}
// Kill server 2
- killallServers([ servers[1] ])
+ await killallServers([ servers[1] ])
// Remove server 2 follower
for (let i = 0; i < 10; i++) {
- await uploadVideo(servers[0].url, servers[0].accessToken, videoAttributes)
+ await servers[0].videos.upload({ attributes: videoAttributes })
}
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
+ missedVideo1 = await servers[0].videos.upload({ attributes: videoAttributes })
- const resLastVideo2 = await uploadVideo(servers[0].url, servers[0].accessToken, videoAttributes)
- missedVideo2 = resLastVideo2.body.video
+ missedVideo2 = await servers[0].videos.upload({ attributes: videoAttributes })
// Unlisted video
- const resVideo = await uploadVideo(servers[0].url, servers[0].accessToken, unlistedVideoAttributes)
- unlistedVideo = resVideo.body.video
+ unlistedVideo = await servers[0].videos.upload({ attributes: unlistedVideoAttributes })
// 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])
@@ -177,90 +151,87 @@ 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].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)
})
it('Should not have pending/processing jobs anymore', async 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].jobs.getJobsList({
state: state,
start: 0,
count: 50,
sort: '-createdAt'
})
- expect(res.body.data).to.have.length(0)
+ expect(body.data).to.have.length(0)
}
})
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 unfollow(servers[1].url, servers[1].accessToken, servers[0])
+ await servers[1].follows.unfollow({ target: servers[0] })
await waitJobs(servers)
- await follow(servers[1].url, [ servers[0].url ], servers[1].accessToken)
+ await servers[1].follows.follow({ hosts: [ 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].follows.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 () {
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].videos.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].videos.update({ id: missedVideo1.uuid })
+ await servers[0].videos.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].videos.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].videos.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 () {
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)
- const resVideo = await getVideo(servers[2].url, missedVideo2.uuid)
- expect(resVideo.body).not.to.be.undefined
+ await servers[2].videos.get({ id: missedVideo2.uuid })
{
- 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)
+ const { data } = await servers[2].comments.listThreads({ videoId: missedVideo2.uuid })
+ expect(data).to.be.an('array')
+ expect(data).to.have.lengthOf(1)
- threadIdServer2 = resComment.body.data[0].id
+ threadIdServer2 = data[0].id
- resComment = await getVideoThreadComments(servers[2].url, missedVideo2.uuid, threadIdServer2)
-
- const tree: VideoCommentThreadTree = resComment.body
+ 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)
@@ -283,57 +254,54 @@ 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].comments.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 () {
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].videos.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].videos.get({ id })
}
await waitJobs(servers)
- await setActorFollowScores(servers[1].internalServerNumber, 20)
+ await servers[1].sql.setActorFollowScores(20)
// Wait video expiration
await wait(11000)
// Refresh video -> score + 10 = 30
- await getVideo(servers[1].url, videoIdsServer1[0])
+ await servers[1].videos.get({ id: videoIdsServer1[0] })
await waitJobs(servers)
})
@@ -341,27 +309,25 @@ 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)
for (let i = 0; i < 5; i++) {
try {
- await getVideo(servers[1].url, videoIdsServer1[i])
+ await servers[1].videos.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].videos.get({ id, expectedStatus: HttpStatusCode.FORBIDDEN_403 })
}
})
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 e8ba89ca6..cb3ba5677 100644
--- a/server/tests/api/server/homepage.ts
+++ b/server/tests/api/server/homepage.ts
@@ -2,51 +2,48 @@
import 'mocha'
import * as chai from 'chai'
-import { HttpStatusCode } from '@shared/core-utils'
-import { CustomPage, ServerConfig } from '@shared/models'
+import { HttpStatusCode } from '@shared/models'
import {
cleanupTests,
- flushAndRunServer,
- getConfig,
- getInstanceHomepage,
+ createSingleServer,
+ CustomPagesCommand,
killallServers,
- reRunServer,
- ServerInfo,
- setAccessTokensToServers,
- updateInstanceHomepage
+ PeerTubeServer,
+ setAccessTokensToServers
} from '../../../../shared/extra-utils/index'
const expect = chai.expect
-async function getHomepageState (server: ServerInfo) {
- const res = await getConfig(server.url)
+async function getHomepageState (server: PeerTubeServer) {
+ const config = await server.config.getConfig()
- const config = res.body as ServerConfig
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
})
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)
@@ -56,12 +53,11 @@ 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)
+ await server.run()
- 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 +65,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/server/tests/api/server/jobs.ts b/server/tests/api/server/jobs.ts
index d0e222997..c10c154c2 100644
--- a/server/tests/api/server/jobs.ts
+++ b/server/tests/api/server/jobs.ts
@@ -1,24 +1,26 @@
/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */
-import * as chai from 'chai'
import 'mocha'
-import { cleanupTests, ServerInfo, setAccessTokensToServers } from '../../../../shared/extra-utils/index'
-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'
+import * as chai from 'chai'
+import {
+ cleanupTests,
+ createMultipleServers,
+ dateIsValid,
+ doubleFollow,
+ PeerTubeServer,
+ setAccessTokensToServers,
+ waitJobs
+} from '@shared/extra-utils'
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)
@@ -27,36 +29,34 @@ 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' })
+ 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 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].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 res = await getJobsListPaginationAndSort({
- url: servers[1].url,
- accessToken: servers[1].accessToken,
+ const body = await servers[1].jobs.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 +66,26 @@ describe('Test jobs', function () {
}
{
- const res = await getJobsListPaginationAndSort({
- url: servers[1].url,
- accessToken: servers[1].accessToken,
+ const body = await servers[1].jobs.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].jobs.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/server/logs.ts b/server/tests/api/server/logs.ts
index bc398ea73..bcd94dda3 100644
--- a/server/tests/api/server/logs.ts
+++ b/server/tests/api/server/logs.ts
@@ -4,27 +4,27 @@ import 'mocha'
import * as chai from 'chai'
import {
cleanupTests,
- flushAndRunServer,
+ createSingleServer,
killallServers,
- 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'
+ LogsCommand,
+ PeerTubeServer,
+ setAccessTokensToServers,
+ waitJobs
+} from '@shared/extra-utils'
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
})
describe('With the standard log file', function () {
@@ -32,16 +32,16 @@ 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.videos.upload({ attributes: { name: 'video 1' } })
await waitJobs([ server ])
const now = new Date()
- await uploadVideo(server.url, server.accessToken, { name: 'video 2' })
+ await server.videos.upload({ attributes: { 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
@@ -50,21 +50,21 @@ 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.videos.upload({ attributes: { name: 'video 3' } })
await waitJobs([ server ])
const now1 = new Date()
- await uploadVideo(server.url, server.accessToken, { name: 'video 4' })
+ await server.videos.upload({ attributes: { name: 'video 4' } })
await waitJobs([ server ])
const now2 = new Date()
- await uploadVideo(server.url, server.accessToken, { name: 'video 5' })
+ await server.videos.upload({ attributes: { 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
@@ -76,19 +76,19 @@ describe('Test logs', function () {
const now = new Date()
- await uploadVideo(server.url, server.accessToken, { name: 'video 6' })
+ await server.videos.upload({ attributes: { name: 'video 6' } })
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
}
@@ -99,10 +99,10 @@ describe('Test logs', function () {
const now = new Date()
- await makePingRequest(server)
+ await server.servers.ping()
- 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
})
@@ -110,16 +110,16 @@ 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 } })
+ await server.run({ log: { log_ping_requests: false } })
const now = new Date()
- await makePingRequest(server)
+ await server.servers.ping()
- 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
})
@@ -129,23 +129,23 @@ 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.videos.upload({ attributes: { name: 'video 7' } })
await waitJobs([ server ])
const now = new Date()
- await uploadVideo(server.url, server.accessToken, { name: 'video 8' })
+ await server.videos.upload({ attributes: { 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')
@@ -155,21 +155,21 @@ 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.videos.upload({ attributes: { name: 'video 9' } })
await waitJobs([ server ])
const now1 = new Date()
- await uploadVideo(server.url, server.accessToken, { name: 'video 10' })
+ await server.videos.upload({ attributes: { name: 'video 10' } })
await waitJobs([ server ])
const now2 = new Date()
- await uploadVideo(server.url, server.accessToken, { name: 'video 11' })
+ await server.videos.upload({ attributes: { 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/server/tests/api/server/no-client.ts b/server/tests/api/server/no-client.ts
index d589f51f3..efa890ad4 100644
--- a/server/tests/api/server/no-client.ts
+++ b/server/tests/api/server/no-client.ts
@@ -1,16 +1,15 @@
import 'mocha'
import * as request from 'supertest'
-import { ServerInfo } from '../../../../shared/extra-utils'
-import { cleanupTests, flushAndRunServer } 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: 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 6b61c7c33..5f9f4ffdd 100644
--- a/server/tests/api/server/plugins.ts
+++ b/server/tests/api/server/plugins.ts
@@ -2,41 +2,23 @@
import 'mocha'
import * as chai from 'chai'
-import { HttpStatusCode } from '@shared/core-utils'
import {
cleanupTests,
- closeAllSequelize,
- flushAndRunServer,
- getConfig,
- getMyUserInformation,
- getPlugin,
- getPluginPackageJSON,
- getPluginTestPath,
- getPublicSettings,
- installPlugin,
+ createSingleServer,
killallServers,
- listAvailablePlugins,
- listPlugins,
- reRunServer,
- ServerInfo,
+ PeerTubeServer,
+ PluginsCommand,
setAccessTokensToServers,
- setPluginVersion,
testHelloWorldRegisteredSettings,
- uninstallPlugin,
- updateCustomSubConfig,
- updateMyUser,
- updatePlugin,
- updatePluginPackageJSON,
- updatePluginSettings,
- wait,
- waitUntilLog
+ wait
} from '@shared/extra-utils'
-import { PeerTubePlugin, PeerTubePluginIndex, PluginPackageJson, PluginType, PublicServerSetting, ServerConfig, User } from '@shared/models'
+import { HttpStatusCode, 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 () {
this.timeout(30000)
@@ -46,68 +28,61 @@ 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
})
it('Should list and search available plugins and themes', async 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,22 +90,12 @@ 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 () {
- const res = await getConfig(server.url)
- const config: ServerConfig = res.body
+ const config = await server.config.getConfig()
const theme = config.theme.registered.find(r => r.name === 'background-red')
expect(theme).to.not.be.undefined
@@ -140,66 +105,56 @@ 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.config.updateCustomSubConfig({
+ newConfig: {
+ theme: { default: 'background-red' }
+ }
+ })
+ const config = await server.config.getConfig()
expect(config.theme.default).to.equal('background-red')
})
it('Should update my default theme', async function () {
- await updateMyUser({
- url: server.url,
- accessToken: server.accessToken,
- theme: 'background-red'
- })
+ await server.users.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.users.getMyInfo()
+ expect(user.theme).to.equal('background-red')
})
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 { data } = await command.list({
count: 2,
start: 0,
sort: 'name'
})
- const data: PeerTubePlugin[] = res.body.data
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 +163,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 +176,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
})
@@ -233,18 +185,12 @@ describe('Test plugins', function () {
it('Should have watched settings changes', async function () {
this.timeout(10000)
- await waitUntilLog(server, 'Settings changed!')
+ await server.servers.waitUntilLog('Settings changed!')
})
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 +208,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')
@@ -292,101 +232,66 @@ describe('Test plugins', function () {
await wait(6000)
// Fake update our plugin version
- await setPluginVersion(server.internalServerNumber, 'hello-world', '0.0.1')
+ await server.sql.setPluginVersion('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)
+ await killallServers([ server ])
+ await server.run()
{
- 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'
- })
+ await command.update({ npmName: 'peertube-plugin-hello-world' })
- 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(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'
- })
+ await command.uninstall({ npmName: 'peertube-plugin-hello-world' })
- const res = await listPlugins({
- url: server.url,
- accessToken: server.accessToken,
- pluginType: PluginType.PLUGIN
- })
-
- 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 () {
- // get /config (default theme + registered themes + registered plugins)
- const res = await getConfig(server.url)
- const config: ServerConfig = res.body
+ const config = await server.config.getConfig()
expect(config.theme.default).to.equal('default')
@@ -398,42 +303,33 @@ 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.users.getMyInfo()
+ expect(user.theme).to.equal('instance-default')
})
it('Should not install a broken plugin', async 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
})
await check()
- killallServers([ server ])
- await reRunServer(server)
+ await killallServers([ server ])
+ await server.run()
await check()
})
after(async function () {
- await closeAllSequelize([ server ])
await cleanupTests([ server ])
})
})
diff --git a/server/tests/api/server/reverse-proxy.ts b/server/tests/api/server/reverse-proxy.ts
index 17d1ee4a5..484f88d67 100644
--- a/server/tests/api/server/reverse-proxy.ts
+++ b/server/tests/api/server/reverse-proxy.ts
@@ -1,16 +1,12 @@
/* 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 { cleanupTests, createSingleServer, PeerTubeServer, setAccessTokensToServers, wait } from '@shared/extra-utils'
+import { HttpStatusCode } from '@shared/models'
describe('Test application behind a reverse proxy', function () {
- let server = null
- let videoId
+ let server: PeerTubeServer
+ let videoId: string
before(async function () {
this.timeout(30000)
@@ -34,85 +30,85 @@ describe('Test application behind a reverse proxy', function () {
}
}
- server = await flushAndRunServer(1, config)
+ server = await createSingleServer(1, config)
await setAccessTokensToServers([ server ])
- const { body } = await uploadVideo(server.url, server.accessToken, {})
- videoId = body.video.uuid
+ 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 viewVideo(server.url, videoId)
- await viewVideo(server.url, videoId)
+ await server.videos.view({ id: videoId })
+ await server.videos.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.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 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.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 { body } = await getVideo(server.url, videoId)
- expect(body.views).to.equal(3)
+ 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 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.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 { body } = await getVideo(server.url, videoId)
- expect(body.views).to.equal(4)
+ 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 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.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 { body } = await getVideo(server.url, videoId)
- expect(body.views).to.equal(6)
+ const video = await server.videos.get({ id: videoId })
+ expect(video.views).to.equal(6)
})
it('Should rate limit logins', async function () {
const user = { username: 'root', password: 'fail' }
for (let i = 0; i < 19; i++) {
- await userLogin(server, user, HttpStatusCode.BAD_REQUEST_400)
+ await server.login.login({ user, expectedStatus: HttpStatusCode.BAD_REQUEST_400 })
}
- await userLogin(server, user, 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 registerUser(server.url, 'test' + i, 'password')
+ await server.users.register({ username: 'test' + i })
} catch {
// empty
}
}
- await registerUser(server.url, 'test42', 'password', 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 () {
@@ -121,10 +117,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.users.register({ username: 'test' + i, expectedStatus: HttpStatusCode.CONFLICT_409 })
}
- await registerUser(server.url, 'test43', 'password', HttpStatusCode.NO_CONTENT_204)
+ await server.users.register({ username: 'test43', expectedStatus: HttpStatusCode.NO_CONTENT_204 })
})
@@ -135,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.videos.get({ id: videoId })
} catch {
// don't care if it fails
}
}
- await getVideo(server.url, videoId, 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 ea64e4040..69d030dbb 100644
--- a/server/tests/api/server/services.ts
+++ b/server/tests/api/server/services.ts
@@ -2,23 +2,13 @@
import 'mocha'
import * as chai from 'chai'
+import { cleanupTests, createSingleServer, PeerTubeServer, setAccessTokensToServers, setDefaultVideoChannel } from '@shared/extra-utils'
import { Video, VideoPlaylistPrivacy } from '@shared/models'
-import {
- addVideoInPlaylist,
- createVideoPlaylist,
- getOEmbed,
- getVideosList,
- ServerInfo,
- setAccessTokensToServers,
- setDefaultVideoChannel,
- uploadVideo
-} from '../../../../shared/extra-utils'
-import { cleanupTests, flushAndRunServer } from '../../../../shared/extra-utils/server/servers'
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
@@ -26,40 +16,34 @@ describe('Test services', function () {
before(async function () {
this.timeout(30000)
- server = await flushAndRunServer(1)
+ server = await createSingleServer(1)
await setAccessTokensToServers([ server ])
await setDefaultVideoChannel([ server ])
{
- const videoAttributes = {
- name: 'my super name'
- }
- await uploadVideo(server.url, server.accessToken, videoAttributes)
+ const attributes = { name: 'my super name' }
+ await server.videos.upload({ attributes })
- const res = await getVideosList(server.url)
- video = res.body.data[0]
+ const { data } = await server.videos.list()
+ video = data[0]
}
{
- const res = await createVideoPlaylist({
- url: server.url,
- token: server.accessToken,
- playlistAttrs: {
+ 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 = 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.playlists.addElement({
+ playlistId: created.id,
+ attributes: {
videoId: video.id
}
})
@@ -70,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 getOEmbed(server.url, oembedUrl)
+ const res = await server.services.getOEmbed({ oembedUrl })
const expectedHtml = ''
@@ -78,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)
@@ -91,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 getOEmbed(server.url, 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
@@ -114,14 +98,14 @@ describe('Test services', function () {
const maxHeight = 50
const maxWidth = 50
- const res = await getOEmbed(server.url, 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 304181a6d..5ec771429 100644
--- a/server/tests/api/server/stats.ts
+++ b/server/tests/api/server/stats.ts
@@ -3,33 +3,20 @@
import 'mocha'
import * as chai from 'chai'
import {
- addVideoChannel,
cleanupTests,
- createUser,
- createVideoPlaylist,
+ createMultipleServers,
doubleFollow,
- flushAndRunMultipleServers,
- follow,
- ServerInfo,
- unfollow,
- 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'
+ PeerTubeServer,
+ setAccessTokensToServers,
+ wait,
+ waitJobs
+} from '@shared/extra-utils'
+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',
@@ -39,31 +26,29 @@ describe('Test stats (excluding redundancy)', function () {
before(async function () {
this.timeout(60000)
- servers = await flushAndRunMultipleServers(3)
+ servers = await createMultipleServers(3)
await setAccessTokensToServers(servers)
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].users.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].videos.upload({ attributes: { fixture: 'video_short.webm' } })
- await addVideoCommentThread(servers[0].url, servers[0].accessToken, videoUUID, 'comment')
+ await servers[0].comments.createThread({ videoId: uuid, text: 'comment' })
- await viewVideo(servers[0].url, videoUUID)
+ await servers[0].videos.view({ id: uuid })
// Wait the video views repeatable job
await wait(8000)
- await follow(servers[2].url, [ servers[0].url ], servers[2].accessToken)
+ await servers[2].follows.follow({ hosts: [ servers[0].url ] })
await waitJobs(servers)
})
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].stats.get()
expect(data.totalLocalVideoComments).to.equal(1)
expect(data.totalLocalVideos).to.equal(1)
@@ -78,8 +63,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].stats.get()
expect(data.totalLocalVideoComments).to.equal(0)
expect(data.totalLocalVideos).to.equal(0)
@@ -94,8 +78,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].stats.get()
expect(data.totalLocalVideoComments).to.equal(0)
expect(data.totalLocalVideos).to.equal(0)
@@ -111,11 +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 unfollow(servers[2].url, servers[2].accessToken, servers[0])
+ await servers[2].follows.unfollow({ target: servers[0] })
await waitJobs(servers)
- const res = await getStats(servers[2].url)
- const data: ServerStats = res.body
+ const data = await servers[2].stats.get()
expect(data.totalVideos).to.equal(0)
})
@@ -124,18 +106,18 @@ 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.stats.get()
+
expect(data.totalDailyActiveUsers).to.equal(1)
expect(data.totalWeeklyActiveUsers).to.equal(1)
expect(data.totalMonthlyActiveUsers).to.equal(1)
}
{
- await userLogin(server, user)
+ await server.login.getAccessToken(user)
+
+ const data = await server.stats.get()
- const res = await getStats(server.url)
- const data: ServerStats = res.body
expect(data.totalDailyActiveUsers).to.equal(2)
expect(data.totalWeeklyActiveUsers).to.equal(2)
expect(data.totalMonthlyActiveUsers).to.equal(2)
@@ -146,33 +128,33 @@ 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.stats.get()
+
expect(data.totalLocalDailyActiveVideoChannels).to.equal(1)
expect(data.totalLocalWeeklyActiveVideoChannels).to.equal(1)
expect(data.totalLocalMonthlyActiveVideoChannels).to.equal(1)
}
{
- 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.channels.create({ attributes })
+ channelId = created.id
+
+ const data = await server.stats.get()
- const res = await getStats(server.url)
- const data: ServerStats = res.body
expect(data.totalLocalDailyActiveVideoChannels).to.equal(1)
expect(data.totalLocalWeeklyActiveVideoChannels).to.equal(1)
expect(data.totalLocalMonthlyActiveVideoChannels).to.equal(1)
}
{
- await uploadVideo(server.url, server.accessToken, { fixture: 'video_short.webm', channelId })
+ await server.videos.upload({ attributes: { fixture: 'video_short.webm', channelId } })
+
+ const data = await server.stats.get()
- const res = await getStats(server.url)
- const data: ServerStats = res.body
expect(data.totalLocalDailyActiveVideoChannels).to.equal(2)
expect(data.totalLocalWeeklyActiveVideoChannels).to.equal(2)
expect(data.totalLocalMonthlyActiveVideoChannels).to.equal(2)
@@ -183,66 +165,62 @@ 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.stats.get()
+ expect(data.totalLocalPlaylists).to.equal(0)
}
{
- await createVideoPlaylist({
- url: server.url,
- token: server.accessToken,
- playlistAttrs: {
+ await server.playlists.create({
+ attributes: {
displayName: 'playlist for count',
privacy: VideoPlaylistPrivacy.PUBLIC,
videoChannelId: channelId
}
})
- const resStats = await getStats(server.url)
- const dataStats: ServerStats = resStats.body
- expect(dataStats.totalLocalPlaylists).to.equal(1)
+ const data = await server.stats.get()
+ expect(data.totalLocalPlaylists).to.equal(1)
}
})
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].config.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
+ }
}
}
})
- await uploadVideo(servers[0].url, servers[0].accessToken, { name: 'video', fixture: 'video_short.webm' })
+ await servers[0].videos.upload({ attributes: { name: 'video', fixture: 'video_short.webm' } })
await waitJobs(servers)
{
- const res = await getStats(servers[1].url)
- const data: ServerStats = res.body
+ const data = await servers[1].stats.get()
expect(data.totalLocalVideoFilesSize).to.equal(0)
}
{
- const res = await getStats(servers[0].url)
- const data: ServerStats = res.body
+ const data = await servers[0].stats.get()
expect(data.totalLocalVideoFilesSize).to.be.greaterThan(500000)
expect(data.totalLocalVideoFilesSize).to.be.lessThan(600000)
}
@@ -251,27 +229,27 @@ 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].config.updateCustomSubConfig({
+ newConfig: {
+ transcoding: {
+ enabled: false
+ }
}
})
- const res1 = await getStats(servers[1].url)
- const first = res1.body as ServerStats
+ const first = await servers[1].stats.get()
for (let i = 0; i < 10; i++) {
- await uploadVideo(servers[0].url, servers[0].accessToken, { name: 'video' })
+ await servers[0].videos.upload({ attributes: { name: 'video' } })
}
await waitJobs(servers)
await wait(6000)
- const res2 = await getStats(servers[1].url)
- const second: ServerStats = res2.body
-
+ const second = await servers[1].stats.get()
expect(second.totalActivityPubMessagesProcessed).to.be.greaterThan(first.totalActivityPubMessagesProcessed)
+
const apTypes: ActivityType[] = [
'Create', 'Update', 'Delete', 'Follow', 'Accept', 'Announce', 'Undo', 'Like', 'Reject', 'View', 'Dislike', 'Flag'
]
@@ -291,9 +269,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].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 4b86e0b90..f597ac60c 100644
--- a/server/tests/api/server/tracker.ts
+++ b/server/tests/api/server/tracker.ts
@@ -1,36 +1,23 @@
/* 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, 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 ])
{
- 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.videos.upload()
+ const video = await server.videos.get({ id: uuid })
goodMagnet = video.files[0].magnetUri
const parsed = magnetUtil.decode(goodMagnet)
@@ -61,8 +48,7 @@ describe('Test tracker', function () {
const errCb = () => done(new Error('Tracker is enabled'))
killallServers([ server ])
-
- reRunServer(server, { tracker: { enabled: false } })
+ .then(() => server.run({ tracker: { enabled: false } }))
.then(() => {
const webtorrent = new WebTorrent()
@@ -86,8 +72,7 @@ describe('Test tracker', function () {
this.timeout(20000)
killallServers([ server ])
-
- 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 60676a37b..77b99886d 100644
--- a/server/tests/api/users/user-subscriptions.ts
+++ b/server/tests/api/users/user-subscriptions.ts
@@ -1,42 +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 {
cleanupTests,
- createUser,
+ createMultipleServers,
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,
- listUserSubscriptions,
- listUserSubscriptionVideos,
- removeUserSubscription
-} from '../../../../shared/extra-utils/users/user-subscriptions'
+ PeerTubeServer,
+ setAccessTokensToServers,
+ SubscriptionsCommand,
+ waitJobs
+} from '@shared/extra-utils'
const expect = chai.expect
describe('Test users subscriptions', function () {
- let servers: ServerInfo[] = []
+ let servers: PeerTubeServer[] = []
const users: { accessToken: string }[] = []
let video3UUID: string
+ let command: SubscriptionsCommand
+
before(async function () {
this.timeout(120000)
- servers = await flushAndRunMultipleServers(3)
+ servers = await createMultipleServers(3)
// Get the access tokens
await setAccessTokensToServers(servers)
@@ -47,47 +35,50 @@ 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.users.create({ username: user.username, password: user.password })
- const accessToken = await userLogin(server, user)
+ const accessToken = await server.login.getAccessToken(user)
users.push({ accessToken })
const videoName1 = 'video 1-' + server.serverNumber
- await uploadVideo(server.url, accessToken, { name: videoName1 })
+ await server.videos.upload({ token: accessToken, attributes: { name: videoName1 } })
const videoName2 = 'video 2-' + server.serverNumber
- await uploadVideo(server.url, accessToken, { name: videoName2 })
+ await server.videos.upload({ token: accessToken, attributes: { name: videoName2 } })
}
}
await waitJobs(servers)
+
+ command = servers[0].subscriptions
})
it('Should display videos of server 2 on server 1', async function () {
- const res = await getVideosList(servers[0].url)
+ const { total } = await servers[0].videos.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 () {
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)
- const res = await uploadVideo(servers[2].url, users[2].accessToken, { name: 'video server 3 added after follow' })
- video3UUID = res.body.video.uuid
+ 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)
})
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].videos.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')
@@ -96,17 +87,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)
@@ -117,8 +108,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)
@@ -128,8 +118,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)
@@ -147,8 +136,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
@@ -158,45 +146,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)
@@ -210,22 +184,22 @@ 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].videos.upload({ attributes: { name: videoName } })
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)
@@ -236,10 +210,10 @@ describe('Test users subscriptions', function () {
}
{
- const res = await getVideosList(servers[0].url)
+ const { data, total } = await servers[0].videos.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')
@@ -250,17 +224,16 @@ 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].follows.follow({ hosts: [ servers[2].url ] })
await waitJobs(servers)
- const res = await getVideosList(servers[0].url)
-
- expect(res.body.total).to.equal(8)
+ 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' ]
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
}
})
@@ -268,14 +241,14 @@ 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].follows.unfollow({ target: servers[2] })
await waitJobs(servers)
- const res = await getVideosList(servers[0].url)
+ const { total, data } = await servers[0].videos.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,17 +257,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)
@@ -308,58 +281,55 @@ 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].videos.update({ id: video3UUID, attributes: { name: 'video server 3 added after follow updated' } })
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)
}
})
it('Should correctly display public videos on server 1', async function () {
- const res = await getVideosList(servers[0].url)
+ const { total, data } = await servers[0].videos.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')
@@ -369,15 +339,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)
@@ -387,10 +357,10 @@ describe('Test users subscriptions', function () {
}
{
- const res = await getVideosList(servers[0].url)
+ const { total, data } = await servers[0].videos.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 f60c66e4b..225145957 100644
--- a/server/tests/api/users/users-multiple-servers.ts
+++ b/server/tests/api/users/users-multiple-servers.ts
@@ -1,32 +1,25 @@
/* 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,
- createUser,
+ createMultipleServers,
doubleFollow,
- flushAndRunMultipleServers,
- getAccountVideos,
- getVideoChannelsList,
- removeUser,
- 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'
+ PeerTubeServer,
+ setAccessTokensToServers,
+ testImage,
+ waitJobs
+} from '@shared/extra-utils'
+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
@@ -36,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)
@@ -49,26 +42,21 @@ 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].videos.upload()
{
const user = {
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
- userAccessToken = await userLogin(servers[0], user)
+ const created = await servers[0].users.create(user)
+ userId = created.id
+ userAccessToken = await servers[0].login.getAccessToken(user)
}
{
- const resVideo = await uploadVideo(servers[0].url, userAccessToken, {})
- videoUUID = resVideo.body.video.uuid
+ const { uuid } = await servers[0].videos.upload({ token: userAccessToken })
+ videoUUID = uuid
}
await waitJobs(servers)
@@ -77,15 +65,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].users.updateMe({ displayName: 'my super display name' })
+ user = await servers[0].users.getMyInfo()
expect(user.account.displayName).to.equal('my super display name')
await waitJobs(servers)
@@ -94,14 +76,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].users.updateMe({ description: 'my super description updated' })
- const res = await getMyUserInformation(servers[0].url, servers[0].accessToken)
- user = res.body
+ 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')
@@ -113,15 +90,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].users.updateMyAvatar({ fixture })
+ user = await servers[0].users.getMyInfo()
userAvatarFilename = user.account.avatar.path
await testImage(servers[0].url, 'avatar2-resized', userAvatarFilename, '.png')
@@ -133,13 +104,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.accounts.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.accounts.get({ accountName: resList.name + '@' + resList.host })
if (!createdAt) createdAt = account.createdAt
@@ -161,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.videos.listByAccount({ handle: '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].videos.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'
- })
+ const { total, data } = await server.videos.listByAccount({ handle: 'user1@localhost:' + servers[0].port, 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)
+ 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)
}
})
@@ -193,32 +161,28 @@ 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.accounts.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)
- 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.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 removeUser(servers[0].url, userId, servers[0].accessToken)
+ await servers[0].users.remove({ userId })
await waitJobs(servers)
for (const server of servers) {
- const resAccounts = await getAccountsList(server.url, '-createdAt')
+ const body = await server.accounts.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)
- 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.channels.list()
+ const videoChannelDeleted = data.find(a => a.name === 'Main user1 channel' && a.host === 'localhost:' + servers[0].port)
expect(videoChannelDeleted).to.be.undefined
}
})
@@ -231,7 +195,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/users/users-verification.ts b/server/tests/api/users/users-verification.ts
index e0f2f2112..f54463359 100644
--- a/server/tests/api/users/users-verification.ts
+++ b/server/tests/api/users/users-verification.ts
@@ -1,30 +1,14 @@
/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */
-import * as chai from 'chai'
import 'mocha'
-import {
- cleanupTests,
- flushAndRunServer,
- getMyUserInformation,
- getUserInformation,
- login,
- registerUser,
- ServerInfo,
- updateCustomSubConfig,
- updateMyUser,
- userLogin,
- verifyEmail
-} from '../../../../shared/extra-utils'
-import { setAccessTokensToServers } from '../../../../shared/extra-utils/users/login'
-import { MockSmtpServer } from '../../../../shared/extra-utils/miscs/email'
-import { waitJobs } from '../../../../shared/extra-utils/server/jobs'
-import { User } from '../../../../shared/models/users'
-import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
+import * as chai from 'chai'
+import { cleanupTests, createSingleServer, MockSmtpServer, PeerTubeServer, setAccessTokensToServers, waitJobs } from '@shared/extra-utils'
+import { HttpStatusCode } from '@shared/models'
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
@@ -50,7 +34,7 @@ describe('Test users account verification', function () {
port
}
}
- server = await flushAndRunServer(1, overrideConfig)
+ server = await createSingleServer(1, overrideConfig)
await setAccessTokensToServers([ server ])
})
@@ -58,15 +42,17 @@ 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.config.updateCustomSubConfig({
+ newConfig: {
+ signup: {
+ enabled: true,
+ requiresEmailVerification: true,
+ limit: 10
+ }
}
})
- await registerUser(server.url, user1.username, user1.password)
+ await server.users.register(user1)
await waitJobs(server)
expectedEmailsLength++
@@ -85,23 +71,23 @@ 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.users.get({ userId })
+ expect(body.emailVerified).to.be.false
})
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.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 verifyEmail(server.url, userId, verificationString)
+ await server.users.verifyEmail({ userId, verificationString })
- const res = await login(server.url, server.client, user1)
- userAccessToken = res.body.access_token
+ const body = await server.login.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.users.get({ userId })
+ expect(user.emailVerified).to.be.true
})
it('Should be able to change the user email', async function () {
@@ -110,9 +96,8 @@ describe('Test users account verification', function () {
let updateVerificationString: string
{
- await updateMyUser({
- url: server.url,
- accessToken: userAccessToken,
+ await server.users.updateMe({
+ token: userAccessToken,
email: 'updated@example.com',
currentPassword: user1.password
})
@@ -128,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.users.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.users.verifyEmail({ userId, verificationString: updateVerificationString, isPendingEmail: true })
+ const me = await server.users.getMyInfo({ token: userAccessToken })
expect(me.email).to.equal('updated@example.com')
expect(me.pendingEmail).to.be.null
}
@@ -148,35 +129,39 @@ 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.config.updateCustomSubConfig({
+ newConfig: {
+ signup: {
+ enabled: true,
+ requiresEmailVerification: false,
+ limit: 10
+ }
}
})
- await registerUser(server.url, user2.username, user2.password)
+ await server.users.register(user2)
await waitJobs(server)
expect(emails).to.have.lengthOf(expectedEmailsLength)
- const accessToken = await userLogin(server, user2)
+ const accessToken = await server.login.getAccessToken(user2)
- const resMyUserInfo = await getMyUserInformation(server.url, accessToken)
- expect(resMyUserInfo.body.emailVerified).to.be.null
+ 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 updateCustomSubConfig(server.url, server.accessToken, {
- signup: {
- enabled: true,
- requiresEmailVerification: true,
- limit: 10
+ await server.config.updateCustomSubConfig({
+ newConfig: {
+ signup: {
+ enabled: true,
+ requiresEmailVerification: true,
+ limit: 10
+ }
}
})
- await userLogin(server, 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 87ba775f6..1419ae820 100644
--- a/server/tests/api/users/users.ts
+++ b/server/tests/api/users/users.ts
@@ -2,63 +2,24 @@
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 {
- addVideoCommentThread,
- blockUser,
cleanupTests,
- closeAllSequelize,
- createUser,
- deleteMe,
- flushAndRunServer,
- getAccountRatings,
- getAdminAbusesList,
- getBlacklistedVideosList,
- getCustomConfig,
- getMyUserInformation,
- getMyUserVideoQuotaUsed,
- getMyUserVideoRating,
- getUserInformation,
- getUsersList,
- getUsersListPaginationAndSort,
- getVideoChannel,
- getVideosList,
- installPlugin,
+ createSingleServer,
killallServers,
- login,
makePutBodyRequest,
- rateVideo,
- registerUserWithChannel,
- removeUser,
- removeVideo,
- reportAbuse,
- reRunServer,
- ServerInfo,
- setTokenField,
+ PeerTubeServer,
+ setAccessTokensToServers,
testImage,
- unblockUser,
- updateAbuse,
- updateCustomSubConfig,
- updateMyAvatar,
- updateMyUser,
- updateUser,
- 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, HttpStatusCode, OAuth2ErrorCode, UserAdminFlag, UserRole, Video, VideoPlaylistType } from '@shared/models'
const expect = chai.expect
describe('Test users', function () {
- let server: ServerInfo
- let accessToken: string
- let accessTokenUser: string
+ let server: PeerTubeServer
+ let token: string
+ let userToken: string
let videoId: number
let userId: number
const user = {
@@ -69,7 +30,7 @@ describe('Test users', function () {
before(async function () {
this.timeout(30000)
- server = await flushAndRunServer(1, {
+ server = await createSingleServer(1, {
rates_limit: {
login: {
max: 30
@@ -79,7 +40,7 @@ describe('Test users', function () {
await setAccessTokensToServers([ server ])
- await installPlugin({ url: server.url, accessToken: server.accessToken, npmName: 'peertube-theme-background-red' })
+ await server.plugins.install({ npmName: 'peertube-theme-background-red' })
})
describe('OAuth client', function () {
@@ -90,158 +51,156 @@ 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 res = await login(server.url, client, server.user, 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(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 client = { id: server.store.client.id, secret: 'coucou' }
+ const body = await server.login.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)
})
})
describe('Login', 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 user = { username: 'captain crochet', password: server.store.user.password }
+ const body = await server.login.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 user = { username: server.store.user.username, password: 'mew_three' }
+ const body = await server.login.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 () {
- accessToken = 'my_super_token'
+ token = 'my_super_token'
- const videoAttributes = {}
- await uploadVideo(server.url, accessToken, videoAttributes, HttpStatusCode.UNAUTHORIZED_401)
+ await server.videos.upload({ token, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 })
})
it('Should not be able to follow', async function () {
- accessToken = 'my_super_token'
- await follow(server.url, [ 'http://example.com' ], accessToken, HttpStatusCode.UNAUTHORIZED_401)
+ token = 'my_super_token'
+
+ await server.follows.follow({
+ hosts: [ 'http://example.com' ],
+ token,
+ expectedStatus: HttpStatusCode.UNAUTHORIZED_401
+ })
})
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.login.login({ expectedStatus: HttpStatusCode.OK_200 })
- accessToken = res.body.access_token
+ 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 login(server.url, server.client, user, 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 login(server.url, server.client, user2, 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 login(server.url, server.client, user3, 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 () {
- const videoAttributes = {}
- await uploadVideo(server.url, accessToken, videoAttributes)
- const res = await getVideosList(server.url)
- const video = res.body.data[0]
+ await server.videos.upload({ token })
+ const { data } = await server.videos.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.videos.upload({ token })
})
})
describe('Ratings', 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
+ 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 rateVideo(server.url, accessToken, videoId, 'like')
+ await server.videos.rate({ id: videoId, rating: 'like' })
- const res = await getAccountRatings(server.url, server.user.username, server.accessToken, null, HttpStatusCode.OK_200)
- const ratings = res.body
+ const body = await server.accounts.listRatings({ accountName: server.store.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.accounts.listRatings({ accountName: server.store.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.accounts.listRatings({ accountName: server.store.user.username, rating: 'dislike' })
+ expect(body.data.length).to.equal(0)
}
})
})
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.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 removeVideo(server.url, accessToken, videoId)
+ await server.videos.remove({ token, id: videoId })
})
})
describe('Logout', function () {
it('Should logout (revoke token)', async function () {
- await logout(server.url, server.accessToken)
+ await server.login.logout({ token: server.accessToken })
})
it('Should not be able to get the user information', async function () {
- await getMyUserInformation(server.url, server.accessToken, HttpStatusCode.UNAUTHORIZED_401)
+ await server.users.getMyInfo({ expectedStatus: HttpStatusCode.UNAUTHORIZED_401 })
})
it('Should not be able to upload a video', async function () {
- await uploadVideo(server.url, server.accessToken, { name: 'video' }, 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 () {
@@ -255,79 +214,70 @@ describe('Test users', function () {
path: path + videoId,
token: 'wrong token',
fields: data,
- statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401
+ expectedStatus: HttpStatusCode.UNAUTHORIZED_401
}
await makePutBodyRequest(options)
})
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.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 getMyUserInformation(server.url, server.accessToken)
+ await server.users.getMyInfo()
})
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.sql.setTokenField(server.accessToken, 'accessTokenExpiresAt', new Date().toISOString())
+ await server.sql.setTokenField(server.accessToken, 'refreshTokenExpiresAt', new Date().toISOString())
- killallServers([ server ])
- await reRunServer(server)
+ await killallServers([ server ])
+ await server.run()
- await getMyUserInformation(server.url, server.accessToken, 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 refreshToken(server, server.refreshToken, 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 setTokenField(server.internalServerNumber, server.accessToken, 'refreshTokenExpiresAt', futureDate)
+ await server.sql.setTokenField(server.accessToken, 'refreshTokenExpiresAt', futureDate)
- killallServers([ server ])
- await reRunServer(server)
+ await killallServers([ server ])
+ await server.run()
- const res = await refreshToken(server, 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 getMyUserInformation(server.url, server.accessToken)
+ await server.users.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.users.create({ ...user, videoQuota: 2 * 1024 * 1024, adminFlags: UserAdminFlag.BYPASS_VIDEO_AUTO_BLACKLIST })
})
it('Should be able to login with this user', async function () {
- accessTokenUser = await userLogin(server, user)
+ userToken = await server.login.getAccessToken(user)
})
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.users.getMyInfo({ token: userToken })
- const res2 = await getUserInformation(server.url, server.accessToken, userMe.id, true)
- const userGet: User = res2.body
+ const userGet = await server.users.get({ userId: userMe.id, withStats: true })
for (const user of [ userMe, userGet ]) {
expect(user.username).to.equal('user_1')
@@ -363,34 +313,28 @@ 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.videos.upload({ token: userToken, attributes })
})
it('Should have video quota updated', async function () {
- const res = await getMyUserVideoQuotaUsed(server.url, accessTokenUser)
- const data = res.body
+ const quota = await server.users.getMyQuotaUsed({ token: userToken })
+ expect(quota.videoQuotaUsed).to.equal(218910)
- expect(data.videoQuotaUsed).to.equal(218910)
-
- const resUsers = await getUsersList(server.url, server.accessToken)
-
- const users: User[] = resUsers.body.data
- const tmpUser = users.find(u => u.username === user.username)
+ 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 res = await getMyVideos(server.url, accessTokenUser, 0, 5)
- expect(res.body.total).to.equal(1)
+ const { total, data } = await server.videos.listMyVideos({ token: userToken })
+ expect(total).to.equal(1)
+ expect(data).to.have.lengthOf(1)
- const videos = res.body.data
- expect(videos).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
@@ -398,19 +342,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.videos.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.videos.listMyVideos({ token: userToken, sort: '-createdAt', search: 'toto' })
+ expect(total).to.equal(0)
+ expect(data).to.have.lengthOf(0)
}
})
@@ -418,28 +358,25 @@ 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.config.getCustomConfig()
config.transcoding.webtorrent.enabled = false
config.transcoding.hls.enabled = true
config.transcoding.enabled = true
- await updateCustomSubConfig(server.url, server.accessToken, config)
+ await server.config.updateCustomSubConfig({ newConfig: config })
}
{
- const videoAttributes = {
+ const attributes = {
name: 'super user video 2',
fixture: 'video_short.webm'
}
- await uploadVideo(server.url, accessTokenUser, videoAttributes)
+ await server.videos.upload({ token: userToken, attributes })
await waitJobs([ server ])
}
{
- const res = await getMyUserVideoQuotaUsed(server.url, accessTokenUser)
- const data = res.body
-
+ const data = await server.users.getMyQuotaUsed({ token: userToken })
expect(data.videoQuotaUsed).to.be.greaterThan(220000)
}
})
@@ -448,21 +385,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.users.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')
@@ -474,16 +408,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.users.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')
@@ -491,111 +421,90 @@ 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.users.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.users.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.users.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.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')
})
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.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')
+ 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.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')
+ expect(data[1].username).to.equal('user_1')
}
})
})
describe('Update my account', function () {
+
it('Should update my password', async function () {
- await updateMyUser({
- url: server.url,
- accessToken: accessTokenUser,
+ await server.users.updateMe({
+ token: userToken,
currentPassword: 'super password',
password: 'new password'
})
user.password = 'new password'
- await userLogin(server, user, HttpStatusCode.OK_200)
+ await server.login.login({ user })
})
it('Should be able to change the NSFW display attribute', async function () {
- await updateMyUser({
- url: server.url,
- accessToken: accessTokenUser,
+ await server.users.updateMe({
+ token: userToken,
nsfwPolicy: 'do_not_list'
})
- const res = await getMyUserInformation(server.url, accessTokenUser)
- const user = res.body
-
+ 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')
@@ -606,42 +515,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.users.updateMe({
+ token: userToken,
autoPlayVideo: false
})
- const res = await getMyUserInformation(server.url, accessTokenUser)
- const user = res.body
-
+ 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 updateMyUser({
- url: server.url,
- accessToken: accessTokenUser,
+ await server.users.updateMe({
+ token: userToken,
autoPlayNextVideo: true
})
- const res = await getMyUserInformation(server.url, accessTokenUser)
- const user = res.body
-
+ 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 updateMyUser({
- url: server.url,
- accessToken: accessTokenUser,
+ await server.users.updateMe({
+ token: userToken,
currentPassword: 'new password',
email: 'updated@example.com'
})
- const res = await getMyUserInformation(server.url, accessTokenUser)
- const user = res.body
-
+ 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')
@@ -654,15 +554,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.users.updateMyAvatar({ token: userToken, fixture })
+ const user = await server.users.getMyInfo({ token: userToken })
await testImage(server.url, 'avatar-resized', user.account.avatar.path, '.gif')
})
@@ -670,29 +564,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.users.updateMyAvatar({ token: userToken, fixture })
+ 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 updateMyUser({
- url: server.url,
- accessToken: accessTokenUser,
- displayName: 'new display name'
- })
-
- const res = await getMyUserInformation(server.url, accessTokenUser)
- const user = res.body
+ await server.users.updateMe({ token: userToken, displayName: 'new display name' })
+ 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')
@@ -703,15 +585,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.users.updateMe({ token: userToken, description: 'my super description updated' })
+ 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')
@@ -725,30 +601,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.users.updateMe({ token: userToken, theme })
- const res = await getMyUserInformation(server.url, accessTokenUser)
- const body: User = res.body
-
- expect(body.theme).to.equal(theme)
+ 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 updateMyUser({
- url: server.url,
- accessToken: accessTokenUser,
+ await server.users.updateMe({
+ token: userToken,
noInstanceConfigWarningModal: true,
noWelcomeModal: true
})
- const res = await getMyUserInformation(server.url, accessTokenUser)
- const user: User = res.body
-
+ const user = await server.users.getMyInfo({ token: userToken })
expect(user.noWelcomeModal).to.be.true
expect(user.noInstanceConfigWarningModal).to.be.true
})
@@ -756,10 +623,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.users.update({
userId,
- accessToken,
+ token,
email: 'updated2@example.com',
emailVerified: true,
videoQuota: 42,
@@ -768,8 +634,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.users.get({ token, userId })
expect(user.username).to.equal('user_1')
expect(user.email).to.equal('updated2@example.com')
@@ -783,57 +648,50 @@ describe('Test users', function () {
})
it('Should reset the auth plugin', async function () {
- await updateUser({ url: server.url, userId, accessToken, pluginAuth: null })
+ await server.users.update({ userId, token, pluginAuth: null })
- const res = await getUserInformation(server.url, accessToken, userId)
- const user = res.body as User
+ const user = await server.users.get({ token, 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.users.getMyQuotaUsed({ token: userToken, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 })
- accessTokenUser = await userLogin(server, user)
+ userToken = await server.login.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.users.update({ userId, token, password: 'password updated' })
- await getMyUserVideoQuotaUsed(server.url, accessTokenUser, HttpStatusCode.UNAUTHORIZED_401)
+ await server.users.getMyQuotaUsed({ token: userToken, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 })
- await userLogin(server, user, HttpStatusCode.BAD_REQUEST_400)
+ await server.login.login({ user, expectedStatus: HttpStatusCode.BAD_REQUEST_400 })
user.password = 'password updated'
- accessTokenUser = await userLogin(server, 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 getBlacklistedVideosList({ url: server.url, token: accessTokenUser })
+ await server.blacklist.list({ token: userToken })
})
})
describe('Remove a user', function () {
it('Should be able to remove this user', async function () {
- await removeUser(server.url, userId, accessToken)
+ await server.users.remove({ userId, token })
})
it('Should not be able to login with this user', async function () {
- await userLogin(server, user, 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 res = await getVideosList(server.url)
+ const { data, total } = await server.videos.list()
+ expect(total).to.equal(1)
- expect(res.body.total).to.equal(1)
-
- const video = res.body.data[0]
+ const video = data[0]
expect(video.account.name).to.equal('root')
})
})
@@ -845,7 +703,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.users.register({ ...user, channel })
})
it('Should be able to login with this registered user', async function () {
@@ -854,40 +712,36 @@ describe('Test users', function () {
password: 'my super password'
}
- user15AccessToken = await userLogin(server, user15)
+ user15AccessToken = await server.login.getAccessToken(user15)
})
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.users.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.users.getMyInfo({ token: user15AccessToken })
expect(user.videoQuota).to.equal(5 * 1024 * 1024)
})
it('Should have created the channel', async function () {
- const res = await getVideoChannel(server.url, 'my_user_15_channel')
+ const { displayName } = await server.channels.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 () {
{
- 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.users.list()
+ expect(data.find(u => u.username === 'user_15')).to.not.be.undefined
}
- await deleteMe(server.url, user15AccessToken)
+ await server.users.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.users.list()
+ expect(data.find(u => u.username === 'user_15')).to.be.undefined
}
})
})
@@ -901,49 +755,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.users.create({ ...user16 })
+ user16Id = user.id
- user16AccessToken = await userLogin(server, user16)
+ user16AccessToken = await server.login.getAccessToken(user16)
- await getMyUserInformation(server.url, user16AccessToken, HttpStatusCode.OK_200)
- await blockUser(server.url, user16Id, server.accessToken)
+ await server.users.getMyInfo({ token: user16AccessToken, expectedStatus: HttpStatusCode.OK_200 })
+ await server.users.banUser({ userId: user16Id })
- await getMyUserInformation(server.url, user16AccessToken, HttpStatusCode.UNAUTHORIZED_401)
- await userLogin(server, user16, 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 res = await getUsersListPaginationAndSort(server.url, server.accessToken, 0, 2, 'createdAt', undefined, true)
- const users = res.body.data as User[]
+ 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)
- 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[]
+ 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)
- expect(res.body.total).to.equal(1)
- expect(users.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)
- user16AccessToken = await userLogin(server, user16)
- await getMyUserInformation(server.url, user16AccessToken, 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 })
})
})
@@ -956,19 +801,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.users.create({ ...user17 })
- user17Id = resUser.body.user.id
- user17AccessToken = await userLogin(server, user17)
-
- const res = await getUserInformation(server.url, server.accessToken, user17Id, true)
- const user: User = res.body
+ user17Id = created.id
+ user17AccessToken = await server.login.getAccessToken(user17)
+ 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)
@@ -977,54 +815,43 @@ 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.videos.upload({ token: user17AccessToken, attributes })
- const res2 = await getUserInformation(server.url, server.accessToken, user17Id, true)
- const user: User = res2.body
+ const { data } = await server.videos.list()
+ videoId = data.find(video => video.name === attributes.name).id
+ 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 addVideoCommentThread(server.url, user17AccessToken, videoId, text)
-
- const res = await getUserInformation(server.url, server.accessToken, user17Id, true)
- const user: User = res.body
+ await server.comments.createThread({ token: user17AccessToken, videoId, text })
+ 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 reportAbuse({ url: server.url, token: user17AccessToken, videoId, reason })
+ await server.abuses.report({ token: user17AccessToken, videoId, reason })
- const res1 = await getAdminAbusesList({ url: server.url, token: server.accessToken })
- const abuseId = res1.body.data[0].id
-
- const res2 = await getUserInformation(server.url, server.accessToken, user17Id, true)
- const user2: User = res2.body
+ const body1 = await server.abuses.getAdminList()
+ const abuseId = body1.data[0].id
+ 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
- const body: AbuseUpdate = { state: AbuseState.ACCEPTED }
- await updateAbuse(server.url, server.accessToken, abuseId, body)
-
- const res3 = await getUserInformation(server.url, server.accessToken, user17Id, true)
- const user3: User = res3.body
+ await server.abuses.update({ abuseId, body: { state: AbuseState.ACCEPTED } })
+ const user3 = await server.users.get({ userId: user17Id, withStats: true })
expect(user3.abusesAcceptedCount).to.equal(1) // number of reports created accepted
})
})
after(async function () {
- await closeAllSequelize([ server ])
await cleanupTests([ server ])
})
})
diff --git a/server/tests/api/videos/audio-only.ts b/server/tests/api/videos/audio-only.ts
index 7ddbd5cd9..15c3ae6d6 100644
--- a/server/tests/api/videos/audio-only.ts
+++ b/server/tests/api/videos/audio-only.ts
@@ -4,23 +4,12 @@ import 'mocha'
import * as chai from 'chai'
import { join } from 'path'
import { getAudioStream, getVideoStreamSize } from '@server/helpers/ffprobe-utils'
-import {
- buildServerDirectory,
- cleanupTests,
- doubleFollow,
- flushAndRunMultipleServers,
- getVideo,
- ServerInfo,
- setAccessTokensToServers,
- uploadVideo,
- waitJobs
-} from '../../../../shared/extra-utils'
-import { VideoDetails } from '../../../../shared/models/videos'
+import { cleanupTests, createMultipleServers, doubleFollow, 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 () {
@@ -47,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)
@@ -59,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].videos.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.videos.get({ id: videoUUID })
expect(video.streamingPlaylists).to.have.lengthOf(1)
for (const files of [ video.files, video.streamingPlaylists[0].files ]) {
@@ -81,8 +68,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].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 a8c8a889b..d916abb09 100644
--- a/server/tests/api/videos/multiple-servers.ts
+++ b/server/tests/api/videos/multiple-servers.ts
@@ -3,49 +3,28 @@
import 'mocha'
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,
cleanupTests,
completeVideoCheck,
- createUser,
+ createMultipleServers,
dateIsValid,
doubleFollow,
- flushAndRunMultipleServers,
- getLocalVideos,
- getVideo,
- getVideoChannelsList,
- getVideosList,
- rateVideo,
- removeVideo,
- ServerInfo,
+ PeerTubeServer,
setAccessTokensToServers,
testImage,
- updateVideo,
- uploadVideo,
- 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 { HttpStatusCode, 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
@@ -53,7 +32,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)
@@ -64,9 +43,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].channels.create({ attributes: videoChannel })
+ const { data } = await servers[0].channels.list({ start: 0, count: 1 })
+ videoChannelId = data[0].id
}
// Server 1 and server 2 follow each other
@@ -79,10 +58,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.videos.list()
+ expect(data).to.be.an('array')
+ expect(data.length).to.equal(0)
}
})
@@ -90,7 +68,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,
@@ -103,7 +81,7 @@ describe('Test multiple servers', function () {
channelId: videoChannelId,
fixture: 'video_short1.webm'
}
- await uploadVideo(servers[0].url, servers[0].accessToken, videoAttributes)
+ await servers[0].videos.upload({ attributes })
await waitJobs(servers)
@@ -146,14 +124,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.videos.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
}
})
@@ -164,10 +141,10 @@ 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 })
- const userAccessToken = await userLogin(servers[1], user)
+ await servers[1].users.create({ username: user.username, password: user.password })
+ const userAccessToken = await servers[1].login.getAccessToken(user)
- const videoAttributes = {
+ const attributes = {
name: 'my super name for server 2',
category: 4,
licence: 3,
@@ -180,7 +157,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].videos.upload({ token: userAccessToken, attributes, mode: 'resumable' })
// Transcoding
await waitJobs(servers)
@@ -235,65 +212,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.videos.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].videos.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].videos.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.videos.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 = {
@@ -328,7 +307,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',
@@ -362,38 +341,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].videos.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].videos.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].videos.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')
})
})
@@ -401,15 +380,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 { data } = await servers[2].videos.list()
- const video = res.body.data[0]
- toRemove.push(res.body.data[2])
- toRemove.push(res.body.data[3])
-
- 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].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)
@@ -419,11 +396,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].videos.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].videos.get({ id: video.id })
const torrent = await webtorrentAdd(videoDetails.files[0].magnetUri, true)
expect(torrent.files).to.be.an('array')
@@ -434,11 +410,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].videos.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].videos.get({ id: video.id })
const torrent = await webtorrentAdd(videoDetails.files[0].magnetUri, true)
expect(torrent.files).to.be.an('array')
@@ -449,11 +424,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].videos.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].videos.get({ id: video.id })
const torrent = await webtorrentAdd(videoDetails.files[0].magnetUri)
expect(torrent.files).to.be.an('array')
@@ -464,11 +438,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].videos.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].videos.get({ id: video.id })
const file = videoDetails.files.find(f => f.resolution.id === 360)
expect(file).not.to.be.undefined
@@ -487,30 +460,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].videos.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].videos.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].videos.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].videos.view({ id: localVideosServer3[0] })
await wait(1000)
- await viewVideo(servers[2].url, localVideosServer3[0])
- await viewVideo(servers[2].url, localVideosServer3[1])
+ await servers[2].videos.view({ id: localVideosServer3[0] })
+ await servers[2].videos.view({ id: localVideosServer3[1] })
await wait(1000)
- await viewVideo(servers[2].url, localVideosServer3[0])
- await viewVideo(servers[2].url, localVideosServer3[0])
+ await servers[2].videos.view({ id: localVideosServer3[0] })
+ await servers[2].videos.view({ id: localVideosServer3[0] })
await waitJobs(servers)
@@ -520,11 +499,10 @@ describe('Test multiple servers', function () {
await waitJobs(servers)
for (const server of servers) {
- const res = await getVideosList(server.url)
+ const { data } = await server.videos.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)
@@ -535,16 +513,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].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)
@@ -558,18 +536,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.videos.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)
}
}
@@ -578,35 +554,34 @@ 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].videos.rate({ id: remoteVideosServer1[0], rating: 'like' })
await wait(500)
- await rateVideo(servers[0].url, servers[0].accessToken, remoteVideosServer1[0], 'dislike')
+ await servers[0].videos.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].videos.rate({ id: remoteVideosServer1[0], rating: 'like' })
+ await servers[2].videos.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].videos.rate({ id: localVideosServer3[1], rating: 'dislike' })
+ await servers[2].videos.rate({ id: remoteVideosServer3[1], rating: 'dislike' })
await wait(500)
- await rateVideo(servers[2].url, servers[2].accessToken, remoteVideosServer3[0], 'like')
+ await servers[2].videos.rate({ id: remoteVideosServer3[0], rating: 'like' })
await waitJobs(servers)
await wait(5000)
+ await waitJobs(servers)
let baseVideos = null
for (const server of servers) {
- const res = await getVideosList(server.url)
-
- const videos = res.body.data
+ const { data } = await server.videos.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)
}
@@ -632,7 +607,7 @@ describe('Test multiple servers', function () {
previewfile: 'preview.jpg'
}
- await updateVideo(servers[2].url, servers[2].accessToken, toRemove[0].id, attributes)
+ await servers[2].videos.update({ id: toRemove[0].id, attributes })
await waitJobs(servers)
})
@@ -641,10 +616,9 @@ describe('Test multiple servers', function () {
this.timeout(10000)
for (const server of servers) {
- const res = await getVideosList(server.url)
+ const { data } = await server.videos.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
@@ -683,49 +657,46 @@ 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].videos.remove({ id: toRemove[0].id })
+ await servers[2].videos.remove({ id: toRemove[1].id })
await waitJobs(servers)
})
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)
}
})
it('Should have videos 1 and 3 on each server', async function () {
for (const server of servers) {
- const res = await getVideosList(server.url)
+ const { data } = await server.videos.list()
- 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)
+ 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 = videos.find(video => video.name === 'my super name for server 1').uuid
+ 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.videos.get({ id: videoUUID })
if (baseVideo === null) {
baseVideo = video
@@ -748,8 +719,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.videos.get({ id: videoUUID })
await testImage(server.url, 'video_short1-preview.webm', video.previewPath)
}
@@ -764,36 +734,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].comments.createThread({ videoId: videoUUID, text })
}
{
const text = 'my super second comment'
- await addVideoCommentThread(servers[2].url, servers[2].accessToken, videoUUID, text)
+ await servers[2].comments.createThread({ videoId: videoUUID, text })
}
await waitJobs(servers)
{
- const threadId = await findCommentId(servers[1].url, videoUUID, '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 addVideoCommentReply(servers[1].url, servers[1].accessToken, videoUUID, threadId, text)
+ await servers[1].comments.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].comments.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].comments.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].comments.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].comments.addReply({ videoId: videoUUID, toCommentId: childCommentId, text: text2 })
}
await waitJobs(servers)
@@ -801,14 +771,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.comments.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')
@@ -819,7 +789,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')
@@ -833,12 +803,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.comments.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.comments.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)
@@ -867,19 +836,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].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 res1 = await getVideoCommentThreads(server.url, videoUUID, 0, 5)
- const threadId = res1.body.data.find(c => c.text === 'my super first comment').id
+ const { data } = await server.comments.listThreads({ videoId: videoUUID })
+ const threadId = data.find(c => c.text === 'my super first comment').id
- const res2 = await getVideoThreadComments(server.url, videoUUID, threadId)
-
- const tree: VideoCommentThreadTree = res2.body
+ const tree = await server.comments.getThread({ videoId: videoUUID, threadId })
expect(tree.comment.text).equal('my super first comment')
const firstChild = tree.children[0]
@@ -900,23 +867,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].comments.listThreads({ videoId: videoUUID })
+ const commentId = data.find(c => c.text === 'my super first comment').id
+ 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 res = await getVideoCommentThreads(server.url, videoUUID, 0, 5)
+ const body = await server.comments.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')
@@ -927,7 +894,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
@@ -945,22 +912,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].comments.listThreads({ videoId: videoUUID })
+ const commentId = data.find(c => c.text === 'my super second comment').id
+ 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 res = await getVideoCommentThreads(server.url, videoUUID, 0, 5)
+ const body = await server.comments.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
@@ -970,7 +937,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
@@ -989,17 +956,17 @@ describe('Test multiple servers', function () {
downloadEnabled: false
}
- await updateVideo(servers[0].url, servers[0].accessToken, videoUUID, attributes)
+ await servers[0].videos.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.videos.get({ id: videoUUID })
+ expect(video.commentsEnabled).to.be.false
+ expect(video.downloadEnabled).to.be.false
const text = 'my super forbidden comment'
- await addVideoCommentThread(server.url, server.accessToken, videoUUID, text, HttpStatusCode.CONFLICT_409)
+ await server.comments.createThread({ videoId: videoUUID, text, expectedStatus: HttpStatusCode.CONFLICT_409 })
}
})
})
@@ -1024,8 +991,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.videos.list()
+ const video = data.find(v => v.name === 'minimum parameters')
const isLocal = server.url === 'http://localhost:' + servers[1].port
const checkAttributes = {
@@ -1072,7 +1039,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 4fc3317df..13e47c85e 100644
--- a/server/tests/api/videos/resumable-upload.ts
+++ b/server/tests/api/videos/resumable-upload.ts
@@ -4,22 +4,15 @@ 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 {
buildAbsoluteFixturePath,
- buildServerDirectory,
cleanupTests,
- flushAndRunServer,
- getMyUserInformation,
- prepareResumableUpload,
- sendDebugCommand,
- sendResumableChunks,
- ServerInfo,
+ createSingleServer,
+ PeerTubeServer,
setAccessTokensToServers,
- setDefaultVideoChannel,
- updateUser
+ setDefaultVideoChannel
} from '@shared/extra-utils'
-import { MyUser, VideoPrivacy } from '@shared/models'
+import { HttpStatusCode, VideoPrivacy } from '@shared/models'
const expect = chai.expect
@@ -27,7 +20,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) {
@@ -42,14 +35,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 prepareResumableUpload({ url: server.url, token: server.accessToken, attributes, size, mimetype })
+ const res = await server.videos.prepareResumableUpload({ attributes, size, mimetype })
return res.header['location'].split('?')[1]
}
@@ -67,15 +60,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.videos.sendResumableChunks({
pathUploadId,
videoFilePath: absoluteFilePath,
size,
contentLength,
contentRangeBuilder,
- specialStatus: expectedStatus
+ expectedStatus
})
}
@@ -83,7 +74,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.servers.buildDirectory(subPath)
const exists = await pathExists(filePath)
if (expectedSize === null) {
@@ -98,7 +89,7 @@ describe('Test resumable upload', function () {
async function countResumableUploads () {
const subPath = join('tmp', 'resumable-uploads')
- const filePath = buildServerDirectory(server, subPath)
+ const filePath = server.servers.buildDirectory(subPath)
const files = await readdir(filePath)
return files.length
@@ -107,19 +98,14 @@ 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 ])
- const res = await getMyUserInformation(server.url, server.accessToken)
- rootId = (res.body as MyUser).id
+ const body = await server.users.getMyInfo()
+ rootId = body.id
- await updateUser({
- url: server.url,
- userId: rootId,
- accessToken: server.accessToken,
- videoQuota: 10_000_000
- })
+ await server.users.update({ userId: rootId, videoQuota: 10_000_000 })
})
describe('Directory cleaning', function () {
@@ -138,13 +124,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.debug.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.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 1058a1e9c..c0535be09 100644
--- a/server/tests/api/videos/single-server.ts
+++ b/server/tests/api/videos/single-server.ts
@@ -2,43 +2,26 @@
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,
+ createSingleServer,
+ PeerTubeServer,
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
describe('Test a single server', function () {
function runSuite (mode: 'legacy' | 'resumable') {
- let server: ServerInfo = null
- let videoId = -1
- let videoId2 = -1
+ let server: PeerTubeServer = null
+ let videoId: number | string
+ let videoId2: string
let videoUUID = ''
let videosListBase: any[] = null
@@ -111,134 +94,122 @@ describe('Test a single server', function () {
before(async function () {
this.timeout(30000)
- server = await flushAndRunServer(1)
+ server = await createSingleServer(1)
await setAccessTokensToServers([ server ])
})
it('Should list video categories', async function () {
- const res = await getVideoCategories(server.url)
-
- const categories = res.body
+ 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 res = await getVideoLicences(server.url)
-
- const licences = res.body
+ 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 res = await getVideoLanguages(server.url)
-
- const languages = res.body
+ 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 res = await getVideoPrivacies(server.url)
-
- const privacies = res.body
+ 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 res = await getVideosList(server.url)
+ const { data, total } = await server.videos.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.videos.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.videos.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.videos.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.videos.view({ id: videoId })
+ await server.videos.view({ id: videoId })
+ await server.videos.view({ id: videoId })
await wait(1500)
- await viewVideo(server.url, videoId)
- await viewVideo(server.url, videoId)
+ await server.videos.view({ id: videoId })
+ await server.videos.view({ id: videoId })
await wait(1500)
- await viewVideo(server.url, videoId)
- await viewVideo(server.url, videoId)
+ await server.videos.view({ id: videoId })
+ await server.videos.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.videos.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.videos.remove({ id: videoId })
- await checkVideoFilesWereRemoved(videoUUID, 1)
+ await checkVideoFilesWereRemoved(videoUUID, server)
})
it('Should not have videos', async function () {
- const res = await getVideosList(server.url)
+ const { total, data } = await server.videos.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.videos.upload({ attributes, mode })
}
})
it('Should have the correct durations', async function () {
- const res = await getVideosList(server.url)
+ const { total, data } = await server.videos.list()
- expect(res.body.total).to.equal(6)
- const videos = res.body.data
- expect(videos).to.be.an('array')
- expect(videos).to.have.lengthOf(6)
+ expect(total).to.equal(6)
+ expect(data).to.be.an('array')
+ expect(data).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.videos.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.videos.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.videos.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.videos.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.videos.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.videos.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.videos.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.videos.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.videos.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.videos.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.videos.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.videos.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.videos.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.videos.update({ id: videoId, attributes })
- const res = await getVideo(server.url, videoId)
- const video = res.body
+ const video = await server.videos.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.videos.update({ id: videoId, attributes })
- const res = await getVideo(server.url, videoId)
- const video = res.body
+ const video = await server.videos.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.videos.rate({ id: videoId, rating: 'like' })
- const res = await getVideo(server.url, videoId)
- const video = res.body
+ 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 rateVideo(server.url, server.accessToken, videoId, 'dislike')
+ await server.videos.rate({ id: videoId, rating: 'dislike' })
- const res = await getVideo(server.url, videoId)
- const video = res.body
+ const video = await server.videos.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.videos.update({ id: videoId, attributes })
- const res = await getVideosListSort(server.url, '-originallyPublishedAt')
- const names = res.body.data.map(v => v.name)
+ const { data } = await server.videos.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.videos.update({ id: videoId2, attributes })
- const res = await getVideosListSort(server.url, '-originallyPublishedAt')
- const names = res.body.data.map(v => v.name)
+ const { data } = await server.videos.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 14ecedfa6..4c8e28adf 100644
--- a/server/tests/api/videos/video-captions.ts
+++ b/server/tests/api/videos/video-captions.ts
@@ -1,72 +1,61 @@
/* 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,
+ createMultipleServers,
doubleFollow,
- flushAndRunMultipleServers,
- removeVideo,
- 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'
+ PeerTubeServer,
+ setAccessTokensToServers,
+ testCaptionFile,
+ wait,
+ waitJobs
+} from '@shared/extra-utils'
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])
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].videos.upload({ attributes: { name: 'my video name' } })
+ videoUUID = uuid
await waitJobs(servers)
})
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.captions.list({ 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].captions.add({
language: 'ar',
videoId: videoUUID,
fixture: 'subtitle-good1.vtt'
})
- await createVideoCaption({
- url: servers[0].url,
- accessToken: servers[0].accessToken,
+ await servers[0].captions.add({
language: 'zh',
videoId: videoUUID,
fixture: 'subtitle-good2.vtt',
@@ -78,17 +67,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.captions.list({ 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 +88,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].captions.add({
language: 'ar',
videoId: videoUUID,
fixture: 'subtitle-good2.vtt'
@@ -112,11 +99,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.captions.list({ 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 +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 createVideoCaption({
- url: servers[0].url,
- accessToken: servers[0].accessToken,
+ await servers[0].captions.add({
language: 'ar',
videoId: videoUUID,
fixture: 'subtitle-good.srt'
@@ -143,11 +128,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.captions.list({ 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 +157,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].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 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.captions.list({ 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')
@@ -193,9 +178,9 @@ 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].videos.remove({ id: videoUUID })
- await checkVideoFilesWereRemoved(videoUUID, 1)
+ await checkVideoFilesWereRemoved(videoUUID, servers[0])
})
after(async function () {
diff --git a/server/tests/api/videos/video-change-ownership.ts b/server/tests/api/videos/video-change-ownership.ts
index a3384851b..6ae6d3004 100644
--- a/server/tests/api/videos/video-change-ownership.ts
+++ b/server/tests/api/videos/video-change-ownership.ts
@@ -2,234 +2,212 @@
import 'mocha'
import * as chai from 'chai'
-import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
import {
- acceptChangeOwnership,
- changeVideoOwnership,
+ ChangeOwnershipCommand,
cleanupTests,
- createLive,
- createUser,
+ createMultipleServers,
+ createSingleServer,
doubleFollow,
- flushAndRunMultipleServers,
- flushAndRunServer,
- getMyUserInformation,
- getVideo,
- getVideoChangeOwnershipList,
- getVideosList,
- refuseChangeOwnership,
- ServerInfo,
+ PeerTubeServer,
setAccessTokensToServers,
setDefaultVideoChannel,
- updateCustomSubConfig,
- uploadVideo,
- userLogin
-} 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'
+ waitJobs
+} from '@shared/extra-utils'
+import { HttpStatusCode, VideoPrivacy } from '@shared/models'
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'
- }
+ let servers: PeerTubeServer[] = []
- let firstUserAccessToken = ''
+ const firstUser = 'first'
+ const secondUser = 'second'
+
+ 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)
- servers = await flushAndRunMultipleServers(2)
+ servers = await createMultipleServers(2)
await setAccessTokensToServers(servers)
await setDefaultVideoChannel(servers)
- await updateCustomSubConfig(servers[0].url, servers[0].accessToken, {
- transcoding: {
- enabled: false
- },
- live: {
- enabled: true
+ await servers[0].config.updateCustomSubConfig({
+ newConfig: {
+ transcoding: {
+ enabled: false
+ },
+ live: {
+ enabled: true
+ }
}
})
- 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
- })
-
- firstUserAccessToken = await userLogin(servers[0], firstUser)
- secondUserAccessToken = await userLogin(servers[0], secondUser)
+ firstUserToken = await servers[0].users.generateUserAndToken(firstUser)
+ secondUserToken = await servers[0].users.generateUserAndToken(secondUser)
{
- const res = await getMyUserInformation(servers[0].url, firstUserAccessToken)
- const firstUserInformation: User = res.body
- firstUserChannelId = firstUserInformation.videoChannels[0].id
+ const { videoChannels } = await servers[0].users.getMyInfo({ token: firstUserToken })
+ firstUserChannelId = videoChannels[0].id
}
{
- const res = await getMyUserInformation(servers[0].url, secondUserAccessToken)
- const secondUserInformation: User = res.body
- secondUserChannelId = secondUserInformation.videoChannels[0].id
+ const { videoChannels } = await servers[0].users.getMyInfo({ token: secondUserToken })
+ secondUserChannelId = videoChannels[0].id
}
{
- const videoAttributes = {
+ const attributes = {
name: 'my super name',
description: 'my super description'
}
- const res = await uploadVideo(servers[0].url, firstUserAccessToken, videoAttributes)
+ const { id } = await servers[0].videos.upload({ token: firstUserToken, attributes })
- const resVideo = await getVideo(servers[0].url, res.body.video.id)
- servers[0].video = resVideo.body
+ servers[0].store.video = await servers[0].videos.get({ id })
}
{
const attributes = { name: 'live', channelId: firstUserChannelId, privacy: VideoPrivacy.PUBLIC }
- const res = await createLive(servers[0].url, firstUserAccessToken, attributes)
+ const video = await servers[0].live.create({ token: firstUserToken, fields: attributes })
- liveId = res.body.video.id
+ liveId = video.id
}
+ command = servers[0].changeOwnership
+
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].store.video.id, username: secondUser })
})
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].store.video.id, username: secondUser })
})
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].store.video.id, username: secondUser })
})
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)
})
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.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')
@@ -240,27 +218,25 @@ 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 })
- 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)
for (const server of servers) {
- const res = await getVideo(server.url, servers[0].video.uuid)
-
- const video: VideoDetails = res.body
+ 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')
@@ -274,99 +250,79 @@ 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'
- }
- let firstUserAccessToken = ''
- let secondUserAccessToken = ''
- let lastRequestChangeOwnershipId = ''
+ let server: PeerTubeServer
+ const firstUser = 'first'
+ const secondUser = 'second'
+
+ let firstUserToken = ''
+ let secondUserToken = ''
+ let lastRequestId: number
before(async function () {
this.timeout(50000)
// Run one server
- server = await flushAndRunServer(1)
+ server = await createSingleServer(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.users.create({ username: secondUser, videoQuota: 10 })
- firstUserAccessToken = await userLogin(server, firstUser)
- secondUserAccessToken = await userLogin(server, secondUser)
+ firstUserToken = await server.users.generateUserAndToken(firstUser)
+ secondUserToken = await server.login.getAccessToken(secondUser)
// Upload some videos on the server
- const video1Attributes = {
+ const attributes = {
name: 'my super name',
description: 'my super description'
}
- await uploadVideo(server.url, firstUserAccessToken, video1Attributes)
+ await server.videos.upload({ token: firstUserToken, attributes })
await waitJobs(server)
- const res = await getVideosList(server.url)
- const videos = res.body.data
+ const { data } = await server.videos.list()
+ expect(data.length).to.equal(1)
- expect(videos.length).to.equal(1)
-
- server.video = videos.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 changeVideoOwnership(server.url, firstUserAccessToken, server.video.id, secondUser.username)
+ 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 resFirstUser = await getVideoChangeOwnershipList(server.url, firstUserAccessToken)
+ {
+ const body = await server.changeOwnership.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.changeOwnership.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 secondUserInformation: User = secondUserInformationResponse.body
- const channelId = secondUserInformation.videoChannels[0].id
+ const { videoChannels } = await server.users.getMyInfo({ token: secondUserToken })
+ const channelId = videoChannels[0].id
- await acceptChangeOwnership(
- server.url,
- secondUserAccessToken,
- lastRequestChangeOwnershipId,
+ await server.changeOwnership.accept({
+ token: secondUserToken,
+ ownershipId: lastRequestId,
channelId,
- HttpStatusCode.PAYLOAD_TOO_LARGE_413
- )
+ expectedStatus: HttpStatusCode.PAYLOAD_TOO_LARGE_413
+ })
})
after(async function () {
diff --git a/server/tests/api/videos/video-channels.ts b/server/tests/api/videos/video-channels.ts
index 865098777..c25754eb6 100644
--- a/server/tests/api/videos/video-channels.ts
+++ b/server/tests/api/videos/video-channels.ts
@@ -6,48 +6,28 @@ import { basename } from 'path'
import { ACTOR_IMAGES_SIZE } from '@server/initializers/constants'
import {
cleanupTests,
- createUser,
- deleteVideoChannelImage,
+ createMultipleServers,
doubleFollow,
- flushAndRunMultipleServers,
- getActorImage,
- getVideo,
- getVideoChannel,
- getVideoChannelVideos,
+ PeerTubeServer,
+ setAccessTokensToServers,
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 { waitJobs } from '../../../../shared/extra-utils/server/jobs'
-import { User, Video, VideoChannel, VideoDetails } from '../../../../shared/index'
+ wait,
+ waitJobs
+} from '@shared/extra-utils'
+import { User, VideoChannel } from '@shared/models'
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)
+async function findChannel (server: PeerTubeServer, channelId: number) {
+ const body = await server.channels.list({ sort: '-name' })
- return videoChannel as VideoChannel
+ 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
@@ -60,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)
@@ -69,11 +49,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].channels.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,23 +66,22 @@ 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].channels.create({ attributes: videoChannel })
+ secondVideoChannelId = created.id
}
// 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].videos.upload({ attributes })
+ videoUUID = uuid
}
await waitJobs(servers)
})
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].users.getMyInfo()
expect(userInfo.videoChannels).to.be.an('array')
expect(userInfo.videoChannels).to.have.lengthOf(2)
@@ -120,16 +99,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].channels.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 +118,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].channels.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].channels.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].channels.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].channels.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].channels.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,30 +192,29 @@ describe('Test video channels', function () {
support: 'support updated'
}
- await updateVideoChannel(servers[0].url, servers[0].accessToken, 'second_video_channel', 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 res = await getVideoChannelsList(server.url, 0, 1, '-name')
+ const body = await server.channels.list({ start: 0, 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('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')
+ 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')
}
})
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.videos.get({ id: videoUUID })
expect(video.support).to.equal('video support field')
}
})
@@ -261,14 +227,12 @@ describe('Test video channels', function () {
bulkVideosSupportUpdate: true
}
- await updateVideoChannel(servers[0].url, servers[0].accessToken, 'second_video_channel', videoChannelAttributes)
+ await servers[0].channels.update({ channelName: 'second_video_channel', attributes: videoChannelAttributes })
await waitJobs(servers)
for (const server of servers) {
- const res = await getVideo(server.url, videoUUID)
- const video: VideoDetails = res.body
-
+ const video = await server.videos.get({ id: videoUUID })
expect(video.support).to.equal(videoChannelAttributes.support)
}
})
@@ -278,10 +242,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].channels.updateImage({
+ channelName: 'second_video_channel',
fixture,
type: 'avatar'
})
@@ -295,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 getActorImage(server.internalServerNumber, 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)
}
@@ -306,10 +268,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].channels.updateImage({
+ channelName: 'second_video_channel',
fixture,
type: 'banner'
})
@@ -317,14 +277,13 @@ 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.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 getActorImage(server.internalServerNumber, 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)
}
@@ -333,12 +292,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].channels.deleteImage({ channelName: 'second_video_channel', type: 'avatar' })
await waitJobs(servers)
@@ -353,12 +307,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].channels.deleteImage({ channelName: 'second_video_channel', type: 'banner' })
await waitJobs(servers)
@@ -375,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.videos.listByChannel({ handle: 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].videos.update({ id: videoUUID, attributes: { channelId: servers[0].store.channel.id } })
await waitJobs(servers)
})
@@ -395,47 +345,50 @@ 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 secondChannelURI = 'second_video_channel@localhost:' + servers[0].port
+ const { total } = await server.videos.listByChannel({ handle: secondChannelURI })
+ expect(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 channelURI = 'root_channel@localhost:' + servers[0].port
+ const { total, data } = await server.videos.listByChannel({ handle: channelURI })
+ expect(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')
+ expect(data).to.be.an('array')
+ expect(data).to.have.lengthOf(1)
+ expect(data[0].name).to.equal('my video name')
+ }
}
})
it('Should delete video channel', async function () {
- await deleteVideoChannel(servers[0].url, servers[0].accessToken, 'second_video_channel')
+ await servers[0].channels.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].channels.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].channels.create({ attributes: videoChannel })
+ totoChannel = created.id
}
{
- await createUser({ url: servers[0].url, accessToken: servers[0].accessToken, username: 'toto', password: 'password' })
- const accessToken = await userLogin(servers[0], { 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 res = await getMyUserInformation(servers[0].url, accessToken)
- const videoChannel = res.body.videoChannels[0]
+ 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}/)
}
})
@@ -444,15 +397,9 @@ describe('Test video channels', function () {
this.timeout(10000)
{
- const res = await getAccountVideoChannelsList({
- url: servers[0].url,
- accountName,
- withStats: true
- })
+ const { data } = await servers[0].channels.listByAccount({ accountName, withStats: true })
- const channels: VideoChannel[] = res.body.data
-
- 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
@@ -464,33 +411,24 @@ 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')
+ // 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 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].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 res = await getAccountVideoChannelsList({
- url: servers[0].url,
- accountName,
- withStats: true
- })
- const channels: VideoChannel[] = res.body.data
+ const { data } = await servers[0].channels.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 +436,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].channels.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].channels.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)
}
})
@@ -525,34 +455,24 @@ 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].videos.upload({ attributes: { channelId: totoChannel } })
await waitJobs(servers)
for (const server of servers) {
- const res = await getAccountVideoChannelsList({
- url: server.url,
- accountName,
- sort: '-updatedAt'
- })
+ const { data } = await server.channels.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 servers[0].videos.upload({ attributes: { channelId: servers[0].store.channel.id } })
await waitJobs(servers)
for (const server of servers) {
- const res = await getAccountVideoChannelsList({
- url: server.url,
- accountName,
- sort: '-updatedAt'
- })
+ const { data } = await server.channels.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-comments.ts b/server/tests/api/videos/video-comments.ts
index b6b002307..61ee54540 100644
--- a/server/tests/api/videos/video-comments.ts
+++ b/server/tests/api/videos/video-comments.ts
@@ -2,80 +2,62 @@
import 'mocha'
import * as chai from 'chai'
-import { VideoComment, VideoCommentAdmin, VideoCommentThreadTree } from '@shared/models'
-import { cleanupTests, testImage } from '../../../../shared/extra-utils'
import {
- createUser,
+ cleanupTests,
+ CommentsCommand,
+ createSingleServer,
dateIsValid,
- flushAndRunServer,
- getAccessToken,
- ServerInfo,
+ PeerTubeServer,
setAccessTokensToServers,
- updateMyAvatar,
- uploadVideo
-} from '../../../../shared/extra-utils/index'
-import {
- addVideoCommentReply,
- addVideoCommentThread,
- deleteVideoComment,
- getAdminVideoComments,
- getVideoCommentThreads,
- getVideoThreadComments
-} from '../../../../shared/extra-utils/videos/video-comments'
+ testImage
+} from '@shared/extra-utils'
const expect = chai.expect
describe('Test video comments', function () {
- let server: ServerInfo
- let videoId
- let videoUUID
- let threadId
+ let server: PeerTubeServer
+ let videoId: number
+ let videoUUID: string
+ let threadId: number
let replyToDeleteId: number
let userAccessTokenServer1: string
+ let command: CommentsCommand
+
before(async function () {
this.timeout(30000)
- server = await flushAndRunServer(1)
+ server = await createSingleServer(1)
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.videos.upload()
+ videoUUID = uuid
+ videoId = id
- await updateMyAvatar({
- url: server.url,
- accessToken: server.accessToken,
- fixture: 'avatar.png'
- })
+ await server.users.updateMyAvatar({ fixture: 'avatar.png' })
- await createUser({
- url: server.url,
- accessToken: server.accessToken,
- username: 'user1',
- password: 'password'
- })
- userAccessTokenServer1 = await getAccessToken(server.url, 'user1', 'password')
+ userAccessTokenServer1 = await server.users.generateUserAndToken('user1')
+
+ command = server.comments
})
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 +73,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 +99,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 +111,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 +144,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')
+ const body = await command.listThreads({ videoId: videoUUID, sort: '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(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(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)
+ 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 +200,88 @@ describe('Test video comments', function () {
})
it('Should delete a complete thread', async function () {
- await deleteVideoComment(server.url, server.accessToken, videoId, threadId)
+ await command.delete({ videoId, commentId: 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)
+ 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(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)
+ 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/api/videos/video-description.ts b/server/tests/api/videos/video-description.ts
index b8e98e45f..d22b4ed96 100644
--- a/server/tests/api/videos/video-description.ts
+++ b/server/tests/api/videos/video-description.ts
@@ -1,25 +1,13 @@
/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */
-import * as chai from 'chai'
import 'mocha'
-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 * as chai from 'chai'
+import { cleanupTests, createMultipleServers, doubleFollow, 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)
@@ -28,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)
@@ -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].videos.upload({ attributes })
await waitJobs(servers)
- const res = await getVideosList(servers[0].url)
+ const { data } = await servers[0].videos.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.videos.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.videos.get({ id: videoUUID })
- const res2 = await getVideoDescription(server.url, video.descriptionPath)
- expect(res2.body.description).to.equal(longDescription)
+ const { description } = await server.videos.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].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 res = await getVideo(server.url, videoUUID)
- const video = res.body
+ const video = await server.videos.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.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 03ac3f321..7845f7334 100644
--- a/server/tests/api/videos/video-hls.ts
+++ b/server/tests/api/videos/video-hls.ts
@@ -9,31 +9,22 @@ import {
checkSegmentHash,
checkTmpIsEmpty,
cleanupTests,
+ createMultipleServers,
doubleFollow,
- flushAndRunMultipleServers,
- getPlaylist,
- getVideo,
makeRawRequest,
- removeVideo,
- ServerInfo,
+ PeerTubeServer,
setAccessTokensToServers,
- updateCustomSubConfig,
- 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 { HttpStatusCode, VideoStreamingPlaylistType } from '@shared/models'
import { DEFAULT_AUDIO_RESOLUTION } from '../../../initializers/constants'
-import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
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 resVideoDetails = await getVideo(server.url, videoUUID)
- const videoDetails: VideoDetails = resVideoDetails.body
+ const videoDetails = await server.videos.get({ id: videoUUID })
const baseUrl = `http://${videoDetails.account.host}`
expect(videoDetails.streamingPlaylists).to.have.lengthOf(1)
@@ -68,10 +59,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.streamingPlaylists.get({ url: hlsPlaylist.playlistUrl })
for (const resolution of resolutions) {
expect(masterPlaylist).to.contain(`${resolution}.m3u8`)
@@ -81,9 +71,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.streamingPlaylists.get({
+ url: `${baseUrl}/static/streaming-playlists/hls/${videoUUID}/${resolution}.m3u8`
+ })
- const subPlaylist = res.text
expect(subPlaylist).to.contain(`${videoUUID}-${resolution}-fragmented.mp4`)
}
}
@@ -92,23 +83,31 @@ 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
+ })
}
}
}
}
describe('Test HLS videos', function () {
- let servers: ServerInfo[] = []
+ let servers: PeerTubeServer[] = []
let videoUUID = ''
let videoAudioUUID = ''
function runTestSuite (hlsOnly: boolean) {
+
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].videos.upload({ attributes: { name: 'video 1', fixture: 'video_short.webm' } })
+ videoUUID = uuid
await waitJobs(servers)
@@ -118,8 +117,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].videos.upload({ attributes: { name: 'video audio', fixture: 'sample.ogg' } })
+ videoAudioUUID = uuid
await waitJobs(servers)
@@ -129,7 +128,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].videos.update({ id: videoUUID, attributes: { name: 'video 1 updated' } })
await waitJobs(servers)
@@ -139,14 +138,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].videos.remove({ id: videoUUID })
+ await servers[0].videos.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.videos.get({ id: videoUUID, expectedStatus: HttpStatusCode.NOT_FOUND_404 })
+ await server.videos.get({ id: videoAudioUUID, expectedStatus: HttpStatusCode.NOT_FOUND_404 })
}
})
@@ -176,7 +175,7 @@ describe('Test HLS videos', function () {
}
}
}
- servers = await flushAndRunMultipleServers(2, configOverride)
+ servers = await createMultipleServers(2, configOverride)
// Get the access tokens
await setAccessTokensToServers(servers)
@@ -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].config.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..2eac130d2 100644
--- a/server/tests/api/videos/video-imports.ts
+++ b/server/tests/api/videos/video-imports.ts
@@ -3,43 +3,30 @@
import 'mocha'
import * as chai from 'chai'
import {
+ areHttpImportTestsDisabled,
cleanupTests,
+ createMultipleServers,
doubleFollow,
- flushAndRunMultipleServers,
- getMyUserInformation,
- getMyVideos,
- getVideo,
- getVideosList,
- immutableAssign,
- listVideoCaptions,
- ServerInfo,
+ FIXTURE_URLS,
+ PeerTubeServer,
setAccessTokensToServers,
testCaptionFile,
- updateCustomSubConfig
-} 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 { VideoCaption, VideoDetails, VideoImport, VideoPrivacy, VideoResolution } from '../../../../shared/models/videos'
+ testImage,
+ waitJobs
+} from '@shared/extra-utils'
+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 (url: string, idHttp: string, idMagnet: string, idTorrent: string) {
- const resHttp = await getVideo(url, idHttp)
- const videoHttp: VideoDetails = resHttp.body
+ 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')
// FIXME: youtube-dl seems broken
@@ -56,10 +43,8 @@ describe('Test video imports', function () {
expect(originallyPublishedAt.getMonth()).to.equal(0)
expect(originallyPublishedAt.getFullYear()).to.equal(2019)
- const resMagnet = await getVideo(url, idMagnet)
- const videoMagnet: VideoDetails = resMagnet.body
- const resTorrent = await getVideo(url, idTorrent)
- const videoTorrent: VideoDetails = resTorrent.body
+ 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')
@@ -74,13 +59,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.captions.list({ videoId: idHttp })
+ expect(bodyCaptions.total).to.equal(2)
}
- async function checkVideoServer2 (url: string, id: number | string) {
- const res = await getVideo(url, id)
- const video: VideoDetails = res.body
+ async function checkVideoServer2 (server: PeerTubeServer, id: number | string) {
+ const video = await server.videos.get({ id })
expect(video.name).to.equal('my super name')
expect(video.category.label).to.equal('Entertainment')
@@ -92,26 +76,26 @@ 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.captions.list({ videoId: id })
+ expect(bodyCaptions.total).to.equal(2)
}
before(async function () {
this.timeout(30_000)
// Run servers
- servers = await flushAndRunMultipleServers(2)
+ servers = await createMultipleServers(2)
await setAccessTokensToServers(servers)
{
- const res = await getMyUserInformation(servers[0].url, servers[0].accessToken)
- channelIdServer1 = res.body.videoChannels[0].id
+ const { videoChannels } = await servers[0].users.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].users.getMyInfo()
+ channelIdServer2 = videoChannels[0].id
}
await doubleFollow(servers[0], servers[1])
@@ -126,18 +110,18 @@ 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 = { ...baseAttributes, targetUrl: FIXTURE_URLS.youtube }
+ const { video } = await servers[0].imports.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 resCaptions = await listVideoCaptions(servers[0].url, res.body.video.id)
- const videoCaptions: VideoCaption[] = resCaptions.body.data
+ const bodyCaptions = await servers[0].captions.list({ videoId: video.id })
+ const videoCaptions = bodyCaptions.data
expect(videoCaptions).to.have.lengthOf(2)
const enCaption = videoCaptions.find(caption => caption.language.id === 'en')
@@ -176,52 +160,52 @@ Ajouter un sous-titre est vraiment facile`)
}
{
- const attributes = immutableAssign(baseAttributes, {
- magnetUri: getMagnetURI(),
+ const attributes = {
+ ...baseAttributes,
+ magnetUri: FIXTURE_URLS.magnet,
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].imports.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 res = await importVideo(servers[0].url, servers[0].accessToken, attributes)
- expect(res.body.video.name).to.equal('你好 世界 720p.mp4')
+ }
+ 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 res = await getMyVideos(servers[0].url, servers[0].accessToken, 0, 5, 'createdAt')
+ const { total, data } = await servers[0].videos.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 () {
- const res = await getMyVideoImports(servers[0].url, servers[0].accessToken, '-createdAt')
+ const { total, data: videoImports } = await servers[0].imports.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(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(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')
@@ -237,12 +221,12 @@ 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.videos.list()
+ expect(total).to.equal(3)
+ expect(data).to.have.lengthOf(3)
- const [ videoHttp, videoMagnet, videoTorrent ] = res.body.data
- await checkVideosServer1(server.url, videoHttp.uuid, videoMagnet.uuid, videoTorrent.uuid)
+ const [ videoHttp, videoMagnet, videoTorrent ] = data
+ await checkVideosServer1(server, videoHttp.uuid, videoMagnet.uuid, videoTorrent.uuid)
}
})
@@ -250,7 +234,7 @@ Ajouter un sous-titre est vraiment facile`)
this.timeout(60_000)
const attributes = {
- targetUrl: getYoutubeVideoUrl(),
+ targetUrl: FIXTURE_URLS.youtube,
channelId: channelIdServer2,
privacy: VideoPrivacy.PUBLIC,
category: 10,
@@ -260,8 +244,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].imports.importVideo({ attributes })
+ expect(video.name).to.equal('my super name')
})
it('Should have the videos listed on the two instances', async function () {
@@ -270,14 +254,14 @@ 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.videos.list()
+ expect(total).to.equal(4)
+ expect(data).to.have.lengthOf(4)
- await checkVideoServer2(server.url, res.body.data[0].uuid)
+ await checkVideoServer2(server, data[0].uuid)
- const [ , videoHttp, videoMagnet, videoTorrent ] = res.body.data
- await checkVideosServer1(server.url, videoHttp.uuid, videoMagnet.uuid, videoTorrent.uuid)
+ const [ , videoHttp, videoMagnet, videoTorrent ] = data
+ await checkVideosServer1(server, videoHttp.uuid, videoMagnet.uuid, videoTorrent.uuid)
}
})
@@ -286,18 +270,17 @@ Ajouter un sous-titre est vraiment facile`)
const attributes = {
name: 'transcoded video',
- magnetUri: getMagnetURI(),
+ magnetUri: FIXTURE_URLS.magnet,
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].imports.importVideo({ attributes })
+ const videoUUID = video.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.videos.get({ id: videoUUID })
expect(video.name).to.equal('transcoded video')
expect(video.files).to.have.lengthOf(4)
@@ -333,22 +316,21 @@ Ajouter un sous-titre est vraiment facile`)
}
}
}
- await updateCustomSubConfig(servers[0].url, servers[0].accessToken, config)
+ await servers[0].config.updateCustomSubConfig({ newConfig: config })
const attributes = {
name: 'hdr video',
- targetUrl: getYoutubeHDRVideoUrl(),
+ targetUrl: FIXTURE_URLS.youtubeHDR,
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].imports.importVideo({ attributes })
+ const videoUUID = videoImported.uuid
await waitJobs(servers)
// test resolution
- const res2 = await getVideo(servers[0].url, videoUUID)
- const video: VideoDetails = res2.body
+ 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 b16b484b9..b5d183d62 100644
--- a/server/tests/api/videos/video-nsfw.ts
+++ b/server/tests/api/videos/video-nsfw.ts
@@ -1,117 +1,96 @@
/* 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 {
- flushAndRunServer,
- getAccountVideos,
- getConfig,
- getCustomConfig,
- getMyUserInformation,
- getVideoChannelVideos,
- getVideosListWithToken,
- searchVideo,
- searchVideoWithToken,
- 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'
+import * as chai from 'chai'
+import { cleanupTests, createSingleServer, PeerTubeServer, setAccessTokensToServers } from '@shared/extra-utils'
+import { BooleanBothQuery, CustomConfig, ResultList, Video, 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 } }
+ return { data: videos, total: videos.length }
}
describe('Test video NSFW policy', function () {
- let server: ServerInfo
+ let server: PeerTubeServer
let userAccessToken: string
let customConfig: CustomConfig
- function getVideosFunctions (token?: string, query = {}) {
- 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[]
+ async function getVideosFunctions (token?: string, query: { nsfw?: BooleanBothQuery } = {}) {
+ const user = await server.users.getMyInfo()
- if (token) {
- promises = [
- getVideosListWithToken(server.url, token, query),
- searchVideoWithToken(server.url, 'n', token, query),
- getAccountVideos(server.url, token, accountName, 0, 5, undefined, query),
- getVideoChannelVideos(server.url, token, videoChannelName, 0, 5, undefined, query)
- ]
+ const channelName = user.videoChannels[0].name
+ const accountName = user.account.name + '@' + user.account.host
- // Overviews do not support video filters
- if (!hasQuery) {
- promises.push(getVideosOverviewWithToken(server.url, 1, token).then(res => createOverviewRes(res)))
- }
+ const hasQuery = Object.keys(query).length !== 0
+ let promises: Promise>[]
- return Promise.all(promises)
- }
+ if (token) {
+ promises = [
+ server.search.advancedVideoSearch({ token, search: { search: 'n', sort: '-publishedAt', ...query } }),
+ server.videos.listWithToken({ token, ...query }),
+ server.videos.listByAccount({ token, handle: accountName, ...query }),
+ server.videos.listByChannel({ token, handle: channelName, ...query })
+ ]
- promises = [
- getVideosList(server.url),
- searchVideo(server.url, '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.overviews.getVideos({ page: 1, token })
+ .then(res => createOverviewRes(res))
+ promises.push(p)
+ }
- // Overviews do not support video filters
- if (!hasQuery) {
- promises.push(getVideosOverview(server.url, 1).then(res => createOverviewRes(res)))
- }
+ return Promise.all(promises)
+ }
- return Promise.all(promises)
- })
+ promises = [
+ server.search.searchVideos({ search: 'n', sort: '-publishedAt' }),
+ server.videos.list(),
+ server.videos.listByAccount({ token: null, handle: accountName }),
+ server.videos.listByChannel({ token: null, handle: channelName })
+ ]
+
+ // Overviews do not support video filters
+ if (!hasQuery) {
+ const p = server.overviews.getVideos({ page: 1 })
+ .then(res => createOverviewRes(res))
+ promises.push(p)
+ }
+
+ return Promise.all(promises)
}
before(async function () {
this.timeout(50000)
- server = await flushAndRunServer(1)
+ server = await createSingleServer(1)
// Get the access tokens
await setAccessTokensToServers([ server ])
{
const attributes = { name: 'nsfw', nsfw: true, category: 1 }
- await uploadVideo(server.url, server.accessToken, attributes)
+ await server.videos.upload({ attributes })
}
{
const attributes = { name: 'normal', nsfw: false, category: 1 }
- await uploadVideo(server.url, server.accessToken, attributes)
+ await server.videos.upload({ attributes })
}
- {
- const res = await getCustomConfig(server.url, server.accessToken)
- customConfig = res.body
- }
+ customConfig = await server.config.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.config.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')
@@ -120,16 +99,15 @@ 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.config.updateCustomConfig({ newCustomConfig: customConfig })
- const resConfig = await getConfig(server.url)
- const serverConfig: ServerConfig = resConfig.body
+ const serverConfig = await server.config.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')
}
@@ -137,16 +115,15 @@ 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.config.updateCustomConfig({ newCustomConfig: customConfig })
- const resConfig = await getConfig(server.url)
- const serverConfig: ServerConfig = resConfig.body
+ const serverConfig = await server.config.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')
@@ -159,24 +136,22 @@ 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.users.create({ username: username, password: password })
- userAccessToken = await userLogin(server, { username, password })
-
- const res = await getMyUserInformation(server.url, userAccessToken)
- const user = res.body
+ userAccessToken = await server.login.getAccessToken({ username, password })
+ 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 updateCustomConfig(server.url, server.accessToken, customConfig)
+ await server.config.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')
@@ -184,16 +159,12 @@ 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.users.updateMe({ 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')
@@ -201,56 +172,51 @@ 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.users.updateMe({ 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')
}
})
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.videos.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 () {
- 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/tests/api/videos/video-playlist-thumbnails.ts b/server/tests/api/videos/video-playlist-thumbnails.ts
index a93a0b7de..f0b2ca169 100644
--- a/server/tests/api/videos/video-playlist-thumbnails.ts
+++ b/server/tests/api/videos/video-playlist-thumbnails.ts
@@ -1,21 +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 {
- addVideoInPlaylist,
cleanupTests,
- createVideoPlaylist,
+ createMultipleServers,
doubleFollow,
- flushAndRunMultipleServers,
- getVideoPlaylistsList,
- removeVideoFromPlaylist,
- reorderVideosPlaylist,
- ServerInfo,
+ PeerTubeServer,
setAccessTokensToServers,
setDefaultVideoChannel,
testImage,
- uploadVideoAndGetId,
waitJobs
} from '../../../../shared/extra-utils'
import { VideoPlaylistPrivacy } from '../../../../shared/models/videos/playlist/video-playlist-privacy.model'
@@ -23,10 +17,10 @@ import { VideoPlaylistPrivacy } from '../../../../shared/models/videos/playlist/
const expect = chai.expect
describe('Playlist thumbnail', function () {
- let servers: ServerInfo[] = []
+ let servers: PeerTubeServer[] = []
- let playlistWithoutThumbnail: number
- let playlistWithThumbnail: number
+ let playlistWithoutThumbnailId: number
+ let playlistWithThumbnailId: number
let withThumbnailE1: number
let withThumbnailE2: number
@@ -36,22 +30,22 @@ describe('Playlist thumbnail', function () {
let video1: number
let video2: number
- async function getPlaylistWithoutThumbnail (server: ServerInfo) {
- const res = await getVideoPlaylistsList(server.url, 0, 10)
+ async function getPlaylistWithoutThumbnail (server: PeerTubeServer) {
+ const body = await server.playlists.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)
+ async function getPlaylistWithThumbnail (server: PeerTubeServer) {
+ const body = await server.playlists.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 () {
this.timeout(120000)
- servers = await flushAndRunMultipleServers(2, { transcoding: { enabled: false } })
+ servers = await createMultipleServers(2, { transcoding: { enabled: false } })
// Get the access tokens
await setAccessTokensToServers(servers)
@@ -60,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].videos.quickUpload({ name: 'video 1' })).id
+ video2 = (await servers[0].videos.quickUpload({ name: 'video 2' })).id
await waitJobs(servers)
})
@@ -69,24 +63,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].playlists.create({
+ attributes: {
displayName: 'playlist without thumbnail',
privacy: VideoPlaylistPrivacy.PUBLIC,
- videoChannelId: servers[1].videoChannel.id
+ videoChannelId: servers[1].store.channel.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].playlists.addElement({
+ playlistId: playlistWithoutThumbnailId,
+ attributes: { videoId: video1 }
})
- withoutThumbnailE1 = res2.body.videoPlaylistElement.id
+ withoutThumbnailE1 = added.id
await waitJobs(servers)
@@ -99,25 +89,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].playlists.create({
+ attributes: {
displayName: 'playlist with thumbnail',
privacy: VideoPlaylistPrivacy.PUBLIC,
- videoChannelId: servers[1].videoChannel.id,
+ videoChannelId: servers[1].store.channel.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].playlists.addElement({
+ playlistId: playlistWithThumbnailId,
+ attributes: { videoId: video1 }
})
- withThumbnailE1 = res2.body.videoPlaylistElement.id
+ withThumbnailE1 = added.id
await waitJobs(servers)
@@ -130,19 +116,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].playlists.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].playlists.reorderElements({
+ playlistId: playlistWithoutThumbnailId,
+ attributes: {
startPosition: 1,
insertAfterPosition: 2
}
@@ -159,19 +141,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].playlists.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].playlists.reorderElements({
+ playlistId: playlistWithThumbnailId,
+ attributes: {
startPosition: 1,
insertAfterPosition: 2
}
@@ -188,11 +166,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].playlists.removeElement({
+ playlistId: playlistWithoutThumbnailId,
+ elementId: withoutThumbnailE1
})
await waitJobs(servers)
@@ -206,11 +182,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].playlists.removeElement({
+ playlistId: playlistWithThumbnailId,
+ elementId: withThumbnailE1
})
await waitJobs(servers)
@@ -224,11 +198,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].playlists.removeElement({
+ playlistId: playlistWithoutThumbnailId,
+ elementId: withoutThumbnailE2
})
await waitJobs(servers)
@@ -242,11 +214,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].playlists.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 da8de054b..f42aee2ff 100644
--- a/server/tests/api/videos/video-playlists.ts
+++ b/server/tests/api/videos/video-playlists.ts
@@ -2,71 +2,33 @@
import 'mocha'
import * as chai from 'chai'
-import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
import {
- addVideoChannel,
- addVideoInPlaylist,
- addVideoToBlacklist,
checkPlaylistFilesWereRemoved,
cleanupTests,
- createUser,
- createVideoPlaylist,
- deleteVideoChannel,
- deleteVideoPlaylist,
+ createMultipleServers,
doubleFollow,
- doVideosExistInMyPlaylist,
- flushAndRunMultipleServers,
- generateUserAccessToken,
- getAccessToken,
- getAccountPlaylistsList,
- getAccountPlaylistsListWithToken,
- getMyUserInformation,
- getPlaylistVideos,
- getVideoChannelPlaylistsList,
- getVideoPlaylist,
- getVideoPlaylistPrivacies,
- getVideoPlaylistsList,
- getVideoPlaylistWithToken,
- removeUser,
- removeVideoFromBlacklist,
- removeVideoFromPlaylist,
- reorderVideosPlaylist,
- ServerInfo,
+ PeerTubeServer,
+ PlaylistsCommand,
setAccessTokensToServers,
setDefaultVideoChannel,
testImage,
- unfollow,
- updateVideo,
- updateVideoPlaylist,
- updateVideoPlaylistElement,
- uploadVideo,
- uploadVideoAndGetId,
- 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'
+ HttpStatusCode,
+ VideoPlaylist,
+ VideoPlaylistCreateResult,
+ VideoPlaylistElementType,
+ VideoPlaylistPrivacy,
+ VideoPlaylistType,
+ VideoPrivacy
+} from '@shared/models'
const expect = chai.expect
async function checkPlaylistElementType (
- servers: ServerInfo[],
+ servers: PeerTubeServer[],
playlistId: string,
type: VideoPlaylistElementType,
position: number,
@@ -74,10 +36,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.playlists.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) {
@@ -90,11 +52,11 @@ async function checkPlaylistElementType (
}
describe('Test video playlists', function () {
- let servers: ServerInfo[] = []
+ let servers: PeerTubeServer[] = []
let playlistServer2Id1: number
let playlistServer2Id2: number
- let playlistServer2UUID2: number
+ let playlistServer2UUID2: string
let playlistServer1Id: number
let playlistServer1UUID: string
@@ -106,12 +68,14 @@ describe('Test video playlists', function () {
let nsfwVideoServer1: number
- let userAccessTokenServer1: string
+ let userTokenServer1: string
+
+ let commands: PlaylistsCommand[]
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)
@@ -122,86 +86,78 @@ describe('Test video playlists', function () {
// Server 1 and server 3 follow each other
await doubleFollow(servers[0], servers[2])
+ 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 resVideo = await uploadVideo(server.url, server.accessToken, { name, nsfw: false })
+ const video = await server.videos.upload({ attributes: { name, nsfw: false } })
- server.videos.push(resVideo.body.video)
+ server.store.videos.push(video)
}
}
}
- nsfwVideoServer1 = (await uploadVideoAndGetId({ server: servers[0], videoName: 'NSFW video', nsfw: true })).id
+ nsfwVideoServer1 = (await servers[0].videos.quickUpload({ name: 'NSFW video', nsfw: true })).id
- {
- await createUser({
- url: servers[0].url,
- accessToken: servers[0].accessToken,
- username: 'user1',
- password: 'password'
- })
- userAccessTokenServer1 = await getAccessToken(servers[0].url, 'user1', 'password')
- }
+ userTokenServer1 = await servers[0].users.generateUserAndToken('user1')
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 token = await servers[0].users.generateUserAndToken('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 })
})
})
@@ -210,15 +166,13 @@ 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',
thumbnailfile: 'thumbnail.jpg',
- videoChannelId: servers[0].videoChannel.id
+ videoChannelId: servers[0].store.channel.id
}
})
@@ -227,14 +181,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.playlists.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.playlists.get({ playlistId: playlistFromList.uuid })
for (const playlist of [ playlistFromGet, playlistFromList ]) {
expect(playlist.id).to.be.a('number')
@@ -264,46 +217,38 @@ 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].playlists.create({
+ attributes: {
displayName: 'playlist 2',
privacy: VideoPlaylistPrivacy.PUBLIC,
- videoChannelId: servers[1].videoChannel.id
+ videoChannelId: servers[1].store.channel.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].playlists.create({
+ attributes: {
displayName: 'playlist 3',
privacy: VideoPlaylistPrivacy.PUBLIC,
thumbnailfile: 'thumbnail.jpg',
- videoChannelId: servers[1].videoChannel.id
+ videoChannelId: servers[1].store.channel.id
}
})
- 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].playlists.addElement({
playlistId: id,
- elementAttrs: { videoId: servers[1].videos[0].id, startTimestamp: 1, stopTimestamp: 2 }
+ attributes: { videoId: servers[1].store.videos[0].id, startTimestamp: 1, stopTimestamp: 2 }
})
- await addVideoInPlaylist({
- url: servers[1].url,
- token: servers[1].accessToken,
+ await servers[1].playlists.addElement({
playlistId: id,
- elementAttrs: { videoId: servers[1].videos[1].id }
+ attributes: { videoId: servers[1].store.videos[1].id }
})
}
@@ -311,20 +256,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.playlists.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].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
})
it('Should have the playlist on server 3 after a new follow', async function () {
@@ -333,13 +278,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].playlists.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
})
})
@@ -349,22 +294,20 @@ describe('Test video playlists', function () {
this.timeout(30000)
{
- const res = await getVideoPlaylistsList(servers[2].url, 1, 2, 'createdAt')
+ const body = await servers[2].playlists.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')
+ const body = await servers[2].playlists.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('my super playlist')
@@ -375,11 +318,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')
}
@@ -389,41 +331,37 @@ describe('Test video playlists', function () {
this.timeout(30000)
{
- const res = await getAccountPlaylistsList(servers[1].url, 'root', 1, 2, '-createdAt')
+ const body = await servers[1].playlists.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 2')
}
{
- const res = await getAccountPlaylistsList(servers[1].url, 'root', 1, 2, 'createdAt')
+ const body = await servers[1].playlists.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')
+ const body = await servers[1].playlists.listByAccount({ handle: 'root', sort: 'createdAt', search: '3' })
+ 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('playlist 3')
}
{
- const res = await getAccountPlaylistsList(servers[1].url, 'root', 0, 10, 'createdAt', '4')
+ const body = await servers[1].playlists.listByAccount({ handle: 'root', sort: 'createdAt', search: '4' })
+ expect(body.total).to.equal(0)
- expect(res.body.total).to.equal(0)
-
- const data: VideoPlaylist[] = res.body.data
+ const data = body.data
expect(data).to.have.lengthOf(0)
}
})
@@ -437,28 +375,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].playlists.create({
+ attributes: {
displayName: 'playlist unlisted',
privacy: VideoPlaylistPrivacy.UNLISTED,
- videoChannelId: servers[1].videoChannel.id
+ videoChannelId: servers[1].store.channel.id
}
})
- unlistedPlaylist = res.body.videoPlaylist
}
{
- const res = await createVideoPlaylist({
- url: servers[1].url,
- token: servers[1].accessToken,
- playlistAttrs: {
+ privatePlaylist = await servers[1].playlists.create({
+ attributes: {
displayName: 'playlist private',
privacy: VideoPlaylistPrivacy.PRIVATE
}
})
- privatePlaylist = res.body.videoPlaylist
}
await waitJobs(servers)
@@ -468,15 +400,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.playlists.listByAccount({ handle: 'root@localhost:' + servers[1].port, sort: '-createdAt' }),
+ await server.playlists.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')
@@ -485,23 +417,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].playlists.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].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 getVideoPlaylist(servers[1].url, id, 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 getVideoPlaylistWithToken(servers[1].url, servers[1].accessToken, id)
+ await servers[1].playlists.get({ token: servers[1].accessToken, playlistId: id })
}
})
})
@@ -511,15 +443,13 @@ 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].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
})
@@ -527,8 +457,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.playlists.get({ playlistId: playlistServer2UUID2 })
expect(playlist.displayName).to.equal('playlist 3 updated')
expect(playlist.description).to.equal('description updated')
@@ -554,39 +483,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
+ videoChannelId: servers[0].store.channel.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 })
+ 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 res = await addVideo({ videoId: servers[0].videos[3].uuid, stopTimestamp: 35 })
- playlistElementServer1Video4 = res.body.videoPlaylistElement.id
+ const element = await addVideo({ videoId: servers[0].store.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].store.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 })
@@ -599,64 +526,68 @@ describe('Test video playlists', function () {
this.timeout(30000)
for (const server of servers) {
- const res = await getPlaylistVideos(server.url, server.accessToken, playlistServer1UUID, 0, 10)
+ {
+ const body = await server.playlists.listVideos({ playlistId: playlistServer1UUID, start: 0, count: 10 })
- expect(res.body.total).to.equal(8)
+ expect(body.total).to.equal(8)
- const videoElements: VideoPlaylistElement[] = res.body.data
- expect(videoElements).to.have.lengthOf(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[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[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[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[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[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[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[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
+ 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.playlists.listVideos({ playlistId: playlistServer1UUID, start: 0, count: 2 })
+ expect(body.data).to.have.lengthOf(2)
+ }
}
})
})
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
@@ -665,31 +596,30 @@ 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
+ videoChannelId: servers[0].store.channel.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
- 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].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)
@@ -707,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].videos.update({ id: video1, attributes: { privacy: VideoPrivacy.PRIVATE } })
await waitJobs(servers)
await checkPlaylistElementType(groupUser1, playlistServer1UUID2, VideoPlaylistElementType.REGULAR, position, name, 3)
@@ -717,7 +647,7 @@ describe('Test video playlists', function () {
}
{
- await updateVideo(servers[0].url, servers[0].accessToken, video1, { 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)
@@ -735,7 +665,7 @@ describe('Test video playlists', function () {
const position = 1
{
- await addVideoToBlacklist(servers[0].url, servers[0].accessToken, video1, 'reason', true)
+ await servers[0].blacklist.add({ videoId: video1, reason: 'reason', unfederate: true })
await waitJobs(servers)
await checkPlaylistElementType(groupUser1, playlistServer1UUID2, VideoPlaylistElementType.REGULAR, position, name, 3)
@@ -745,7 +675,7 @@ describe('Test video playlists', function () {
}
{
- await removeVideoFromBlacklist(servers[0].url, servers[0].accessToken, video1)
+ await servers[0].blacklist.remove({ videoId: video1 })
await waitJobs(servers)
await checkPlaylistElementType(groupUser1, playlistServer1UUID2, VideoPlaylistElementType.REGULAR, position, name, 3)
@@ -759,56 +689,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].blocklist
+
const name = 'video 90'
const position = 2
{
- await addAccountToAccountBlocklist(servers[0].url, userAccessTokenServer1, '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 removeAccountFromAccountBlocklist(servers[0].url, userAccessTokenServer1, '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 addServerToAccountBlocklist(servers[0].url, userAccessTokenServer1, '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 removeServerFromAccountBlocklist(servers[0].url, userAccessTokenServer1, '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)
}
{
- 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)
@@ -816,10 +748,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
@@ -835,11 +767,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
}
@@ -848,8 +778,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.playlists.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',
@@ -865,11 +795,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
@@ -879,8 +807,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.playlists.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',
@@ -896,11 +824,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
}
@@ -909,8 +835,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.playlists.listVideos({ playlistId: playlistServer1UUID, start: 0, count: 10 })
const names = elements.map(v => v.video.name)
expect(names).to.deep.equal([
@@ -934,22 +859,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
}
})
@@ -957,8 +878,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.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)
@@ -974,17 +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 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]
+ 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)
@@ -993,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)
@@ -1002,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)
@@ -1015,42 +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 res = await getAccountPlaylistsListWithToken(server.url, server.accessToken, 'root', 0, 5, undefined, '-updatedAt')
+ const { data } = await server.playlists.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.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 removeVideoFromPlaylist({
- url: server.url,
- token: server.accessToken,
- playlistId: playlistServer2Id1,
- playlistElementId: element1
- })
+ 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 removeVideoFromPlaylist({
- url: server.url,
- token: server.accessToken,
- playlistId: playlistServer2Id2,
- playlistElementId: element2
- })
+ await server.playlists.removeElement({ playlistId: playlistServer2Id2, elementId: element2.id })
const names3 = await getPlaylistNames()
expect(names3[0]).to.equal('playlist 3 updated')
@@ -1060,28 +966,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)
+ const body = await server.playlists.listVideos({ playlistId: playlistServer1UUID, start: 0, count: 10 })
+ expect(body.total).to.equal(6)
- expect(res.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')
@@ -1107,34 +1001,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
+ videoChannelId: servers[0].store.channel.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.playlists.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.playlists.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 })
})
})
@@ -1143,12 +1034,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.playlists.get({ playlistId: playlistServer1UUID, expectedStatus: HttpStatusCode.NOT_FOUND_404 })
}
})
@@ -1163,75 +1054,61 @@ 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].playlists.list({ start: 0, count: 5 })
+ expect(body.total).to.equal(3)
+
+ expect(finder(body.data)).to.not.be.undefined
}
- await unfollow(servers[2].url, servers[2].accessToken, servers[0])
+ await servers[2].follows.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].playlists.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
}
})
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].channels.create({ attributes: { name: 'super_channel', displayName: 'super channel' } })
- 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
+ videoChannelId: channel.id
}
})
- const videoPlaylistUUID = res2.body.videoPlaylist.uuid
await waitJobs(servers)
- await deleteVideoChannel(servers[0].url, servers[0].accessToken, 'super_channel')
+ await servers[0].channels.delete({ channelName: 'super_channel' })
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].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 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, token } = await servers[0].users.generate('user_1')
- const userId = res.body.user.id
- const userAccessToken = await userLogin(servers[0], user)
+ const { videoChannels } = await servers[0].users.getMyInfo({ token })
+ const userChannel = videoChannels[0]
- 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
@@ -1240,22 +1117,24 @@ 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.playlists.list({ start: 0, count: 15 })
+
+ expect(finder(body.data)).to.not.be.undefined
}
}
- await removeUser(servers[0].url, userId, servers[0].accessToken)
+ await servers[0].users.remove({ userId })
await waitJobs(servers)
{
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.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 950aeb7cf..b51b3bcdd 100644
--- a/server/tests/api/videos/video-privacy.ts
+++ b/server/tests/api/videos/video-privacy.ts
@@ -2,28 +2,13 @@
import 'mocha'
import * as chai from 'chai'
-import { HttpStatusCode } from '@shared/core-utils/miscs/http-error-codes'
-import { Video, VideoCreateResult } from '@shared/models'
-import {
- cleanupTests,
- flushAndRunServer,
- getVideosList,
- getVideosListWithToken,
- 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'
+import { cleanupTests, createSingleServer, doubleFollow, PeerTubeServer, setAccessTokensToServers, waitJobs } from '@shared/extra-utils'
+import { HttpStatusCode, 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
@@ -49,8 +34,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)
@@ -66,55 +51,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].videos.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].videos.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].videos.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].videos.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].videos.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].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 () {
@@ -124,18 +107,23 @@ 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].users.create({ username: user.username, password: user.password })
- anotherUserToken = await userLogin(servers[0], user)
- await getVideoWithToken(servers[0].url, anotherUserToken, privateVideoUUID, HttpStatusCode.FORBIDDEN_403)
+ anotherUserToken = await servers[0].login.getAccessToken(user)
+
+ await servers[0].videos.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].videos.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].videos.getWithToken({ id: privateVideoUUID })
})
})
@@ -148,7 +136,7 @@ describe('Test video privacy', function () {
name: 'unlisted video',
privacy: VideoPrivacy.UNLISTED
}
- await uploadVideo(servers[1].url, servers[1].accessToken, attributes)
+ await servers[1].videos.upload({ attributes })
// Server 2 has transcoding enabled
await waitJobs(servers)
@@ -156,32 +144,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.videos.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].videos.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].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 () {
for (const server of servers) {
for (const id of [ unlistedVideo.uuid, unlistedVideo.shortUUID ]) {
- const res = await getVideo(server.url, id)
+ const video = await server.videos.get({ id })
- expect(res.body.name).to.equal('unlisted video')
+ expect(video.name).to.equal('unlisted video')
}
}
})
@@ -193,28 +181,28 @@ describe('Test video privacy', function () {
name: 'unlisted video',
privacy: VideoPrivacy.UNLISTED
}
- await uploadVideo(servers[0].url, servers[0].accessToken, attributes)
+ await servers[0].videos.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].videos.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].videos.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].videos.get({ id: nonFederatedUnlistedVideoUUID, expectedStatus: HttpStatusCode.NOT_FOUND_404 })
})
})
@@ -226,20 +214,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].videos.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].videos.update({ id: internalVideoId, attributes })
}
await waitJobs(servers)
@@ -247,13 +235,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.videos.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 +257,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].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 res = await getVideosList(server.url)
+ const { total, data } = await server.videos.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
+ const { total, data } = await servers[0].videos.listMyVideos()
+ expect(total).to.equal(3)
+ expect(data).to.have.lengthOf(3)
- expect(res.body.total).to.equal(3)
- expect(videos).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..3f7738784 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,
+ createMultipleServers,
doubleFollow,
- flushAndRunMultipleServers,
- getMyVideos,
- getVideosList,
- getVideoWithToken,
- ServerInfo,
+ PeerTubeServer,
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
@@ -28,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)
@@ -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].videos.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.videos.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].videos.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].videos.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.videos.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].videos.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].videos.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.videos.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].videos.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)
+ const { total, data } = await server.videos.list()
+ expect(total).to.equal(2)
- expect(res.body.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 ea5ffd239..e4892bb24 100644
--- a/server/tests/api/videos/video-transcoder.ts
+++ b/server/tests/api/videos/video-transcoder.ts
@@ -2,36 +2,23 @@
import 'mocha'
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 {
buildAbsoluteFixturePath,
- buildServerDirectory,
cleanupTests,
+ createMultipleServers,
doubleFollow,
- flushAndRunMultipleServers,
generateHighBitrateVideo,
generateVideoWithFramerate,
- getJobsListPaginationAndSort,
- getMyVideos,
- getServerFileSize,
- getVideo,
- getVideoFileMetadataUrl,
- getVideosList,
makeGetRequest,
- ServerInfo,
+ PeerTubeServer,
setAccessTokensToServers,
- updateCustomSubConfig,
- uploadVideo,
- uploadVideoAndGetId,
waitJobs,
webtorrentAdd
-} from '../../../../shared/extra-utils'
-import { getMaxBitrate, VideoDetails, VideoResolution, VideoState } from '../../../../shared/models/videos'
+} from '@shared/extra-utils'
+import { getMaxBitrate, HttpStatusCode, VideoResolution, VideoState } from '@shared/models'
+import { VIDEO_TRANSCODING_FPS } from '../../../../server/initializers/constants'
import {
canDoQuickTranscode,
getAudioStream,
@@ -43,37 +30,39 @@ 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
+function updateConfigForTranscoding (server: PeerTubeServer) {
+ return server.config.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
+ }
}
}
})
}
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)
@@ -87,21 +76,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].videos.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.videos.list()
+ const video = data[0]
- const res2 = await getVideo(server.url, video.id)
- const videoDetails = res2.body
+ const videoDetails = await server.videos.get({ id: video.id })
expect(videoDetails.files).to.have.lengthOf(1)
const magnetUri = videoDetails.files[0].magnetUri
@@ -117,21 +105,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].videos.upload({ attributes })
await waitJobs(servers)
for (const server of servers) {
- const res = await getVideosList(server.url)
+ const { data } = await server.videos.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.videos.get({ id: video.id })
expect(videoDetails.files).to.have.lengthOf(4)
@@ -150,47 +137,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].videos.upload({ attributes })
+ const videoId = uuid
// Should be in transcode state
- const { body } = await getVideo(servers[1].url, 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')
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].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)
+ 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].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 getVideo(servers[0].url, videoId, 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 res = await getVideosList(server.url)
- const videoToFind = res.body.data.find(v => v.name === 'waiting video')
+ const { data } = await server.videos.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.videos.get({ id: videoToFind.id })
expect(videoDetails.state.id).to.equal(VideoState.PUBLISHED)
expect(videoDetails.state.label).to.equal('Published')
@@ -211,22 +201,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].videos.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.videos.list()
+ const video = data.find(v => v.name === attributes.name)
+ const videoDetails = await server.videos.get({ id: video.id })
expect(videoDetails.files).to.have.lengthOf(4)
const magnetUri = videoDetails.files[0].magnetUri
@@ -238,22 +226,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].videos.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.videos.get({ id: video4k })
expect(videoDetails.files).to.have.lengthOf(resolutions.length)
for (const r of resolutions) {
@@ -269,24 +255,23 @@ 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].videos.upload({ attributes })
await waitJobs(servers)
for (const server of servers) {
- const res = await getVideosList(server.url)
+ const { data } = await server.videos.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.videos.get({ id: video.id })
expect(videoDetails.files).to.have.lengthOf(4)
- const path = buildServerDirectory(servers[1], 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) {
@@ -301,23 +286,22 @@ 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].videos.upload({ attributes })
await waitJobs(servers)
for (const server of servers) {
- const res = await getVideosList(server.url)
+ const { data } = await server.videos.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.videos.get({ id: video.id })
expect(videoDetails.files).to.have.lengthOf(4)
- const path = buildServerDirectory(servers[1], 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')
}
@@ -326,26 +310,25 @@ 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].videos.upload({ attributes })
await waitJobs(servers)
for (const server of servers) {
- const res = await getVideosList(server.url)
+ const { data } = await server.videos.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.videos.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 = buildServerDirectory(servers[1], join('videos', video.uuid + '-240.mp4'))
+ const path = servers[1].servers.buildDirectory(join('videos', video.uuid + '-240.mp4'))
const videoProbe = await getAudioStream(path)
@@ -364,19 +347,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].config.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
+ }
}
}
})
@@ -385,22 +370,21 @@ 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].videos.upload({ attributes, mode })
await waitJobs(servers)
for (const server of servers) {
- const res = await getVideosList(server.url)
+ const { data } = await server.videos.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.videos.get({ id: video.id })
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')
@@ -410,22 +394,21 @@ 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].videos.upload({ attributes, mode })
await waitJobs(servers)
for (const server of servers) {
- const res = await getVideosList(server.url)
+ const { data } = await server.videos.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.videos.get({ id: video.id })
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')
@@ -435,26 +418,27 @@ 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].config.updateCustomSubConfig({
+ newConfig: {
+ transcoding: {
+ hls: { enabled: true },
+ webtorrent: { enabled: true },
+ resolutions: {
+ '0p': true,
+ '240p': false,
+ '360p': false
+ }
}
}
})
- 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].videos.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.videos.get({ id })
for (const files of [ videoDetails.files, videoDetails.streamingPlaylists[0].files ]) {
expect(files).to.have.lengthOf(2)
@@ -480,21 +464,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].videos.upload({ attributes })
await waitJobs(servers)
for (const server of servers) {
- const res = await getVideosList(server.url)
+ const { data } = await server.videos.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.videos.get({ id: video.id })
expect(videoDetails.files).to.have.lengthOf(4)
expect(videoDetails.files[0].fps).to.be.above(58).and.below(62)
@@ -503,13 +486,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].servers.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].servers.buildDirectory(join('videos', video.uuid + '-720.mp4'))
const fps = await getVideoFileFPS(path)
expect(fps).to.be.above(58).and.below(62)
@@ -528,29 +511,29 @@ 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].videos.upload({ attributes })
await waitJobs(servers)
for (const server of servers) {
- const res = await getVideosList(server.url)
+ const { data } = await server.videos.list()
- const video = res.body.data.find(v => v.name === videoAttributes.name)
+ const video = data.find(v => v.name === attributes.name)
{
- const path = buildServerDirectory(servers[1], 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 = buildServerDirectory(servers[1], 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)
}
@@ -571,23 +554,23 @@ 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].videos.upload({ attributes })
await waitJobs(servers)
for (const server of servers) {
- const res = await getVideosList(server.url)
+ const { data } = await server.videos.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 = buildServerDirectory(servers[1], 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,7 +585,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: {
@@ -618,22 +601,21 @@ describe('Test video transcoding', function () {
hls: { enabled: true }
}
}
- await updateCustomSubConfig(servers[1].url, servers[1].accessToken, config)
+ await servers[1].config.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].videos.upload({ attributes })
await waitJobs(servers)
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 path = `videos/${uuid}-${r}.mp4`
+ const size = await servers[1].servers.getServerFileSize(path)
expect(size, `${path} not below ${60_000}`).to.be.below(60_000)
}
})
@@ -644,11 +626,11 @@ 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].videos.quickUpload({ name: 'ffprobe data' })).uuid
await waitJobs(servers)
{
- const path = buildServerDirectory(servers[1], join('videos', videoUUID + '-240.mp4'))
+ const path = servers[1].servers.buildDirectory(join('videos', videoUUID + '-240.mp4'))
const metadata = await getMetadataFromFile(path)
// expected format properties
@@ -678,8 +660,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.videos.get({ id: videoUUID })
const videoFiles = videoDetails.files
.concat(videoDetails.streamingPlaylists[0].files)
@@ -691,8 +672,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.videos.getFileMetadata({ url: file.metadataUrl })
expect(metadata).to.have.nested.property('format.size')
}
}
@@ -709,17 +689,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].jobs.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/server/tests/api/videos/videos-filter.ts b/server/tests/api/videos/videos-filter.ts
index 7428b82c5..2306807bf 100644
--- a/server/tests/api/videos/videos-filter.ts
+++ b/server/tests/api/videos/videos-filter.ts
@@ -1,25 +1,18 @@
/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */
-import * as chai from 'chai'
import 'mocha'
+import { expect } from 'chai'
import {
cleanupTests,
- createUser,
+ createMultipleServers,
doubleFollow,
- flushAndRunMultipleServers,
makeGetRequest,
- ServerInfo,
- setAccessTokensToServers,
- uploadVideo,
- userLogin
-} 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'
+ PeerTubeServer,
+ setAccessTokensToServers
+} from '@shared/extra-utils'
+import { HttpStatusCode, UserRole, Video, VideoPrivacy } from '@shared/models'
-const expect = chai.expect
-
-async function getVideosNames (server: ServerInfo, 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',
@@ -38,7 +31,7 @@ async function getVideosNames (server: ServerInfo, token: string, filter: string
sort: 'createdAt',
filter
},
- statusCodeExpected
+ expectedStatus
})
videosResults.push(res.body.data.map(v => v.name))
@@ -48,42 +41,32 @@ 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)
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
- }
- )
- server['moderatorAccessToken'] = await userLogin(server, moderator)
+ await server.users.create({ username: moderator.username, password: moderator.password, role: UserRole.MODERATOR })
+ server['moderatorAccessToken'] = await server.login.getAccessToken(moderator)
- await uploadVideo(server.url, server.accessToken, { name: 'public ' + server.serverNumber })
+ await server.videos.upload({ attributes: { name: 'public ' + server.serverNumber } })
{
const attributes = { name: 'unlisted ' + server.serverNumber, privacy: VideoPrivacy.UNLISTED }
- await uploadVideo(server.url, server.accessToken, attributes)
+ await server.videos.upload({ attributes })
}
{
const attributes = { name: 'private ' + server.serverNumber, privacy: VideoPrivacy.PRIVATE }
- await uploadVideo(server.url, server.accessToken, 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 b25cff879..e4bc0bb3a 100644
--- a/server/tests/api/videos/videos-history.ts
+++ b/server/tests/api/videos/videos-history.ts
@@ -1,74 +1,66 @@
/* 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,
- createUser,
- flushAndRunServer,
- getVideosListWithToken,
- getVideoWithToken,
+ createSingleServer,
+ HistoryCommand,
killallServers,
- reRunServer,
- searchVideoWithToken,
- ServerInfo,
+ PeerTubeServer,
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 { HttpStatusCode, 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
let video3WatchedDate: Date
let userAccessToken: string
+ let command: HistoryCommand
before(async function () {
this.timeout(30000)
- server = await flushAndRunServer(1)
+ server = await createSingleServer(1)
await setAccessTokensToServers([ server ])
+ command = server.history
+
{
- const res = await uploadVideo(server.url, server.accessToken, { name: 'video 1' })
- video1UUID = res.body.video.uuid
+ const { uuid } = await server.videos.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.videos.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.videos.upload({ attributes: { name: 'video 3' } })
+ video3UUID = uuid
}
const user = {
username: 'user_1',
password: 'super password'
}
- await createUser({ url: server.url, accessToken: server.accessToken, username: user.username, password: user.password })
- userAccessToken = await userLogin(server, 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 res = await getVideosListWithToken(server.url, server.accessToken)
- const videos: Video[] = res.body.data
+ const { data } = await server.videos.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.videos.getWithToken({ id: video.id })
expect(video.userHistory).to.be.undefined
expect(videoDetails.userHistory).to.be.undefined
@@ -76,21 +68,21 @@ 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 () {
const videosOfVideos: Video[][] = []
{
- const res = await getVideosListWithToken(server.url, server.accessToken)
- videosOfVideos.push(res.body.data)
+ const { data } = await server.videos.listWithToken()
+ videosOfVideos.push(data)
}
{
- const res = await searchVideoWithToken(server.url, 'video', server.accessToken)
- videosOfVideos.push(res.body.data)
+ const body = await server.search.searchVideos({ token: server.accessToken, search: 'video' })
+ videosOfVideos.push(body.data)
}
for (const videos of videosOfVideos) {
@@ -108,24 +100,21 @@ describe('Test videos history', function () {
}
{
- const resDetail = await getVideoWithToken(server.url, server.accessToken, video1UUID)
- const videoDetails: VideoDetails = resDetail.body
+ const videoDetails = await server.videos.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.videos.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.videos.getWithToken({ id: video3UUID })
expect(videoDetails.userHistory).to.be.undefined
}
@@ -133,71 +122,64 @@ 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')
+ const body = await command.list({ search: '2' })
+ expect(body.total).to.equal(1)
- expect(res.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)
+ const body = await command.list()
+ expect(body.total).to.equal(1)
- expect(res.body.total).to.equal(1)
-
- const videos: Video[] = res.body.data
+ const videos = body.data
expect(videos[0].name).to.equal('video 3')
})
it('Should disable videos history', async function () {
- await updateMyUser({
- url: server.url,
- accessToken: server.accessToken,
+ await server.users.updateMe({
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 () {
- await updateMyUser({
- url: server.url,
- accessToken: server.accessToken,
+ await server.users.updateMe({
videosHistoryEnabled: true
})
- await userWatchVideo(server.url, server.accessToken, video1UUID, 8)
+ await command.wathVideo({ videoId: video1UUID, currentTime: 8 })
- const res = await listMyVideosHistory(server.url, server.accessToken)
+ const body = await command.list()
+ expect(body.total).to.equal(2)
- expect(res.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')
})
@@ -205,30 +187,29 @@ 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' } } })
+ await server.run({ history: { videos: { max_age: '10 days' } } })
await wait(6000)
// 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 () {
this.timeout(50000)
- killallServers([ server ])
+ await killallServers([ server ])
- await reRunServer(server, { history: { videos: { max_age: '5 seconds' } } })
+ await server.run({ history: { videos: { max_age: '5 seconds' } } })
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/server/tests/api/videos/videos-overview.ts b/server/tests/api/videos/videos-overview.ts
index c266a1dc5..70aa66549 100644
--- a/server/tests/api/videos/videos-overview.ts
+++ b/server/tests/api/videos/videos-overview.ts
@@ -2,29 +2,15 @@
import 'mocha'
import * as chai from 'chai'
-
-import {
- cleanupTests,
- flushAndRunServer,
- generateUserAccessToken,
- ServerInfo,
- 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'
+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
-
- function testOverviewCount (res: Response, expected: number) {
- const overview: VideosOverview = res.body
+ let server: PeerTubeServer = null
+ 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)
@@ -33,15 +19,15 @@ describe('Test a videos overview', function () {
before(async function () {
this.timeout(30000)
- server = await flushAndRunServer(1)
+ server = await createSingleServer(1)
await setAccessTokensToServers([ server ])
})
it('Should send empty overview', async function () {
- const res = await getVideosOverview(server.url, 1)
+ const body = await server.overviews.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 () {
@@ -49,40 +35,45 @@ 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.videos.upload({
+ attributes: {
+ name: 'video 0',
+ category: 3,
+ tags: [ 'coucou1', 'coucou2' ]
+ }
})
- const res = await getVideosOverview(server.url, 1)
+ const body = await server.overviews.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' ]
- })
- }
-
- await wait(3000)
-
{
- const res = await getVideosOverview(server.url, 1)
+ for (let i = 1; i < 6; i++) {
+ await server.videos.upload({
+ attributes: {
+ name: 'video ' + i,
+ category: 3,
+ tags: [ 'coucou1', 'coucou2' ]
+ }
+ })
+ }
- testOverviewCount(res, 1)
+ await wait(3000)
}
{
- const res = await getVideosOverview(server.url, 2)
+ const body = await server.overviews.getVideos({ page: 1 })
+
+ testOverviewCount(body, 1)
+ }
+
+ {
+ const overview = await server.overviews.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 +81,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 = await server.overviews.getVideos({ page: 1 })
+ const overview2 = await server.overviews.getVideos({ page: 2 })
- const overview1: VideosOverview = res1.body
- const overview2: VideosOverview = res2.body
-
- const tmp = [
- overview1.tags,
- overview1.categories,
- overview1.channels,
- overview2.tags
- ]
-
- 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]
@@ -127,20 +108,20 @@ describe('Test a videos overview', function () {
})
it('Should hide muted accounts', async function () {
- const token = await generateUserAccessToken(server, 'choco')
+ const token = await server.users.generateUserAndToken('choco')
- await addAccountToAccountBlocklist(server.url, token, 'root@' + server.host)
+ await server.blocklist.addToMyBlocklist({ token, account: 'root@' + server.host })
{
- const res = await getVideosOverview(server.url, 1)
+ const body = await server.overviews.getVideos({ page: 1 })
- testOverviewCount(res, 1)
+ testOverviewCount(body, 1)
}
{
- const res = await getVideosOverviewWithToken(server.url, 1, token)
+ const body = await server.overviews.getVideos({ page: 1, token })
- testOverviewCount(res, 0)
+ testOverviewCount(body, 0)
}
})
diff --git a/server/tests/api/videos/videos-views-cleaner.ts b/server/tests/api/videos/videos-views-cleaner.ts
index b89f33217..82268b1be 100644
--- a/server/tests/api/videos/videos-views-cleaner.ts
+++ b/server/tests/api/videos/videos-views-cleaner.ts
@@ -1,19 +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 {
cleanupTests,
- closeAllSequelize,
- countVideoViewsOf,
+ createMultipleServers,
doubleFollow,
- flushAndRunMultipleServers,
killallServers,
- reRunServer,
- ServerInfo,
+ PeerTubeServer,
setAccessTokensToServers,
- uploadVideoAndGetId,
- viewVideo,
wait,
waitJobs
} from '../../../../shared/extra-utils'
@@ -21,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
@@ -29,20 +24,20 @@ 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])
- 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].videos.quickUpload({ name: 'video server 1' })).uuid
+ videoIdServer2 = (await servers[1].videos.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].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)
})
@@ -50,9 +45,9 @@ 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' } } } })
+ await servers[0].run({ views: { videos: { remote: { max_age: '10 days' } } } })
await wait(6000)
@@ -60,14 +55,14 @@ describe('Test video views cleaner', function () {
{
for (const server of servers) {
- const total = await countVideoViewsOf(server.internalServerNumber, 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 countVideoViewsOf(server.internalServerNumber, videoIdServer2)
+ const total = await server.sql.countVideoViewsOf(videoIdServer2)
expect(total).to.equal(2, 'Server ' + server.serverNumber + ' does not have the correct amount of views')
}
}
@@ -76,9 +71,9 @@ 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' } } } })
+ await servers[0].run({ views: { videos: { remote: { max_age: '5 seconds' } } } })
await wait(6000)
@@ -86,23 +81,21 @@ describe('Test video views cleaner', function () {
{
for (const server of servers) {
- const total = await countVideoViewsOf(server.internalServerNumber, videoIdServer1)
+ const total = await server.sql.countVideoViewsOf(videoIdServer1)
expect(total).to.equal(2)
}
}
{
- const totalServer1 = await countVideoViewsOf(servers[0].internalServerNumber, videoIdServer2)
+ const totalServer1 = await servers[0].sql.countVideoViewsOf(videoIdServer2)
expect(totalServer1).to.equal(0)
- const totalServer2 = await countVideoViewsOf(servers[1].internalServerNumber, videoIdServer2)
+ const totalServer2 = await servers[1].sql.countVideoViewsOf(videoIdServer2)
expect(totalServer2).to.equal(2)
}
})
after(async function () {
- await closeAllSequelize(servers)
-
await cleanupTests(servers)
})
})
diff --git a/server/tests/cli/create-import-video-file-job.ts b/server/tests/cli/create-import-video-file-job.ts
index 49758ff56..bddcff5e7 100644
--- a/server/tests/cli/create-import-video-file-job.ts
+++ b/server/tests/cli/create-import-video-file-job.ts
@@ -2,21 +2,8 @@
import 'mocha'
import * as chai from 'chai'
-import { VideoFile } from '@shared/models/videos/video-file.model'
-import {
- cleanupTests,
- doubleFollow,
- execCLI,
- flushAndRunMultipleServers,
- getEnvCli,
- 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, createMultipleServers, doubleFollow, PeerTubeServer, setAccessTokensToServers, waitJobs } from '@shared/extra-utils'
+import { VideoFile } from '@shared/models'
const expect = chai.expect
@@ -33,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
@@ -41,56 +28,61 @@ 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])
// 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].videos.upload({ attributes: { name: 'video1' } })
+ video1UUID = uuid
+ }
+
+ {
+ const { uuid } = await servers[1].videos.upload({ attributes: { name: 'video2' } })
+ video2UUID = uuid
+ }
// Transcoding
await waitJobs(servers)
})
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].cli.execWithEnv(command)
await waitJobs(servers)
for (const server of servers) {
- const { data: videos } = (await getVideosList(server.url)).body
+ const { data: videos } = await server.videos.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.videos.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)
}
})
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].cli.execWithEnv(command)
await waitJobs(servers)
for (const server of servers) {
- const { data: videos } = (await getVideosList(server.url)).body
+ const { data: videos } = await server.videos.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.videos.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')
@@ -99,20 +91,20 @@ 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].cli.execWithEnv(command)
await waitJobs(servers)
for (const server of servers) {
- const { data: videos } = (await getVideosList(server.url)).body
+ const { data: videos } = await server.videos.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.videos.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 5bc1687cd..df787ccdc 100644
--- a/server/tests/cli/create-transcoding-job.ts
+++ b/server/tests/cli/create-transcoding-job.ts
@@ -2,26 +2,19 @@
import 'mocha'
import * as chai from 'chai'
-import { VideoDetails } from '../../../shared/models/videos'
import {
cleanupTests,
+ createMultipleServers,
doubleFollow,
- execCLI,
- flushAndRunMultipleServers,
- getEnvCli,
- getVideo,
- getVideosList,
- ServerInfo,
+ PeerTubeServer,
setAccessTokensToServers,
- updateCustomSubConfig,
- uploadVideo
+ waitJobs
} from '../../../shared/extra-utils'
-import { waitJobs } from '../../../shared/extra-utils/server/jobs'
const expect = chai.expect
describe('Test create transcoding jobs', function () {
- let servers: ServerInfo[] = []
+ let servers: PeerTubeServer[] = []
const videosUUID: string[] = []
const config = {
@@ -46,16 +39,16 @@ 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 updateCustomSubConfig(servers[0].url, servers[0].accessToken, config)
+ await servers[0].config.updateCustomSubConfig({ newConfig: config })
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].videos.upload({ attributes: { name: 'video' + i } })
+ videosUUID.push(uuid)
}
await waitJobs(servers)
@@ -65,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.videos.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.videos.get({ id: video.uuid })
expect(videoDetail.files).to.have.lengthOf(1)
expect(videoDetail.streamingPlaylists).to.have.lengthOf(0)
}
@@ -81,20 +72,16 @@ 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].cli.execWithEnv(`npm run create-transcoding-job -- -v ${videosUUID[1]}`)
await waitJobs(servers)
for (const server of servers) {
- const res = await getVideosList(server.url)
- const videos = res.body.data
+ const { data } = await server.videos.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.videos.get({ id: video.uuid })
if (video.uuid === videosUUID[1]) {
expect(videoDetail.files).to.have.lengthOf(4)
@@ -123,43 +110,38 @@ 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].cli.execWithEnv(`npm run create-transcoding-job -- -v ${videosUUID[0]} -r 480`)
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.videos.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.videos.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)
}
})
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].cli.execWithEnv(`npm run create-transcoding-job -- -v ${videosUUID[2]} --generate-hls -r 480`)
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.videos.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)
}
@@ -168,16 +150,14 @@ 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].cli.execWithEnv(`npm run create-transcoding-job -- -v ${videosUUID[2]} --generate-hls -r 480`)
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.videos.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)
}
@@ -186,19 +166,17 @@ 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].cli.execWithEnv(`npm run create-transcoding-job -- -v ${videosUUID[3]} --generate-hls`)
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.videos.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)
}
})
@@ -207,20 +185,18 @@ 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].config.updateCustomSubConfig({ newConfig: config })
- const env = getEnvCli(servers[0])
- await execCLI(`${env} 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 res = await getVideo(server.url, videosUUID[4])
- const videoDetail: VideoDetails = res.body
+ const videoDetails = await server.videos.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 91a1c9cc4..685b3b7b8 100644
--- a/server/tests/cli/optimize-old-videos.ts
+++ b/server/tests/cli/optimize-old-videos.ts
@@ -4,36 +4,29 @@ import 'mocha'
import * as chai from 'chai'
import { join } from 'path'
import {
- buildServerDirectory,
cleanupTests,
+ createMultipleServers,
doubleFollow,
- execCLI,
- flushAndRunMultipleServers,
generateHighBitrateVideo,
- getEnvCli,
- getVideo,
- getVideosList,
- ServerInfo,
+ PeerTubeServer,
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'
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])
@@ -48,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].videos.upload({ attributes: { name: 'video1', fixture: tempFixturePath } })
+ await servers[0].videos.upload({ attributes: { name: 'video2', fixture: tempFixturePath } })
await waitJobs(servers)
})
@@ -58,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)
+ const { data } = await server.videos.list()
+ expect(data).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)
+ for (const video of data) {
+ const videoDetails = await server.videos.get({ id: video.uuid })
+ expect(videoDetails.files).to.have.lengthOf(1)
}
}
})
@@ -73,34 +64,29 @@ 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].cli.execWithEnv('npm run optimize-old-videos')
await waitJobs(servers)
for (const server of servers) {
- const res = await getVideosList(server.url)
- const videos: Video[] = res.body.data
+ const { data } = await server.videos.list()
+ expect(data).to.have.lengthOf(2)
- expect(videos).to.have.lengthOf(2)
-
- for (const video of videos) {
- await viewVideo(server.url, video.uuid)
+ for (const video of data) {
+ await server.videos.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.videos.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)
- const path = buildServerDirectory(servers[0], 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 fcf7e2e2e..f2a984962 100644
--- a/server/tests/cli/peertube.ts
+++ b/server/tests/cli/peertube.ts
@@ -2,97 +2,91 @@
import 'mocha'
import { expect } from 'chai'
-import { Video, VideoDetails } from '../../../shared'
import {
- addVideoChannel,
areHttpImportTestsDisabled,
buildAbsoluteFixturePath,
cleanupTests,
- createUser,
+ CLICommand,
+ createSingleServer,
doubleFollow,
- execCLI,
- flushAndRunServer,
- getEnvCli,
- getLocalIdByUUID,
- getVideo,
- getVideosList,
- removeVideo,
- ServerInfo,
+ FIXTURE_URLS,
+ PeerTubeServer,
setAccessTokensToServers,
testHelloWorldRegisteredSettings,
- uploadVideoAndGetId,
- userLogin,
waitJobs
} from '../../../shared/extra-utils'
-import { getYoutubeVideoUrl } from '../../../shared/extra-utils/videos/video-imports'
describe('Test CLI wrapper', function () {
- let server: ServerInfo
+ let server: PeerTubeServer
let userAccessToken: string
+ let cliCommand: CLICommand
+
const cmd = 'node ./dist/server/tools/peertube.js'
before(async function () {
this.timeout(30000)
- server = await flushAndRunServer(1)
+ server = await createSingleServer(1)
await setAccessTokensToServers([ server ])
- await createUser({ url: server.url, accessToken: server.accessToken, username: 'user_1', password: 'super_password' })
+ await server.users.create({ username: 'user_1', password: 'super_password' })
- userAccessToken = await userLogin(server, { username: 'user_1', password: 'super_password' })
+ userAccessToken = await server.login.getAccessToken({ 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.channels.create({ token: userAccessToken, attributes })
}
+
+ cliCommand = server.cli
})
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 body = await server.users.getMyInfo({ token })
+ expect(body.username).to.equal('user_1')
+ })
+
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,24 +96,17 @@ 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 () {
- 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.videos.list()
+ expect(total).to.equal(1)
+ 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')
@@ -130,11 +117,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}`)
+ const params = `--target-url ${FIXTURE_URLS.youtube} --channel-name user_channel`
+ await cliCommand.execWithEnv(`${cmd} import ${params}`)
})
it('Should have imported the video', async function () {
@@ -144,21 +128,19 @@ describe('Test CLI wrapper', function () {
await waitJobs([ server ])
- const res = await getVideosList(server.url)
+ const { total, data } = await server.videos.list()
+ expect(total).to.equal(2)
- expect(res.body.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.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 removeVideo(server.url, userAccessToken, video.id)
+ await server.videos.remove({ token: userAccessToken, id: video.id })
})
it('Should import and override some imported attributes', async function () {
@@ -166,23 +148,20 @@ 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}`)
+ const params = `--target-url ${FIXTURE_URLS.youtube} ` +
+ `--channel-name user_channel --video-name toto --nsfw --support support`
+ await cliCommand.execWithEnv(`${cmd} import ${params}`)
await waitJobs([ server ])
{
- const res = await getVideosList(server.url)
- expect(res.body.total).to.equal(2)
+ const { total, data } = await server.videos.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.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
@@ -194,18 +173,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 +189,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,29 +197,27 @@ 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')
})
})
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)
@@ -253,20 +225,17 @@ 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.videos.quickUpload({ name: 'super video' })
await waitJobs(servers)
- video1Server2 = await getLocalIdByUUID(server.url, uuid)
+ video1Server2 = await server.videos.getId({ uuid })
})
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 +244,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 +255,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..07c78cc89 100644
--- a/server/tests/cli/plugins.ts
+++ b/server/tests/cli/plugins.ts
@@ -1,55 +1,47 @@
/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */
import 'mocha'
+import { expect } from 'chai'
import {
cleanupTests,
- execCLI,
- flushAndRunServer,
- getConfig,
- getEnvCli,
- getPluginTestPath,
+ createSingleServer,
killallServers,
- reRunServer,
- ServerInfo,
+ PeerTubeServer,
+ PluginsCommand,
setAccessTokensToServers
} from '../../../shared/extra-utils'
-import { ServerConfig } from '../../../shared/models/server'
-import { expect } from 'chai'
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 ])
})
it('Should install a plugin from stateless CLI', async function () {
this.timeout(60000)
- const packagePath = getPluginTestPath()
+ const packagePath = PluginsCommand.getPluginTestPath()
- const env = getEnvCli(server)
- await execCLI(`${env} 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)
- const env = getEnvCli(server)
- await execCLI(`${env} 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 () {
this.timeout(30000)
- killallServers([ server ])
- await reRunServer(server)
+ await killallServers([ server ])
+ await server.run()
- const res = await getConfig(server.url)
- const config: ServerConfig = res.body
+ const config = await server.config.getConfig()
const plugin = config.plugin.registered
.find(p => p.name === 'test')
@@ -63,18 +55,16 @@ 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.cli.execWithEnv(`npm run plugin:uninstall -- --npm-name peertube-plugin-test`)
})
it('Should have removed the plugin on another peertube restart', async function () {
this.timeout(30000)
- killallServers([ server ])
- await reRunServer(server)
+ await killallServers([ server ])
+ await server.run()
- const res = await getConfig(server.url)
- const config: ServerConfig = res.body
+ const config = await server.config.getConfig()
const plugin = config.plugin.registered
.find(p => p.name === 'test')
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..954a87833 100644
--- a/server/tests/cli/prune-storage.ts
+++ b/server/tests/cli/prune-storage.ts
@@ -5,87 +5,78 @@ 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 {
- buildServerDirectory,
cleanupTests,
- createVideoPlaylist,
+ CLICommand,
+ createMultipleServers,
doubleFollow,
- execCLI,
- flushAndRunMultipleServers,
- getAccount,
- getEnvCli,
killallServers,
makeGetRequest,
- ServerInfo,
+ PeerTubeServer,
setAccessTokensToServers,
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 { HttpStatusCode, 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: PeerTubeServer, directory: string) {
+ const files = await readdir(server.servers.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: PeerTubeServer, directory: string, substring: string) {
+ const files = await readdir(server.servers.buildDirectory(directory))
for (const f of files) {
expect(f).to.not.contain(substring)
}
}
-async function assertCountAreOkay (servers: ServerInfo[]) {
+async function assertCountAreOkay (servers: PeerTubeServer[]) {
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)
}
}
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)
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.videos.upload({ attributes: { name: 'video 1' } })
+ await server.videos.upload({ attributes: { name: 'video 2' } })
- await updateMyAvatar({ url: server.url, accessToken: server.accessToken, fixture: 'avatar.png' })
+ await server.users.updateMyAvatar({ fixture: 'avatar.png' })
- await createVideoPlaylist({
- url: server.url,
- token: server.accessToken,
- playlistAttrs: {
+ await server.playlists.create({
+ attributes: {
displayName: 'playlist',
privacy: VideoPlaylistPrivacy.PUBLIC,
- videoChannelId: server.videoChannel.id,
+ videoChannelId: server.store.channel.id,
thumbnailfile: 'thumbnail.jpg'
}
})
@@ -95,29 +86,27 @@ 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].accounts.get({ accountName: 'root@localhost:' + servers[1].port })
await makeGetRequest({
url: servers[0].url,
path: account.avatar.path,
- statusCodeExpected: HttpStatusCode.OK_200
+ expectedStatus: HttpStatusCode.OK_200
})
}
{
- const res = await getAccount(servers[1].url, 'root@localhost:' + servers[0].port)
- const account: Account = res.body
+ const account = await servers[1].accounts.get({ accountName: 'root@localhost:' + servers[0].port })
await makeGetRequest({
url: servers[1].url,
path: account.avatar.path,
- statusCodeExpected: HttpStatusCode.OK_200
+ expectedStatus: HttpStatusCode.OK_200
})
}
await wait(1000)
await waitJobs(servers)
- killallServers(servers)
+ await killallServers(servers)
await wait(1000)
})
@@ -129,7 +118,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].servers.buildDirectory('videos')
const n1 = buildUUID() + '.mp4'
const n2 = buildUUID() + '.webm'
@@ -141,7 +130,7 @@ describe('Test prune storage scripts', function () {
}
{
- const base = buildServerDirectory(servers[0], 'torrents')
+ const base = servers[0].servers.buildDirectory('torrents')
const n1 = buildUUID() + '-240.torrent'
const n2 = buildUUID() + '-480.torrent'
@@ -153,7 +142,7 @@ describe('Test prune storage scripts', function () {
}
{
- const base = buildServerDirectory(servers[0], 'thumbnails')
+ const base = servers[0].servers.buildDirectory('thumbnails')
const n1 = buildUUID() + '.jpg'
const n2 = buildUUID() + '.jpg'
@@ -165,7 +154,7 @@ describe('Test prune storage scripts', function () {
}
{
- const base = buildServerDirectory(servers[0], 'previews')
+ const base = servers[0].servers.buildDirectory('previews')
const n1 = buildUUID() + '.jpg'
const n2 = buildUUID() + '.jpg'
@@ -177,7 +166,7 @@ describe('Test prune storage scripts', function () {
}
{
- const base = buildServerDirectory(servers[0], 'avatars')
+ const base = servers[0].servers.buildDirectory('avatars')
const n1 = buildUUID() + '.png'
const n2 = buildUUID() + '.jpg'
@@ -193,8 +182,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].cli.getEnv()
+ await CLICommand.exec(`echo y | ${env} npm run prune-storage`)
})
it('Should have removed files', async function () {
@@ -202,7 +191,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 8acb9f263..780c9b4bd 100644
--- a/server/tests/cli/regenerate-thumbnails.ts
+++ b/server/tests/cli/regenerate-thumbnails.ts
@@ -2,36 +2,33 @@ import 'mocha'
import { expect } from 'chai'
import { writeFile } from 'fs-extra'
import { basename, join } from 'path'
-import { Video, VideoDetails } from '@shared/models'
+import { HttpStatusCode, Video } from '@shared/models'
import {
- buildServerDirectory,
cleanupTests,
+ createMultipleServers,
doubleFollow,
- execCLI,
- flushAndRunMultipleServers,
- getEnvCli,
- getVideo,
makeRawRequest,
- ServerInfo,
+ PeerTubeServer,
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
+async function testThumbnail (server: PeerTubeServer, videoId: number | string) {
+ const video = await server.videos.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 () {
- let servers: ServerInfo[]
+ let servers: PeerTubeServer[]
let video1: Video
let video2: Video
@@ -43,28 +40,28 @@ 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])
{
- 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].videos.quickUpload({ name: 'video 1' })).uuid
+ video1 = await servers[0].videos.get({ id: videoUUID1 })
- thumbnail1Path = join(buildServerDirectory(servers[0], 'thumbnails'), basename(video1.thumbnailPath))
+ thumbnail1Path = join(servers[0].servers.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].videos.quickUpload({ name: 'video 2' })).uuid
+ video2 = await servers[0].videos.get({ id: videoUUID2 })
}
{
- const videoUUID = (await uploadVideoAndGetId({ server: servers[1], videoName: 'video 3' })).uuid
+ const videoUUID = (await servers[1].videos.quickUpload({ name: 'video 3' })).uuid
await waitJobs(servers)
- remoteVideo = await (getVideo(servers[0].url, videoUUID).then(res => res.body))
+ remoteVideo = await servers[0].videos.get({ id: videoUUID })
- thumbnailRemotePath = join(buildServerDirectory(servers[0], 'thumbnails'), basename(remoteVideo.thumbnailPath))
+ thumbnailRemotePath = join(servers[0].servers.buildDirectory('thumbnails'), basename(remoteVideo.thumbnailPath))
}
await writeFile(thumbnail1Path, '')
@@ -91,8 +88,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].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 a84463b33..4a02db35d 100644
--- a/server/tests/cli/reset-password.ts
+++ b/server/tests/cli/reset-password.ts
@@ -1,35 +1,24 @@
import 'mocha'
-
-import {
- cleanupTests,
- createUser,
- execCLI,
- flushAndRunServer,
- getEnvCli,
- login,
- ServerInfo,
- setAccessTokensToServers
-} from '../../../shared/extra-utils'
-import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes'
+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 createUser({ url: server.url, accessToken: server.accessToken, 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 = getEnvCli(server)
- await execCLI(`echo coucou | ${env} npm run reset-password -- -u user_1`)
+ const env = server.cli.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.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 2070f16f5..fcbcb55ba 100644
--- a/server/tests/cli/update-host.ts
+++ b/server/tests/cli/update-host.ts
@@ -1,33 +1,20 @@
/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */
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 { expect } from 'chai'
import {
- addVideoChannel,
cleanupTests,
- createUser,
- execCLI,
- flushAndRunServer,
- getEnvCli,
- getVideo,
- getVideoChannelsList,
- getVideosList,
+ createSingleServer,
killallServers,
makeActivityPubGetRequest,
- parseTorrentVideo, reRunServer,
- ServerInfo,
+ parseTorrentVideo,
+ PeerTubeServer,
setAccessTokensToServers,
- uploadVideo
-} from '../../../shared/extra-utils'
-import { getAccountsList } from '../../../shared/extra-utils/users/accounts'
-
-const expect = chai.expect
+ waitJobs
+} from '@shared/extra-utils'
describe('Test update host scripts', function () {
- let server: ServerInfo
+ let server: PeerTubeServer
before(async function () {
this.timeout(60000)
@@ -38,17 +25,15 @@ 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
- 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.videos.upload()
+ await server.videos.upload()
// Create a user
- await createUser({ url: server.url, accessToken: server.accessToken, username: 'toto', password: 'coucou' })
+ await server.users.create({ username: 'toto', password: 'coucou' })
// Create channel
const videoChannel = {
@@ -56,11 +41,11 @@ describe('Test update host scripts', function () {
displayName: 'second video channel',
description: 'super video channel description'
}
- await addVideoChannel(server.url, server.accessToken, videoChannel)
+ await server.channels.create({ attributes: videoChannel })
// Create comments
const text = 'my super first comment'
- await addVideoCommentThread(server.url, server.accessToken, video1UUID, text)
+ await server.comments.createThread({ videoId: video1UUID, text })
await waitJobs(server)
})
@@ -68,25 +53,23 @@ 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)
+ await server.run()
- const env = getEnvCli(server)
- await execCLI(`${env} npm run update-host`)
+ await server.cli.execWithEnv(`npm run update-host`)
})
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.videos.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.videos.get({ id: video.uuid })
expect(videoDetails.trackerUrls[0]).to.include(server.host)
expect(videoDetails.streamingPlaylists[0].playlistUrl).to.include(server.host)
@@ -95,10 +78,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.channels.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)
@@ -106,10 +89,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.accounts.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)
@@ -120,13 +103,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.videos.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.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 7c4fb4e46..9c27a7aae 100644
--- a/server/tests/client.ts
+++ b/server/tests/client.ts
@@ -3,28 +3,16 @@
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, HttpStatusCode, ServerConfig, VideoPlaylistCreateResult, VideoPlaylistPrivacy } from '@shared/models'
import {
- addVideoInPlaylist,
cleanupTests,
- createVideoPlaylist,
+ createMultipleServers,
doubleFollow,
- flushAndRunMultipleServers,
- getAccount,
- getConfig,
- getCustomConfig,
- getVideosList,
makeGetRequest,
makeHTMLRequest,
- ServerInfo,
+ PeerTubeServer,
setAccessTokensToServers,
setDefaultVideoChannel,
- updateCustomConfig,
- updateCustomSubConfig,
- updateMyUser,
- updateVideoChannel,
- uploadVideo,
waitJobs
} from '../../shared/extra-utils'
@@ -40,7 +28,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'
@@ -62,7 +50,7 @@ describe('Test a client controllers', function () {
before(async function () {
this.timeout(120000)
- servers = await flushAndRunMultipleServers(2)
+ servers = await createMultipleServers(2)
await setAccessTokensToServers(servers)
@@ -70,47 +58,48 @@ 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].channels.update({
+ channelName: servers[0].store.channel.name,
+ attributes: { description: channelDescription }
+ })
// 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].videos.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].videos.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].store.video = video
+ videoIds = [ video.id, video.uuid, video.shortUUID ]
+ }
// Playlist
- const playlistAttrs = {
- displayName: playlistName,
- description: playlistDescription,
- privacy: VideoPlaylistPrivacy.PUBLIC,
- videoChannelId: servers[0].videoChannel.id
+ {
+ const attributes = {
+ displayName: playlistName,
+ description: playlistDescription,
+ privacy: VideoPlaylistPrivacy.PUBLIC,
+ videoChannelId: servers[0].store.channel.id
+ }
+
+ playlist = await servers[0].playlists.create({ attributes })
+ playlistIds = [ playlist.id, playlist.shortUUID, playlist.uuid ]
+
+ await servers[0].playlists.addElement({ playlistId: playlist.shortUUID, attributes: { videoId: servers[0].store.video.id } })
}
- const resVideoPlaylistRequest = await createVideoPlaylist({ url: servers[0].url, token: servers[0].accessToken, playlistAttrs })
- playlist = resVideoPlaylistRequest.body.videoPlaylist
- playlistIds = [ playlist.id, playlist.shortUUID, playlist.uuid ]
-
- await addVideoInPlaylist({
- url: servers[0].url,
- token: servers[0].accessToken,
- playlistId: playlist.shortUUID,
- elementAttrs: { videoId: video.id }
- })
-
// Account
- await updateMyUser({ url: servers[0].url, accessToken: servers[0].accessToken, description: 'my account description' })
+ {
+ await servers[0].users.updateMe({ 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].accounts.get({ accountName: `${servers[0].store.user.username}@${servers[0].host}` })
+ }
await waitJobs(servers)
})
@@ -124,14 +113,14 @@ 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
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)
}
@@ -145,7 +134,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
@@ -163,37 +152,37 @@ 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(``)
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 res = await makeGetRequest({ url: servers[0].url, path, accept: 'text/html', expectedStatus: 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) {
- 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(``)
expect(text).to.contain(``)
expect(text).to.contain('')
- expect(text).to.contain(``)
+ expect(text).to.contain(``)
}
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(``)
@@ -203,15 +192,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 () {
@@ -236,7 +225,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('')
@@ -246,17 +235,17 @@ 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('')
expect(text).to.contain('')
- expect(text).to.contain(``)
+ expect(text).to.contain(``)
expect(text).to.contain(``)
}
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('')
@@ -266,7 +255,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('')
@@ -298,27 +287,26 @@ 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 res = await getCustomConfig(servers[0].url, servers[0].accessToken)
- const config = res.body as CustomConfig
+ const config = await servers[0].config.getCustomConfig()
config.services.twitter = {
username: '@Kuja',
whitelisted: true
}
- await updateCustomConfig(servers[0].url, servers[0].accessToken, config)
+ await servers[0].config.updateCustomConfig({ newCustomConfig: config })
})
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('')
@@ -326,7 +314,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('')
@@ -334,7 +322,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('')
@@ -342,7 +330,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('')
@@ -372,9 +360,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)
})
})
})
@@ -382,53 +370,55 @@ 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].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.'
- 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].config.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].config.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].config.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 () {
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(``)
}
}
})
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 +428,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 +450,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 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; }', resConfig.body)
+ 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 e4eae7e8c..acec69df5 100644
--- a/server/tests/external-plugins/auth-ldap.ts
+++ b/server/tests/external-plugins/auth-ldap.ts
@@ -2,46 +2,29 @@
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 { cleanupTests, flushAndRunServer, ServerInfo } from '../../../shared/extra-utils/server/servers'
+import { cleanupTests, createSingleServer, PeerTubeServer, setAccessTokensToServers } from '@shared/extra-utils'
+import { HttpStatusCode } from '@shared/models'
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 installPlugin({
- url: server.url,
- accessToken: server.accessToken,
- 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 userLogin(server, { username: 'fry', password: 'fry' }, 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 updatePluginSettings({
- url: server.url,
- accessToken: server.accessToken,
+ await server.plugins.updateSettings({
npmName: 'peertube-plugin-auth-ldap',
settings: {
'bind-credentials': 'GoodNewsEveryone',
@@ -55,13 +38,11 @@ describe('Official plugin auth-ldap', function () {
}
})
- await userLogin(server, { username: 'fry', password: 'fry' }, 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 updatePluginSettings({
- url: server.url,
- accessToken: server.accessToken,
+ await server.plugins.updateSettings({
npmName: 'peertube-plugin-auth-ldap',
settings: {
'bind-credentials': 'GoodNewsEveryone',
@@ -75,22 +56,20 @@ 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.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 userLogin(server, { 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 userLogin(server, { 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 res = await getMyUserInformation(server.url, accessToken)
- const body: User = res.body
-
+ const body = await server.users.getMyInfo({ token: accessToken })
expect(body.username).to.equal('fry')
expect(body.email).to.equal('fry@planetexpress.com')
@@ -98,25 +77,31 @@ describe('Official plugin auth-ldap', function () {
})
it('Should upload a video', async function () {
- await uploadVideo(server.url, accessToken, { 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 blockUser(server.url, userId, server.accessToken)
+ await server.users.banUser({ userId })
- await userLogin(server, { username: 'fry@planetexpress.com', password: 'fry' }, 400)
+ 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 unblockUser(server.url, userId, server.accessToken)
+ await server.users.unbanUser({ userId })
- await userLogin(server, { 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 uninstallPlugin({ url: server.url, accessToken: server.accessToken, npmName: 'peertube-plugin-auth-ldap' })
+ await server.plugins.uninstall({ npmName: 'peertube-plugin-auth-ldap' })
- await userLogin(server, { username: 'fry@planetexpress.com', password: 'fry' }, 400)
+ await server.login.login({
+ user: { username: 'fry@planetexpress.com', password: 'fry' },
+ expectedStatus: HttpStatusCode.BAD_REQUEST_400
+ })
})
after(async function () {
diff --git a/server/tests/external-plugins/auto-block-videos.ts b/server/tests/external-plugins/auto-block-videos.ts
index 18ea17d78..0eb4bda9a 100644
--- a/server/tests/external-plugins/auto-block-videos.ts
+++ b/server/tests/external-plugins/auto-block-videos.ts
@@ -2,41 +2,29 @@
import 'mocha'
import { expect } from 'chai'
-import { Video, VideoBlacklist } from '@shared/models'
-import {
- doubleFollow,
- getBlacklistedVideosList,
- getVideosList,
- installPlugin,
- MockBlocklist,
- removeVideoFromBlacklist,
- setAccessTokensToServers,
- updatePluginSettings,
- uploadVideoAndGetId,
- wait
-} from '../../../shared/extra-utils'
import {
cleanupTests,
- flushAndRunMultipleServers,
+ createMultipleServers,
+ doubleFollow,
killallServers,
- reRunServer,
- ServerInfo
-} from '../../../shared/extra-utils/server/servers'
+ MockBlocklist,
+ PeerTubeServer,
+ 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)
+async function check (server: PeerTubeServer, videoUUID: string, exists = true) {
+ const { data } = await server.videos.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
- }
+ if (exists) expect(video).to.not.be.undefined
+ else expect(video).to.be.undefined
}
describe('Official plugin auto-block videos', function () {
- let servers: ServerInfo[]
+ let servers: PeerTubeServer[]
let blocklistServer: MockBlocklist
let server1Videos: Video[] = []
let server2Videos: Video[] = []
@@ -45,42 +33,36 @@ 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) {
- await installPlugin({
- url: server.url,
- accessToken: server.accessToken,
- npmName: 'peertube-plugin-auto-block-videos'
- })
+ await server.plugins.install({ npmName: 'peertube-plugin-auto-block-videos' })
}
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 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 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].videos.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].videos.list()
+ server2Videos = data.map(v => Object.assign(v, { url: servers[1].url + '/videos/watch/' + v.uuid }))
}
await doubleFollow(servers[0], servers[1])
})
it('Should update plugin settings', async function () {
- await updatePluginSettings({
- url: servers[0].url,
- accessToken: servers[0].accessToken,
+ await servers[0].plugins.updateSettings({
npmName: 'peertube-plugin-auto-block-videos',
settings: {
'blocklist-urls': `http://localhost:${port}/blocklist`,
@@ -108,10 +90,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].blacklist.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)
@@ -174,12 +155,12 @@ 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].blacklist.remove({ videoId: video.uuid })
await check(servers[0], video.uuid, true)
- killallServers([ servers[0] ])
- await reRunServer(servers[0])
+ await killallServers([ 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 09355d932..271779dd4 100644
--- a/server/tests/external-plugins/auto-mute.ts
+++ b/server/tests/external-plugins/auto-mute.ts
@@ -3,63 +3,45 @@
import 'mocha'
import { expect } from 'chai'
import {
- addAccountToServerBlocklist,
- addServerToAccountBlocklist,
- removeAccountFromServerBlocklist
-} from '@shared/extra-utils/users/blocklist'
-import {
+ cleanupTests,
+ createMultipleServers,
doubleFollow,
- getVideosList,
- installPlugin,
+ killallServers,
makeGetRequest,
MockBlocklist,
+ PeerTubeServer,
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'
+import { HttpStatusCode } from '@shared/models'
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) {
- await installPlugin({
- url: server.url,
- accessToken: server.accessToken,
- npmName: 'peertube-plugin-auto-mute'
- })
+ await server.plugins.install({ npmName: 'peertube-plugin-auto-mute' })
}
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 servers[0].videos.quickUpload({ name: 'video server 1' })
+ await servers[1].videos.quickUpload({ name: 'video server 2' })
await doubleFollow(servers[0], servers[1])
})
it('Should update plugin settings', async function () {
- await updatePluginSettings({
- url: servers[0].url,
- accessToken: servers[0].accessToken,
+ await servers[0].plugins.updateSettings({
npmName: 'peertube-plugin-auto-mute',
settings: {
'blocklist-urls': `http://localhost:${port}/blocklist`,
@@ -81,8 +63,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].videos.list()
+ expect(total).to.equal(1)
})
it('Should remove a server blocklist', async function () {
@@ -99,8 +81,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].videos.list()
+ expect(total).to.equal(2)
})
it('Should add an account blocklist', async function () {
@@ -116,8 +98,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].videos.list()
+ expect(total).to.equal(1)
})
it('Should remove an account blocklist', async function () {
@@ -134,8 +116,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].videos.list()
+ expect(total).to.equal(2)
})
it('Should auto mute an account, manually unmute it and do not remute it automatically', async function () {
@@ -155,24 +137,24 @@ 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].videos.list()
+ expect(total).to.equal(1)
}
- await removeAccountFromServerBlocklist(servers[0].url, servers[0].accessToken, account)
+ await servers[0].blocklist.removeFromServerBlocklist({ account })
{
- const res = await getVideosList(servers[0].url)
- expect(res.body.total).to.equal(2)
+ const { total } = await servers[0].videos.list()
+ expect(total).to.equal(2)
}
- killallServers([ servers[0] ])
- await reRunServer(servers[0])
+ await killallServers([ servers[0] ])
+ await servers[0].run()
await wait(2000)
{
- const res = await getVideosList(servers[0].url)
- expect(res.body.total).to.equal(2)
+ const { total } = await servers[0].videos.list()
+ expect(total).to.equal(2)
}
})
@@ -180,14 +162,12 @@ 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
})
})
it('Should enable auto mute list', async function () {
- await updatePluginSettings({
- url: servers[0].url,
- accessToken: servers[0].accessToken,
+ await servers[0].plugins.updateSettings({
npmName: 'peertube-plugin-auto-mute',
settings: {
'blocklist-urls': '',
@@ -199,16 +179,14 @@ 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
})
})
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].plugins.updateSettings({
npmName: 'peertube-plugin-auto-mute',
settings: {
'blocklist-urls': 'http://localhost:' + servers[0].port + autoMuteListPath,
@@ -217,13 +195,13 @@ 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].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,
path: '/plugins/auto-mute/router/api/v1/mute-list',
- statusCodeExpected: HttpStatusCode.OK_200
+ expectedStatus: HttpStatusCode.OK_200
})
const data = res.body.data
@@ -234,8 +212,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.videos.list()
+ expect(total).to.equal(1)
}
})
diff --git a/server/tests/feeds/feeds.ts b/server/tests/feeds/feeds.ts
index 7bad81751..5667207c0 100644
--- a/server/tests/feeds/feeds.ts
+++ b/server/tests/feeds/feeds.ts
@@ -3,35 +3,16 @@
import 'mocha'
import * as chai from 'chai'
import * as xmlParser from 'fast-xml-parser'
-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 {
cleanupTests,
- createUser,
+ createMultipleServers,
+ createSingleServer,
doubleFollow,
- flushAndRunMultipleServers,
- flushAndRunServer,
- getJSONfeed,
- getMyUserInformation,
- getUserScopedTokens,
- getXMLfeed,
- renewUserScopedTokens,
- ServerInfo,
+ PeerTubeServer,
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'
-import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes'
+ waitJobs
+} from '@shared/extra-utils'
+import { HttpStatusCode, VideoPrivacy } from '@shared/models'
chai.use(require('chai-xml'))
chai.use(require('chai-json-schema'))
@@ -39,8 +20,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
@@ -52,8 +33,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 },
@@ -65,50 +46,45 @@ 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].users.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 })
- userAccessToken = await userLogin(servers[0], attr)
+ await servers[0].users.create({ username: attr.username, password: attr.password })
+ userAccessToken = await servers[0].login.getAccessToken(attr)
- const res = await getMyUserInformation(servers[0].url, userAccessToken)
- const user: User = res.body
+ const user = await servers[0].users.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].users.getMyScopedTokens({ token: userAccessToken })
userFeedToken = token.feedToken
}
{
- await uploadVideo(servers[0].url, userAccessToken, { name: 'user video' })
+ await servers[0].videos.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].videos.upload({ attributes })
- 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].comments.createThread({ videoId: id, text: 'super comment 1' })
+ await servers[0].comments.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].videos.upload({ attributes })
- await addVideoCommentThread(servers[0].url, servers[0].accessToken, videoId, 'comment on unlisted video')
+ await servers[0].comments.createThread({ videoId: id, text: 'comment on unlisted video' })
}
await waitJobs(servers)
@@ -118,18 +94,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].feed.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].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 json = await getJSONfeed(servers[0].url, feed)
- expect(JSON.parse(json.text)).to.be.jsonSchema({ type: 'object' })
+ const jsonText = await servers[0].feed.getJSON({ feed })
+ expect(JSON.parse(jsonText)).to.be.jsonSchema({ type: 'object' })
}
})
})
@@ -138,10 +114,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.feed.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 +129,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.feed.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 +142,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].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')
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].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')
expect(jsonObj.items[0].author.name).to.equal('john')
@@ -183,15 +159,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.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 getJSONfeed(server.url, 'videos', { accountName: 'john@localhost:' + servers[0].port })
- const jsonObj = JSON.parse(json.text)
+ 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')
}
@@ -200,16 +176,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].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')
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].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')
expect(jsonObj.items[0].author.name).to.equal('john')
@@ -217,15 +193,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.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')
}
{
- 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.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')
}
@@ -235,12 +213,12 @@ 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.videos.upload({ attributes: { name: 'hls only video' } })
await waitJobs([ serverHLSOnly ])
- const json = await getJSONfeed(serverHLSOnly.url, 'videos')
- const jsonObj = JSON.parse(json.text)
+ 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
expect(jsonObj.items[0].attachments.length).to.be.eq(4)
@@ -257,9 +235,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.feed.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')
@@ -271,32 +249,32 @@ describe('Test syndication feeds', () => {
const remoteHandle = 'root@localhost:' + servers[0].port
- await addAccountToServerBlocklist(servers[1].url, servers[1].accessToken, remoteHandle)
+ await servers[1].blocklist.addToServerBlocklist({ account: remoteHandle })
{
- const json = await getJSONfeed(servers[1].url, 'video-comments', { version: 2 })
- const jsonObj = JSON.parse(json.text)
+ 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 removeAccountFromServerBlocklist(servers[1].url, servers[1].accessToken, remoteHandle)
+ await servers[1].blocklist.removeFromServerBlocklist({ account: remoteHandle })
{
- const videoUUID = (await uploadVideoAndGetId({ server: servers[1], videoName: 'server 2' })).uuid
+ const videoUUID = (await servers[1].videos.quickUpload({ name: 'server 2' })).uuid
await waitJobs(servers)
- await addVideoCommentThread(servers[0].url, servers[0].accessToken, videoUUID, 'super comment')
+ await servers[0].comments.createThread({ videoId: videoUUID, text: '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].feed.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)
+ await servers[1].blocklist.addToMyBlocklist({ account: remoteHandle })
{
- const json = await getJSONfeed(servers[1].url, 'video-comments', { version: 4 })
- const jsonObj = JSON.parse(json.text)
+ 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)
}
})
@@ -308,66 +286,64 @@ 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)
+ await servers[0].users.create({ username: attr.username, password: attr.password })
+ const feeduserAccessToken = await servers[0].login.getAccessToken(attr)
{
- const res = await getMyUserInformation(servers[0].url, feeduserAccessToken)
- const user: User = res.body
+ const user = await servers[0].users.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].users.getMyScopedTokens({ token: feeduserAccessToken })
feeduserFeedToken = token.feedToken
}
{
- const res = await listUserSubscriptionVideos(servers[0].url, feeduserAccessToken)
- expect(res.body.total).to.equal(0)
+ const body = await servers[0].subscriptions.listVideos({ token: feeduserAccessToken })
+ expect(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].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
}
})
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].feed.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].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 res = await listUserSubscriptionVideos(servers[0].url, userAccessToken)
- expect(res.body.total).to.equal(0)
+ const body = await servers[0].subscriptions.listVideos({ token: userAccessToken })
+ expect(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].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
})
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].subscriptions.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].subscriptions.listVideos({ token: userAccessToken })
+ expect(body.total).to.equal(1)
+ expect(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].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
}
})
@@ -375,36 +351,33 @@ 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].subscriptions.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].subscriptions.listVideos({ token: userAccessToken })
+ expect(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].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 renewUserScopedTokens(servers[0].url, userAccessToken)
+ await servers[0].users.renewMyScopedTokens({ token: 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].feed.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].users.getMyScopedTokens({ token: userAccessToken })
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].feed.getJSON({ feed: 'subscriptions', query })
})
})
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/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/misc-endpoints.ts b/server/tests/misc-endpoints.ts
index 09e5afcf9..4968eef08 100644
--- a/server/tests/misc-endpoints.ts
+++ b/server/tests/misc-endpoints.ts
@@ -2,28 +2,18 @@
import 'mocha'
import * as chai from 'chai'
-import {
- addVideoChannel,
- cleanupTests,
- createUser,
- flushAndRunServer,
- makeGetRequest,
- ServerInfo,
- setAccessTokensToServers,
- uploadVideo
-} from '../../shared/extra-utils'
-import { VideoPrivacy } from '../../shared/models/videos'
-import { HttpStatusCode } from '@shared/core-utils'
+import { cleanupTests, createSingleServer, makeGetRequest, PeerTubeServer, setAccessTokensToServers } from '@shared/extra-utils'
+import { HttpStatusCode, 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 ])
})
@@ -33,7 +23,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')
@@ -43,7 +33,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')
@@ -55,7 +45,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')
@@ -65,7 +55,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')
@@ -75,7 +65,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')
@@ -88,7 +78,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
@@ -113,7 +103,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')
@@ -123,7 +113,7 @@ describe('Test misc endpoints', function () {
await makeGetRequest({
url: server.url,
path: '/security.txt',
- statusCodeExpected: HttpStatusCode.MOVED_PERMANENTLY_301
+ expectedStatus: HttpStatusCode.MOVED_PERMANENTLY_301
})
})
@@ -131,7 +121,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')
@@ -146,7 +136,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"')
@@ -157,7 +147,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"')
@@ -167,20 +157,20 @@ 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.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 addVideoChannel(server.url, server.accessToken, { name: 'channel1', displayName: 'channel 1' })
- await addVideoChannel(server.url, server.accessToken, { 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 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.users.create({ username: 'user1', password: 'password' })
+ await server.users.create({ username: 'user2', password: 'password' })
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/action-hooks.ts b/server/tests/plugins/action-hooks.ts
index 0f57ef7fe..4c1bc7d06 100644
--- a/server/tests/plugins/action-hooks.ts
+++ b/server/tests/plugins/action-hooks.ts
@@ -1,63 +1,38 @@
/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */
import 'mocha'
-import { ServerHookName, VideoPlaylistPrivacy, VideoPrivacy } from '@shared/models'
-import {
- addVideoCommentReply,
- addVideoCommentThread,
- addVideoInPlaylist,
- blockUser,
- createLive,
- createUser,
- createVideoPlaylist,
- deleteVideoComment,
- getPluginTestPath,
- installPlugin,
- registerUser,
- removeUser,
- setAccessTokensToServers,
- setDefaultVideoChannel,
- unblockUser,
- updateUser,
- updateVideo,
- uploadVideo,
- userLogin,
- viewVideo
-} from '../../../shared/extra-utils'
import {
cleanupTests,
- flushAndRunMultipleServers,
+ createMultipleServers,
killallServers,
- reRunServer,
- ServerInfo,
- waitUntilLog
-} from '../../../shared/extra-utils/server/servers'
+ PeerTubeServer,
+ PluginsCommand,
+ 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
function checkHook (hook: ServerHookName) {
- return waitUntilLog(servers[0], 'Run hook ' + hook)
+ return servers[0].servers.waitUntilLog('Run hook ' + hook)
}
before(async function () {
this.timeout(30000)
- servers = await flushAndRunMultipleServers(2)
+ servers = await createMultipleServers(2)
await setAccessTokensToServers(servers)
await setDefaultVideoChannel(servers)
- await installPlugin({
- url: servers[0].url,
- accessToken: servers[0].accessToken,
- path: getPluginTestPath()
- })
+ await servers[0].plugins.install({ path: PluginsCommand.getPluginTestPath() })
- killallServers([ servers[0] ])
+ await killallServers([ servers[0] ])
- await reRunServer(servers[0], {
+ await servers[0].run({
live: {
enabled: true
}
@@ -73,20 +48,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].videos.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].videos.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].videos.view({ id: videoUUID })
await checkHook('action:api.video.viewed')
})
@@ -98,10 +73,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 createLive(servers[0].url, servers[0].accessToken, attributes)
+ await servers[0].live.create({ fields: attributes })
await checkHook('action:api.live-video.created')
})
@@ -109,20 +84,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].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 addVideoCommentReply(servers[0].url, servers[0].accessToken, videoUUID, threadId, '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 deleteVideoComment(servers[0].url, servers[0].accessToken, videoUUID, threadId)
+ await servers[0].comments.delete({ videoId: videoUUID, commentId: threadId })
await checkHook('action:api.video-comment.deleted')
})
@@ -132,49 +107,44 @@ 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].users.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].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 userLogin(servers[0], { username: 'created_user', password: 'super_password' })
+ await servers[0].login.login({ user: { username: 'created_user' } })
await checkHook('action:api.user.oauth2-got-token')
})
it('Should run action:api.user.blocked', async function () {
- await blockUser(servers[0].url, userId, servers[0].accessToken)
+ await servers[0].users.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].users.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].users.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].users.remove({ userId })
await checkHook('action:api.user.deleted')
})
@@ -186,30 +156,23 @@ 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].playlists.create({
+ attributes: {
displayName: 'My playlist',
privacy: VideoPlaylistPrivacy.PRIVATE
}
})
- playlistId = res.body.videoPlaylist.id
+ playlistId = id
}
{
- const res = await uploadVideo(servers[0].url, servers[0].accessToken, { name: 'my super name' })
- videoId = res.body.video.id
+ 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 addVideoInPlaylist({
- url: servers[0].url,
- token: servers[0].accessToken,
- playlistId,
- elementAttrs: { 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 5addb45c7..f3e018d43 100644
--- a/server/tests/plugins/external-auth.ts
+++ b/server/tests/plugins/external-auth.ts
@@ -2,44 +2,32 @@
import 'mocha'
import { expect } from 'chai'
-import { ServerConfig, User, UserRole } from '@shared/models'
import {
+ cleanupTests,
+ createSingleServer,
decodeQueryString,
- getConfig,
- getExternalAuth,
- getMyUserInformation,
- getPluginTestPath,
- installPlugin,
- loginUsingExternalToken,
- logout,
- refreshToken,
+ PeerTubeServer,
+ PluginsCommand,
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
+} from '@shared/extra-utils'
+import { HttpStatusCode, UserRole } from '@shared/models'
async function loginExternal (options: {
- server: ServerInfo
+ server: PeerTubeServer
npmName: string
authName: string
username: string
query?: any
- statusCodeExpected?: HttpStatusCode
- statusCodeExpectedStep2?: HttpStatusCode
+ expectedStatus?: HttpStatusCode
+ expectedStatusStep2?: HttpStatusCode
}) {
- const res = await getExternalAuth({
- url: options.server.url,
+ const res = await options.server.plugins.getExternalAuth({
npmName: options.npmName,
npmVersion: '0.0.1',
authName: options.authName,
query: options.query,
- statusCodeExpected: options.statusCodeExpected || HttpStatusCode.FOUND_302
+ expectedStatus: options.expectedStatus || HttpStatusCode.FOUND_302
})
if (res.status !== HttpStatusCode.FOUND_302) return
@@ -47,18 +35,17 @@ 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.login.loginUsingExternalToken({
+ username: options.username,
+ externalAuthToken: externalAuthToken as string,
+ expectedStatus: options.expectedStatusStep2
+ })
return resLogin.body
}
describe('Test external auth plugins', function () {
- let server: ServerInfo
+ let server: PeerTubeServer
let cyanAccessToken: string
let cyanRefreshToken: string
@@ -71,22 +58,16 @@ 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' ]) {
- await installPlugin({
- url: server.url,
- accessToken: server.accessToken,
- path: getPluginTestPath('-external-auth-' + suffix)
- })
+ await server.plugins.install({ path: PluginsCommand.getPluginTestPath('-external-auth-' + suffix) })
}
})
it('Should display the correct configuration', async function () {
- const res = await getConfig(server.url)
-
- const config: ServerConfig = res.body
+ const config = await server.config.getConfig()
const auths = config.plugin.registeredExternalAuths
expect(auths).to.have.lengthOf(8)
@@ -98,15 +79,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.plugins.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
@@ -121,13 +101,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.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 () {
- await loginUsingExternalToken(server, '', externalAuthToken, HttpStatusCode.BAD_REQUEST_400)
- await loginUsingExternalToken(server, '', externalAuthToken, HttpStatusCode.BAD_REQUEST_400)
+ const command = server.login
+
+ 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 () {
@@ -135,9 +119,13 @@ describe('Test external auth plugins', function () {
await wait(5000)
- await loginUsingExternalToken(server, 'cyan', externalAuthToken, HttpStatusCode.BAD_REQUEST_400)
+ await server.login.loginUsingExternalToken({
+ username: 'cyan',
+ externalAuthToken,
+ expectedStatus: HttpStatusCode.BAD_REQUEST_400
+ })
- await waitUntilLog(server, '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 () {
@@ -157,9 +145,7 @@ describe('Test external auth plugins', function () {
}
{
- const res = await getMyUserInformation(server.url, cyanAccessToken)
-
- const body: User = res.body
+ 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')
@@ -181,9 +167,7 @@ describe('Test external auth plugins', function () {
}
{
- const res = await getMyUserInformation(server.url, kefkaAccessToken)
-
- const body: User = res.body
+ 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')
@@ -193,43 +177,39 @@ 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.login.refreshToken({ refreshToken: cyanRefreshToken })
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.users.getMyInfo({ token: cyanAccessToken })
+ expect(body.username).to.equal('cyan')
}
{
- await refreshToken(server, kefkaRefreshToken, HttpStatusCode.BAD_REQUEST_400)
+ await server.login.refreshToken({ refreshToken: kefkaRefreshToken, expectedStatus: HttpStatusCode.BAD_REQUEST_400 })
}
})
it('Should update Cyan profile', async function () {
- await updateMyUser({
- url: server.url,
- accessToken: cyanAccessToken,
+ await server.users.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.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 logout(server.url, cyanAccessToken)
+ await server.login.logout({ token: cyanAccessToken })
})
it('Should have logged out Cyan', async function () {
- await waitUntilLog(server, 'On logout cyan')
+ await server.servers.waitUntilLog('On logout cyan')
- await getMyUserInformation(server.url, cyanAccessToken, 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 () {
@@ -247,9 +227,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.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')
@@ -257,12 +235,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.users.updateMe({
+ token: cyanAccessToken,
email: 'toto@example.com',
currentPassword: 'toto',
- statusCodeExpected: HttpStatusCode.BAD_REQUEST_400
+ expectedStatus: HttpStatusCode.BAD_REQUEST_400
})
})
@@ -271,18 +248,16 @@ describe('Test external auth plugins', function () {
await wait(5000)
- await getMyUserInformation(server.url, kefkaAccessToken, 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 updatePluginSettings({
- url: server.url,
- accessToken: server.accessToken,
+ await server.plugins.updateSettings({
npmName: 'peertube-plugin-test-external-auth-one',
settings: { disableKefka: true }
})
- await userLogin(server, { username: 'kefka', password: 'fake' }, HttpStatusCode.BAD_REQUEST_400)
+ await server.login.login({ user: { username: 'kefka', password: 'fake' }, expectedStatus: HttpStatusCode.BAD_REQUEST_400 })
await loginExternal({
server,
@@ -292,14 +267,12 @@ describe('Test external auth plugins', function () {
username: 'kefka'
},
username: 'kefka',
- statusCodeExpected: HttpStatusCode.NOT_FOUND_404
+ expectedStatus: HttpStatusCode.NOT_FOUND_404
})
})
it('Should have disabled this auth', async function () {
- const res = await getConfig(server.url)
-
- const config: ServerConfig = res.body
+ const config = await server.config.getConfig()
const auths = config.plugin.registeredExternalAuths
expect(auths).to.have.lengthOf(7)
@@ -309,11 +282,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.plugins.uninstall({ npmName: 'peertube-plugin-test-external-auth-one' })
await loginExternal({
server,
@@ -323,12 +292,12 @@ describe('Test external auth plugins', function () {
username: 'cyan'
},
username: 'cyan',
- statusCodeExpected: HttpStatusCode.NOT_FOUND_404
+ expectedStatus: 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.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 () {
@@ -337,7 +306,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({
@@ -345,31 +314,24 @@ 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
})
})
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.users.create({ username: 'existing_user', password: 'super_password' })
await loginExternal({
server,
npmName: 'test-external-auth-two',
authName: 'external-auth-6',
username: 'existing_user',
- statusCodeExpectedStep2: HttpStatusCode.BAD_REQUEST_400
+ expectedStatusStep2: HttpStatusCode.BAD_REQUEST_400
})
})
it('Should display the correct configuration', async function () {
- const res = await getConfig(server.url)
-
- const config: ServerConfig = res.body
+ const config = await server.config.getConfig()
const auths = config.plugin.registeredExternalAuths
expect(auths).to.have.lengthOf(6)
@@ -390,9 +352,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.login.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 () {
@@ -403,8 +364,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.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 644b41dea..c00ac8f91 100644
--- a/server/tests/plugins/filter-hooks.ts
+++ b/server/tests/plugins/filter-hooks.ts
@@ -2,192 +2,152 @@
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 {
- addVideoCommentReply,
- addVideoCommentThread,
- advancedVideoPlaylistSearch,
- advancedVideosSearch,
- createLive,
- createVideoPlaylist,
+ cleanupTests,
+ createMultipleServers,
doubleFollow,
- getAccountVideos,
- getConfig,
- getMyVideos,
- getPluginTestPath,
- getVideo,
- getVideoChannelVideos,
- getVideoCommentThreads,
- getVideoPlaylist,
- getVideosList,
- getVideosListPagination,
- getVideoThreadComments,
- getVideoWithToken,
- installPlugin,
+ FIXTURE_URLS,
makeRawRequest,
- registerUser,
+ PeerTubeServer,
+ PluginsCommand,
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'
-import {
- VideoCommentThreadTree,
- VideoDetails,
- VideoImport,
- VideoImportState,
- VideoPlaylist,
- VideoPlaylistPrivacy,
- VideoPrivacy
-} from '../../../shared/models/videos'
+} from '@shared/extra-utils'
+import { HttpStatusCode, VideoDetails, VideoImportState, VideoPlaylist, VideoPlaylistPrivacy, VideoPrivacy } from '@shared/models'
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])
- 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].plugins.install({ path: PluginsCommand.getPluginTestPath() })
+ await servers[0].plugins.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].videos.upload({ attributes: { name: 'default video ' + i } })
}
- const res = await getVideosList(servers[0].url)
- videoUUID = res.body.data[0].uuid
+ const { data } = await servers[0].videos.list()
+ videoUUID = 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].config.updateCustomSubConfig({
+ newConfig: {
+ live: { enabled: true },
+ signup: { enabled: true },
+ import: {
+ videos: {
+ http: { enabled: true },
+ torrent: { enabled: true }
+ }
}
}
})
})
it('Should run filter:api.videos.list.params', async function () {
- const res = await getVideosListPagination(servers[0].url, 0, 2)
+ const { data } = await servers[0].videos.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].videos.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].videos.listByAccount({ handle: '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].videos.listByAccount({ handle: '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].videos.listByChannel({ handle: '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].videos.listByChannel({ handle: '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].videos.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].videos.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].videos.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].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 createLive(servers[0].url, servers[0].accessToken, attributes, 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 baseAttributes = {
+ const attributes = {
name: 'normal title',
privacy: VideoPrivacy.PUBLIC,
- channelId: servers[0].videoChannel.id,
- targetUrl: getGoodVideoUrl() + 'bad'
+ channelId: servers[0].store.channel.id,
+ targetUrl: FIXTURE_URLS.goodVideo + 'bad'
}
- await importVideo(servers[0].url, servers[0].accessToken, baseAttributes, 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 baseAttributes = {
+ 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 importVideo(servers[0].url, servers[0].accessToken, baseAttributes, 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 () {
@@ -196,21 +156,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()
+ channelId: servers[0].store.channel.id,
+ targetUrl: FIXTURE_URLS.goodVideo
}
- const res = await importVideo(servers[0].url, servers[0].accessToken, baseAttributes)
- videoImportId = res.body.id
+ const body = await servers[0].imports.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].imports.getMyVideoImports()
+ const videoImports = body.data
const videoImport = videoImports.find(i => i.id === videoImportId)
@@ -225,21 +185,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,
+ channelId: servers[0].store.channel.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].imports.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].imports.getMyVideoImports()
const videoImport = videoImports.find(i => i.id === videoImportId)
@@ -249,60 +208,63 @@ 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].comments.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
+ const created = await servers[0].comments.createThread({ videoId: videoUUID, text: 'thread' })
+ threadId = created.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)
+ await servers[0].comments.addReply({
+ videoId: videoUUID,
+ toCommentId: threadId,
+ text: 'comment with bad word',
+ expectedStatus: HttpStatusCode.FORBIDDEN_403
+ })
+ await servers[0].comments.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].comments.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].comments.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].comments.getThread({ videoId: videoUUID, threadId })
- const thread = res.body as VideoCommentThreadTree
expect(thread.comment.text.endsWith(' <3')).to.be.true
})
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)
- const video: VideoDetails = res.body
+ async function checkIsBlacklisted (id: number | string, value: boolean) {
+ const video = await servers[0].videos.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, true)
+ const { uuid } = await servers[0].videos.upload({ attributes: { name: 'video please blacklist me' } })
+ await checkIsBlacklisted(uuid, true)
})
it('Should blacklist on import', async function () {
@@ -310,60 +272,62 @@ describe('Test plugin filter hooks', function () {
const attributes = {
name: 'video please blacklist me',
- targetUrl: getGoodVideoUrl(),
- channelId: servers[0].videoChannel.id
+ targetUrl: FIXTURE_URLS.goodVideo,
+ channelId: servers[0].store.channel.id
}
- const res = await importVideo(servers[0].url, servers[0].accessToken, attributes)
- await checkIsBlacklisted(res, true)
+ const body = await servers[0].imports.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)
+ const { uuid } = await servers[0].videos.upload({ attributes: { name: 'video' } })
+ await checkIsBlacklisted(uuid, false)
- await updateVideo(servers[0].url, servers[0].accessToken, videoId, { name: 'please blacklist me' })
- await checkIsBlacklisted(res, true)
+ 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 res = await uploadVideo(servers[1].url, servers[1].accessToken, { name: 'remote please blacklist me' })
+ const { uuid } = await servers[1].videos.upload({ attributes: { name: 'remote please blacklist me' } })
await waitJobs(servers)
- await checkIsBlacklisted(res, 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].videos.upload({ attributes: { name: 'video' } })
await waitJobs(servers)
- const videoId = res.body.video.uuid
- await checkIsBlacklisted(res, false)
+ await checkIsBlacklisted(uuid, false)
- await updateVideo(servers[1].url, servers[1].accessToken, videoId, { name: 'please blacklist me' })
+ await servers[1].videos.update({ id: uuid, attributes: { name: 'please blacklist me' } })
await waitJobs(servers)
- await checkIsBlacklisted(res, true)
+ await checkIsBlacklisted(uuid, true)
})
})
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].config.getConfig()
+ expect(body.signup.allowed).to.be.true
})
it('Should allow a signup', async function () {
- await registerUser(servers[0].url, 'john', 'password')
+ await servers[0].users.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].users.register({
+ username: 'jma',
+ password: 'password',
+ expectedStatus: HttpStatusCode.FORBIDDEN_403
+ })
expect(res.body.error).to.equal('No jma')
})
@@ -375,13 +339,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].config.updateCustomSubConfig({
+ newConfig: {
+ transcoding: {
+ webtorrent: {
+ enabled: true
+ },
+ hls: {
+ enabled: true
+ }
}
}
})
@@ -389,15 +355,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].videos.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].videos.get({ id: uuid }))
}
})
@@ -437,25 +402,26 @@ 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].config.updateCustomSubConfig({
+ newConfig: {
+ transcoding: {
+ enabled: false
+ }
}
})
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].videos.quickUpload({ name: name })).uuid
+ embedVideos.push(await servers[0].videos.get({ id: uuid }))
}
{
- 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].store.channel.id, privacy: VideoPlaylistPrivacy.PUBLIC }
+ const { id } = await servers[0].playlists.create({ attributes })
- const resPlaylist = await getVideoPlaylist(servers[0].url, res.body.videoPlaylist.id)
- embedPlaylists.push(resPlaylist.body)
+ const playlist = await servers[0].playlists.get({ playlistId: id })
+ embedPlaylists.push(playlist)
}
}
})
@@ -474,78 +440,92 @@ 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].config.updateCustomSubConfig({
+ newConfig: {
+ search: {
+ searchIndex: {
+ enabled: true,
+ isDefaultSearch: false,
+ disableLocalSearch: false
+ }
}
}
})
})
it('Should run filter:api.search.videos.local.list.{params,result}', async function () {
- await advancedVideosSearch(servers[0].url, {
- search: 'Sun Quan'
+ await servers[0].search.advancedVideoSearch({
+ search: {
+ search: 'Sun Quan'
+ }
})
- 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].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 advancedVideosSearch(servers[0].url, {
- search: 'Sun Quan',
- searchTarget: 'search-index'
+ await servers[0].search.advancedVideoSearch({
+ search: {
+ search: 'Sun Quan',
+ searchTarget: 'search-index'
+ }
})
- 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].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 advancedVideoChannelSearch(servers[0].url, {
- search: 'Sun Ce'
+ await servers[0].search.advancedChannelSearch({
+ search: {
+ search: 'Sun Ce'
+ }
})
- 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].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 advancedVideoChannelSearch(servers[0].url, {
- search: 'Sun Ce',
- searchTarget: 'search-index'
+ await servers[0].search.advancedChannelSearch({
+ search: {
+ search: 'Sun Ce',
+ searchTarget: 'search-index'
+ }
})
- 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].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 advancedVideoPlaylistSearch(servers[0].url, {
- search: 'Sun Jian'
+ await servers[0].search.advancedPlaylistSearch({
+ search: {
+ search: 'Sun Jian'
+ }
})
- 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].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 advancedVideoPlaylistSearch(servers[0].url, {
- search: 'Sun Jian',
- searchTarget: 'search-index'
+ await servers[0].search.advancedPlaylistSearch({
+ search: {
+ search: 'Sun Jian',
+ searchTarget: 'search-index'
+ }
})
- 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].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 4fa8caa3a..95c0cd687 100644
--- a/server/tests/plugins/html-injection.ts
+++ b/server/tests/plugins/html-injection.ts
@@ -4,31 +4,32 @@ import 'mocha'
import * as chai from 'chai'
import {
cleanupTests,
- flushAndRunServer,
- getPluginsCSS,
- installPlugin,
+ createSingleServer,
makeHTMLRequest,
- ServerInfo,
- setAccessTokensToServers,
- uninstallPlugin
+ PeerTubeServer,
+ PluginsCommand,
+ 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
})
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..fde0166f9 100644
--- a/server/tests/plugins/id-and-pass-auth.ts
+++ b/server/tests/plugins/id-and-pass-auth.ts
@@ -1,24 +1,12 @@
/* 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 {
- getMyUserInformation,
- getPluginTestPath,
- installPlugin,
- logout,
- 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'
+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: ServerInfo
+ let server: PeerTubeServer
let crashAccessToken: string
let crashRefreshToken: string
@@ -29,22 +17,16 @@ 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' ]) {
- await installPlugin({
- url: server.url,
- accessToken: server.accessToken,
- path: 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 res = await getConfig(server.url)
-
- const config: ServerConfig = res.body
+ const config = await server.config.getConfig()
const auths = config.plugin.registeredIdAndPassAuths
expect(auths).to.have.lengthOf(8)
@@ -56,15 +38,14 @@ describe('Test id and pass auth plugins', function () {
})
it('Should not login', async function () {
- await userLogin(server, { username: 'toto', password: 'password' }, 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 userLogin(server, { username: 'spyro', password: 'spyro password' })
+ const accessToken = await server.login.getAccessToken({ username: 'spyro', password: 'spyro password' })
- const res = await getMyUserInformation(server.url, accessToken)
+ const body = await server.users.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)
@@ -72,15 +53,14 @@ 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.login.login({ user: { username: 'crash', password: 'crash password' } })
+ crashAccessToken = body.access_token
+ crashRefreshToken = body.refresh_token
}
{
- const res = await getMyUserInformation(server.url, crashAccessToken)
+ const body = await server.users.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)
@@ -89,15 +69,14 @@ 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.login.login({ user: { username: 'laguna', password: 'laguna password' } })
+ lagunaAccessToken = body.access_token
+ lagunaRefreshToken = body.refresh_token
}
{
- const res = await getMyUserInformation(server.url, lagunaAccessToken)
+ const body = await server.users.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)
@@ -106,51 +85,47 @@ 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.login.refreshToken({ refreshToken: crashRefreshToken })
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.users.getMyInfo({ token: crashAccessToken })
+ expect(body.username).to.equal('crash')
}
{
- await refreshToken(server, lagunaRefreshToken, 400)
+ await server.login.refreshToken({ refreshToken: lagunaRefreshToken, expectedStatus: HttpStatusCode.BAD_REQUEST_400 })
}
})
it('Should update Crash profile', async function () {
- await updateMyUser({
- url: server.url,
- accessToken: crashAccessToken,
+ await server.users.updateMe({
+ token: crashAccessToken,
displayName: 'Beautiful Crash',
description: 'Mutant eastern barred bandicoot'
})
- const res = await getMyUserInformation(server.url, crashAccessToken)
+ const body = await server.users.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')
})
it('Should logout Crash', async function () {
- await logout(server.url, crashAccessToken)
+ await server.login.logout({ token: crashAccessToken })
})
it('Should have logged out Crash', async function () {
- await waitUntilLog(server, 'On logout for auth 1 - 2')
+ await server.servers.waitUntilLog('On logout for auth 1 - 2')
- await getMyUserInformation(server.url, crashAccessToken, 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 userLogin(server, { username: 'crash', password: 'crash password' })
+ crashAccessToken = await server.login.getAccessToken({ username: 'crash', password: 'crash password' })
- const res = await getMyUserInformation(server.url, crashAccessToken)
+ const body = await server.users.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')
@@ -162,39 +137,38 @@ describe('Test id and pass auth plugins', function () {
await wait(5000)
- await getMyUserInformation(server.url, lagunaAccessToken, 401)
+ await server.users.getMyInfo({ token: lagunaAccessToken, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 })
})
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')
+ const command = server.login
- await userLogin(server, { username: 'kiros', password: 'kiros password' }, 400)
- await waitUntilLog(server, 'valid display name')
+ await command.login({ user: { username: 'ward', password: 'ward password' }, expectedStatus: HttpStatusCode.BAD_REQUEST_400 })
+ await server.servers.waitUntilLog('valid username')
- await userLogin(server, { username: 'raine', password: 'raine password' }, 400)
- await waitUntilLog(server, 'valid role')
+ await command.login({ user: { username: 'kiros', password: 'kiros password' }, expectedStatus: HttpStatusCode.BAD_REQUEST_400 })
+ await server.servers.waitUntilLog('valid display name')
- await userLogin(server, { username: 'ellone', password: 'elonne password' }, 400)
- await waitUntilLog(server, 'valid email')
+ await command.login({ user: { username: 'raine', password: 'raine password' }, expectedStatus: HttpStatusCode.BAD_REQUEST_400 })
+ await server.servers.waitUntilLog('valid role')
+
+ await command.login({ user: { username: 'ellone', password: 'elonne password' }, expectedStatus: HttpStatusCode.BAD_REQUEST_400 })
+ await server.servers.waitUntilLog('valid email')
})
it('Should unregister spyro-auth and do not login existing Spyro', async function () {
- await updatePluginSettings({
- url: server.url,
- accessToken: server.accessToken,
+ await server.plugins.updateSettings({
npmName: 'peertube-plugin-test-id-pass-auth-one',
settings: { disableSpyro: true }
})
- await userLogin(server, { username: 'spyro', password: 'spyro password' }, 400)
- await userLogin(server, { username: 'spyro', password: 'fake' }, 400)
+ 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 res = await getConfig(server.url)
-
- const config: ServerConfig = res.body
+ const config = await server.config.getConfig()
const auths = config.plugin.registeredIdAndPassAuths
expect(auths).to.have.lengthOf(7)
@@ -204,19 +178,16 @@ 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.plugins.uninstall({ npmName: 'peertube-plugin-test-id-pass-auth-one' })
- await userLogin(server, { username: 'crash', password: 'crash password' }, 400)
+ await server.login.login({
+ user: { username: 'crash', password: 'crash password' },
+ expectedStatus: HttpStatusCode.BAD_REQUEST_400
+ })
})
it('Should display the correct configuration', async function () {
- const res = await getConfig(server.url)
-
- const config: ServerConfig = res.body
+ const config = await server.config.getConfig()
const auths = config.plugin.registeredIdAndPassAuths
expect(auths).to.have.lengthOf(6)
@@ -226,13 +197,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 { data } = await server.users.list()
- const users: User[] = res.body.data
-
- 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/tests/plugins/plugin-helpers.ts b/server/tests/plugins/plugin-helpers.ts
index 0296d6eb7..242994273 100644
--- a/server/tests/plugins/plugin-helpers.ts
+++ b/server/tests/plugins/plugin-helpers.ts
@@ -1,25 +1,22 @@
/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */
import 'mocha'
+import { expect } from 'chai'
import {
checkVideoFilesWereRemoved,
+ cleanupTests,
+ createMultipleServers,
doubleFollow,
- getPluginTestPath,
- getVideo,
- installPlugin,
+ makeGetRequest,
makePostBodyRequest,
+ PeerTubeServer,
+ PluginsCommand,
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'
+ waitJobs
+} from '@shared/extra-utils'
+import { HttpStatusCode } from '@shared/models'
-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)
@@ -27,54 +24,50 @@ function postCommand (server: ServerInfo, 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
})
}
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])
- await installPlugin({
- url: servers[0].url,
- accessToken: servers[0].accessToken,
- path: getPluginTestPath('-four')
- })
+ await servers[0].plugins.install({ path: PluginsCommand.getPluginTestPath('-four') })
})
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].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 waitUntilLog(servers[0], `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 waitUntilLog(servers[0], `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 () {
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
@@ -85,7 +78,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].servers.waitUntilLog('server actor name is peertube')
})
})
@@ -95,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/')
@@ -107,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)
@@ -120,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
})
})
@@ -129,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')
@@ -147,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 servers[0].videos.quickUpload({ name: 'video server 1' })
videoUUIDServer1 = res.uuid
}
{
- await uploadVideoAndGetId({ server: servers[1], videoName: 'video server 2' })
+ await servers[1].videos.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].videos.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].videos.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].videos.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].videos.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].videos.list()
- expect(videos).to.have.lengthOf(2)
+ expect(data).to.have.lengthOf(2)
})
it('Should blacklist video', async function () {
@@ -210,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.videos.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')
}
})
@@ -226,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.videos.list()
- expect(videos).to.have.lengthOf(2)
+ expect(data).to.have.lengthOf(2)
}
})
})
@@ -238,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 servers[0].videos.quickUpload({ name: 'video1' })
videoUUID = res.uuid
})
@@ -246,25 +232,25 @@ describe('Test plugin helpers', function () {
this.timeout(40000)
// Should not throw -> video exists
- await getVideo(servers[0].url, videoUUID)
+ await servers[0].videos.get({ id: videoUUID })
// Should delete the video
- await viewVideo(servers[0].url, videoUUID)
+ await servers[0].videos.view({ id: videoUUID })
- await waitUntilLog(servers[0], '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 getVideo(servers[0].url, videoUUID)
+ await servers[0].videos.get({ id: videoUUID })
throw new Error('Video exists')
} catch (err) {
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].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 24e6a1e83..b1ac9e2fe 100644
--- a/server/tests/plugins/plugin-router.ts
+++ b/server/tests/plugins/plugin-router.ts
@@ -1,19 +1,20 @@
/* 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 {
- getPluginTestPath,
- installPlugin,
+ cleanupTests,
+ createSingleServer,
makeGetRequest,
makePostBodyRequest,
- setAccessTokensToServers, uninstallPlugin
-} from '../../../shared/extra-utils'
-import { expect } from 'chai'
-import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes'
+ PeerTubeServer,
+ PluginsCommand,
+ setAccessTokensToServers
+} from '@shared/extra-utils'
+import { HttpStatusCode } from '@shared/models'
describe('Test plugin helpers', function () {
- let server: ServerInfo
+ let server: PeerTubeServer
const basePaths = [
'/plugins/test-five/router/',
'/plugins/test-five/0.0.1/router/'
@@ -22,14 +23,10 @@ describe('Test plugin helpers', function () {
before(async function () {
this.timeout(30000)
- server = await flushAndRunServer(1)
+ server = await createSingleServer(1)
await setAccessTokensToServers([ server ])
- await installPlugin({
- url: server.url,
- accessToken: server.accessToken,
- path: getPluginTestPath('-five')
- })
+ await server.plugins.install({ path: PluginsCommand.getPluginTestPath('-five') })
})
it('Should answer "pong"', async function () {
@@ -37,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')
@@ -50,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)
@@ -58,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)
@@ -77,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)
@@ -85,24 +82,20 @@ 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.plugins.uninstall({ npmName: 'peertube-plugin-test-five' })
for (const path of basePaths) {
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 3c46b2585..e20c36dba 100644
--- a/server/tests/plugins/plugin-storage.ts
+++ b/server/tests/plugins/plugin-storage.ts
@@ -4,37 +4,32 @@ import 'mocha'
import { expect } from 'chai'
import { pathExists, readdir, readFile } from 'fs-extra'
import { join } from 'path'
-import { HttpStatusCode } from '@shared/core-utils'
import {
- buildServerDirectory,
- getPluginTestPath,
- installPlugin,
+ cleanupTests,
+ createSingleServer,
makeGetRequest,
- setAccessTokensToServers,
- uninstallPlugin
-} from '../../../shared/extra-utils'
-import { cleanupTests, flushAndRunServer, ServerInfo, waitUntilLog } from '../../../shared/extra-utils/server/servers'
+ PeerTubeServer,
+ PluginsCommand,
+ setAccessTokensToServers
+} from '@shared/extra-utils'
+import { HttpStatusCode } from '@shared/models'
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 installPlugin({
- url: server.url,
- accessToken: server.accessToken,
- path: getPluginTestPath('-six')
- })
+ await server.plugins.install({ path: PluginsCommand.getPluginTestPath('-six') })
})
describe('DB storage', function () {
it('Should correctly store a subkey', async function () {
- await waitUntilLog(server, 'superkey stored value is toto')
+ await server.servers.waitUntilLog('superkey stored value is toto')
})
})
@@ -50,12 +45,12 @@ describe('Test plugin storage', function () {
}
before(function () {
- dataPath = buildServerDirectory(server, '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 = buildServerDirectory(server, 'plugins/data')
+ const dataPath = server.servers.buildDirectory('plugins/data')
const pluginDataPath = join(dataPath, 'peertube-plugin-test-six')
expect(await pathExists(dataPath)).to.be.true
@@ -68,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()
@@ -76,22 +71,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.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 installPlugin({
- url: server.url,
- accessToken: server.accessToken,
- path: 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 eefb2294d..0bf1fab01 100644
--- a/server/tests/plugins/plugin-transcoding.ts
+++ b/server/tests/plugins/plugin-transcoding.ts
@@ -4,77 +4,72 @@ 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,
- createLive,
- getConfig,
- getPluginTestPath,
- getVideo,
- installPlugin,
- sendRTMPStreamInVideo,
+ cleanupTests,
+ createSingleServer,
+ PeerTubeServer,
+ PluginsCommand,
setAccessTokensToServers,
setDefaultVideoChannel,
testFfmpegStreamError,
- uninstallPlugin,
- updateCustomSubConfig,
- uploadVideoAndGetId,
- waitJobs,
- waitUntilLivePublished
-} from '../../../shared/extra-utils'
-import { cleanupTests, flushAndRunServer, ServerInfo } from '../../../shared/extra-utils/server/servers'
+ waitJobs
+} 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.videoChannel.id,
+ channelId: server.store.channel.id,
privacy: VideoPrivacy.PUBLIC
}
- const res = await createLive(server.url, server.accessToken, liveAttributes)
- return res.body.video.uuid
+ const { uuid } = await server.live.create({ fields: liveAttributes })
+
+ return uuid
}
-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: {
+function updateConf (server: PeerTubeServer, vodProfile: string, liveProfile: string) {
+ return server.config.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
+ }
+ }
}
}
})
}
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 ])
@@ -84,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.videos.get({ id: uuid })
const files = video.files.concat(...video.streamingPlaylists.map(p => p.files))
for (const file of files) {
@@ -109,16 +103,11 @@ describe('Test transcoding plugins', function () {
}
before(async function () {
- await installPlugin({
- url: server.url,
- accessToken: server.accessToken,
- path: getPluginTestPath('-transcoding-one')
- })
+ await server.plugins.install({ path: PluginsCommand.getPluginTestPath('-transcoding-one') })
})
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.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' ])
@@ -127,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.videos.quickUpload({ name: 'video' })).uuid
await waitJobs([ server ])
await checkVideoFPS(videoUUID, 'above', 20)
@@ -138,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.videos.quickUpload({ name: 'video' })).uuid
await waitJobs([ server ])
await checkVideoFPS(videoUUID, 'below', 12)
@@ -149,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.videos.quickUpload({ name: 'video' })).uuid
await waitJobs([ server ])
await checkVideoFPS(videoUUID, 'below', 6)
@@ -160,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.videos.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.videos.get({ id: videoUUID })
expect(video.files).to.have.lengthOf(1)
expect(video.streamingPlaylists).to.have.lengthOf(0)
})
@@ -176,8 +163,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.live.sendRTMPStreamInVideo({ videoId: liveVideoId, fixtureName: 'video_short2.webm' })
+ await server.live.waitUntilPublished({ videoId: liveVideoId })
await waitJobs([ server ])
await checkLiveFPS(liveVideoId, 'above', 20)
@@ -190,8 +177,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.live.sendRTMPStreamInVideo({ videoId: liveVideoId, fixtureName: 'video_short2.webm' })
+ await server.live.waitUntilPublished({ videoId: liveVideoId })
await waitJobs([ server ])
await checkLiveFPS(liveVideoId, 'below', 12)
@@ -204,8 +191,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.live.sendRTMPStreamInVideo({ videoId: liveVideoId, fixtureName: 'video_short2.webm' })
+ await server.live.waitUntilPublished({ videoId: liveVideoId })
await waitJobs([ server ])
await checkLiveFPS(liveVideoId, 'below', 6)
@@ -218,22 +205,21 @@ 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.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 uninstallPlugin({ url: server.url, accessToken: server.accessToken, npmName: 'peertube-plugin-test-transcoding-one' })
+ await server.plugins.uninstall({ npmName: 'peertube-plugin-test-transcoding-one' })
- const res = await getConfig(server.url)
- const config = res.body as ServerConfig
+ 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 uploadVideoAndGetId({ server, videoName: 'video' })).uuid
+ const videoUUID = (await server.videos.quickUpload({ name: 'video' })).uuid
await waitJobs([ server ])
await checkVideoFPS(videoUUID, 'above', 20)
@@ -244,11 +230,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.plugins.install({ path: PluginsCommand.getPluginTestPath('-transcoding-two') })
await updateConf(server, 'test-vod-profile', 'test-live-profile')
})
@@ -256,10 +238,10 @@ 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.videos.quickUpload({ name: 'video', fixture: 'video_short_240p.mp4' })).uuid
await waitJobs([ server ])
- const path = buildServerDirectory(server, 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')
@@ -272,8 +254,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.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 74ca82e2f..6bf2fda9b 100644
--- a/server/tests/plugins/plugin-unloading.ts
+++ b/server/tests/plugins/plugin-unloading.ts
@@ -1,42 +1,36 @@
/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */
import 'mocha'
+import { expect } from 'chai'
import {
cleanupTests,
- flushAndRunServer,
- getPluginTestPath,
+ createSingleServer,
makeGetRequest,
- installPlugin,
- uninstallPlugin,
- ServerInfo,
+ PeerTubeServer,
+ PluginsCommand,
setAccessTokensToServers
-} from '../../../shared/extra-utils'
-import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes'
-import { expect } from 'chai'
+} from '@shared/extra-utils'
+import { HttpStatusCode } from '@shared/models'
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 installPlugin({
- url: server.url,
- accessToken: server.accessToken,
- path: getPluginTestPath('-unloading')
- })
+ await server.plugins.install({ path: PluginsCommand.getPluginTestPath('-unloading') })
})
it('Should return a numeric value', async 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+$/)
@@ -47,36 +41,29 @@ 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)
})
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.plugins.uninstall({ npmName: 'peertube-plugin-test-unloading' })
await makeGetRequest({
url: server.url,
path: requestPath,
- statusCodeExpected: HttpStatusCode.NOT_FOUND_404
+ expectedStatus: HttpStatusCode.NOT_FOUND_404
})
})
it('Should return a different numeric value', async function () {
- await installPlugin({
- url: server.url,
- accessToken: server.accessToken,
- path: getPluginTestPath('-unloading')
- })
+ await server.plugins.install({ path: PluginsCommand.getPluginTestPath('-unloading') })
+
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/translations.ts b/server/tests/plugins/translations.ts
index 9fd2ba1c5..8b25c6b75 100644
--- a/server/tests/plugins/translations.ts
+++ b/server/tests/plugins/translations.ts
@@ -1,50 +1,37 @@
/* 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 {
- getPluginTestPath,
- getPluginTranslations,
- installPlugin,
- setAccessTokensToServers,
- uninstallPlugin
-} from '../../../shared/extra-utils'
+import * as chai from 'chai'
+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 ])
- await installPlugin({
- url: server.url,
- accessToken: server.accessToken,
- path: getPluginTestPath()
- })
+ command = server.plugins
- 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 +42,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 +52,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 +65,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 7b1312f88..19cba6c2c 100644
--- a/server/tests/plugins/video-constants.ts
+++ b/server/tests/plugins/video-constants.ts
@@ -1,47 +1,33 @@
/* 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 {
- createVideoPlaylist,
- getPluginTestPath,
- getVideo,
- getVideoCategories,
- getVideoLanguages,
- getVideoLicences,
- getVideoPlaylistPrivacies,
- getVideoPrivacies,
- installPlugin,
+ cleanupTests,
+ createSingleServer,
makeGetRequest,
- setAccessTokensToServers,
- uninstallPlugin,
- uploadVideo
-} from '../../../shared/extra-utils'
-import { VideoDetails, VideoPlaylistPrivacy } from '../../../shared/models/videos'
-import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes'
+ PeerTubeServer,
+ PluginsCommand,
+ setAccessTokensToServers
+} from '@shared/extra-utils'
+import { HttpStatusCode, 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 installPlugin({
- url: server.url,
- accessToken: server.accessToken,
- path: getPluginTestPath('-video-constants')
- })
+ await server.plugins.install({ path: PluginsCommand.getPluginTestPath('-video-constants') })
})
it('Should have updated languages', async function () {
- const res = await getVideoLanguages(server.url)
- const languages = res.body
+ const languages = await server.videos.getLanguages()
expect(languages['en']).to.not.exist
expect(languages['fr']).to.not.exist
@@ -52,8 +38,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.videos.getCategories()
expect(categories[1]).to.not.exist
expect(categories[2]).to.not.exist
@@ -63,8 +48,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.videos.getLicences()
expect(licences[1]).to.not.exist
expect(licences[7]).to.not.exist
@@ -74,8 +58,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.videos.getPrivacies()
expect(privacies[1]).to.exist
expect(privacies[2]).to.not.exist
@@ -84,8 +67,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.playlists.getPrivacies()
expect(playlistPrivacies[1]).to.exist
expect(playlistPrivacies[2]).to.exist
@@ -93,38 +75,30 @@ 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.videos.upload({ attributes, expectedStatus: HttpStatusCode.BAD_REQUEST_400 })
})
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.playlists.create({ attributes, expectedStatus: HttpStatusCode.BAD_REQUEST_400 })
})
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.videos.upload({ attributes })
- const res = await getVideo(server.url, resUpload.body.video.uuid)
-
- const video: VideoDetails = res.body
+ 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 uninstallPlugin({ url: server.url, accessToken: server.accessToken, npmName: 'peertube-plugin-test-video-constants' })
+ await server.plugins.uninstall({ npmName: 'peertube-plugin-test-video-constants' })
{
- const res = await getVideoLanguages(server.url)
- const languages = res.body
+ const languages = await server.videos.getLanguages()
expect(languages['en']).to.equal('English')
expect(languages['fr']).to.equal('French')
@@ -135,8 +109,7 @@ describe('Test plugin altering video constants', function () {
}
{
- const res = await getVideoCategories(server.url)
- const categories = res.body
+ const categories = await server.videos.getCategories()
expect(categories[1]).to.equal('Music')
expect(categories[2]).to.equal('Films')
@@ -146,8 +119,7 @@ describe('Test plugin altering video constants', function () {
}
{
- const res = await getVideoLicences(server.url)
- const licences = res.body
+ const licences = await server.videos.getLicences()
expect(licences[1]).to.equal('Attribution')
expect(licences[7]).to.equal('Public Domain Dedication')
@@ -157,8 +129,7 @@ describe('Test plugin altering video constants', function () {
}
{
- const res = await getVideoPrivacies(server.url)
- const privacies = res.body
+ const privacies = await server.videos.getPrivacies()
expect(privacies[1]).to.exist
expect(privacies[2]).to.exist
@@ -167,8 +138,7 @@ describe('Test plugin altering video constants', function () {
}
{
- const res = await getVideoPlaylistPrivacies(server.url)
- const playlistPrivacies = res.body
+ const playlistPrivacies = await server.playlists.getPrivacies()
expect(playlistPrivacies[1]).to.exist
expect(playlistPrivacies[2]).to.exist
@@ -177,35 +147,34 @@ describe('Test plugin altering video constants', function () {
})
it('Should be able to reset categories', async function () {
- await installPlugin({
- url: server.url,
- accessToken: server.accessToken,
- path: getPluginTestPath('-video-constants')
- })
+ await server.plugins.install({ path: PluginsCommand.getPluginTestPath('-video-constants') })
- let { body: categories } = await getVideoCategories(server.url)
+ {
+ const categories = await server.videos.getCategories()
- expect(categories[1]).to.not.exist
- expect(categories[2]).to.not.exist
+ expect(categories[1]).to.not.exist
+ expect(categories[2]).to.not.exist
- expect(categories[42]).to.exist
- expect(categories[43]).to.exist
+ expect(categories[42]).to.exist
+ expect(categories[43]).to.exist
+ }
await makeGetRequest({
url: server.url,
token: server.accessToken,
path: '/plugins/test-video-constants/router/reset-categories',
- statusCodeExpected: HttpStatusCode.NO_CONTENT_204
+ expectedStatus: HttpStatusCode.NO_CONTENT_204
})
- const { body } = await getVideoCategories(server.url)
- categories = body
+ {
+ const categories = await server.videos.getCategories()
- expect(categories[1]).to.exist
- expect(categories[2]).to.exist
+ expect(categories[1]).to.exist
+ expect(categories[2]).to.exist
- expect(categories[42]).to.not.exist
- expect(categories[43]).to.not.exist
+ expect(categories[42]).to.not.exist
+ expect(categories[43]).to.not.exist
+ }
})
after(async function () {
diff --git a/server/tools/cli.ts b/server/tools/cli.ts
index 7b94306cd..52e6ea593 100644
--- a/server/tools/cli.ts
+++ b/server/tools/cli.ts
@@ -1,14 +1,11 @@
-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 { 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 { Netrc } from 'netrc-parser'
+import { join } from 'path'
+import { createLogger, format, transports } from 'winston'
+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'
let configName = 'PeerTube/CLI'
if (isTestInstance()) configName += `-${getAppNumber()}`
@@ -17,17 +14,16 @@ 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)
- const me: User = resMe.body
+async function getAdminTokenOrDie (server: PeerTubeServer, username: string, password: string) {
+ 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.')
process.exit(-1)
}
- return accessToken
+ return token
}
interface Settings {
@@ -128,7 +124,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: PeerTubeServer, command: Command, defaultAttributes: any = {}) {
const options = command.opts()
const defaultBooleanAttributes = {
@@ -164,8 +160,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.channels.get({ channelName: options.channelName })
Object.assign(videoAttributes, { channelId: videoChannel.id })
@@ -184,6 +179,19 @@ function getServerCredentials (program: Command) {
})
}
+function buildServer (url: string) {
+ return new PeerTubeServer({ url })
+}
+
+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 }
+
+ const body = await server.login.login({ client, user: { username, password } })
+
+ server.accessToken = body.access_token
+}
+
function getLogger (logLevel = 'info') {
const logLevels = {
0: 0,
@@ -230,5 +238,7 @@ export {
buildCommonVideoOptions,
buildVideoAttributesFromCommander,
- getAdminTokenOrDie
+ getAdminTokenOrDie,
+ 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 9488eba0e..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 { getClient, Server, serverLogin } from '../../shared/extra-utils'
+import { assignToken, buildServer } from './cli'
program
.option('-u, --url ', 'Server url')
@@ -24,24 +24,11 @@ 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
+const server = buildServer(options.url)
- return serverLogin(server)
- })
- .then(accessToken => {
- console.log(accessToken)
+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 101a95b2a..52aae3d2c 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 { 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 {
+ assignToken,
+ buildCommonVideoOptions,
+ buildServer,
+ buildVideoAttributesFromCommander,
+ getLogger,
+ getServerCredentials
+} from './cli'
+import { PeerTubeServer } from '@shared/extra-utils'
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))
- 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 before "%s", don\'t upload it.\n', videoInfo.title, formatDate(options.since))
return
}
- const result = await advancedVideosSearch(url, { search: videoInfo.title, sort: '-match', searchTarget: 'local' })
+ 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))
+ return
+ }
+
+ const server = buildServer(url)
+ const { data } = await server.search.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,11 +195,15 @@ 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 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)) {
@@ -223,28 +235,28 @@ async function uploadVideoOnPeerTube (parameters: {
tags
}
- const videoAttributes = await buildVideoAttributesFromCommander(url, program, defaultAttributes)
+ const baseAttributes = 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)
-
- let accessToken = await getAccessTokenOrDie(url, user)
+ log.info('\nUploading on PeerTube video "%s".', attributes.name)
try {
- await uploadVideo(url, accessToken, videoAttributes)
+ 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.')
- accessToken = await getAccessTokenOrDie(url, user)
+ server.accessToken = await server.login.getAccessToken(username, password)
- await uploadVideo(url, accessToken, videoAttributes)
+ await server.videos.upload({ attributes })
} else {
exitError(err.message)
}
@@ -253,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: PeerTubeServer, 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.videos.getCategories()
for (const key of Object.keys(categoriesServer)) {
const categoryServer = categoriesServer[key]
@@ -362,21 +373,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..d9c285115 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 { assignToken, buildServer, 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 server = buildServer(url)
+ await assignToken(server, username, password)
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.plugins.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 server = buildServer(url)
+ await assignToken(server, username, password)
try {
- await installPlugin({
- url,
- accessToken,
- 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)
@@ -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 server = buildServer(url)
+ await assignToken(server, username, password)
try {
- await updatePlugin({
- url,
- accessToken,
- 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)
@@ -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 server = buildServer(url)
+ await assignToken(server, username, password)
try {
- await uninstallPlugin({
- url,
- accessToken,
- 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 4810deee0..73b026ac8 100644
--- a/server/tools/peertube-redundancy.ts
+++ b/server/tools/peertube-redundancy.ts
@@ -1,17 +1,13 @@
-// 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, VideoRedundanciesTarget } from '@shared/models'
+import { assignToken, buildServer, getServerCredentials } from './cli'
import bytes = require('bytes')
@@ -63,15 +59,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 server = buildServer(url)
+ await assignToken(server, username, password)
- const redundancies = await listVideoRedundanciesData(url, accessToken, 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' ]
}) as any
- for (const redundancy of redundancies) {
+ for (const redundancy of data) {
const webtorrentFiles = redundancy.redundancies.files
const streamingPlaylists = redundancy.redundancies.streamingPlaylists
@@ -106,7 +103,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 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')
@@ -115,11 +113,7 @@ async function addRedundancyCLI (options: { video: number }, command: Command) {
}
try {
- await addVideoRedundancy({
- url,
- accessToken,
- videoId: options.video
- })
+ await server.redundancy.addVideo({ videoId: options.video })
console.log('Video will be duplicated by your instance!')
@@ -139,7 +133,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 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')
@@ -149,12 +144,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.redundancy.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.redundancy.listVideos({ target: 'remote-videos' })
+ videoRedundancy = remoteVideoRedundancies.data.find(r => videoId === r.id)
}
if (!videoRedundancy) {
@@ -168,11 +163,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.redundancy.removeVideo({ redundancyId: id })
}
console.log('Video redundancy removed!')
@@ -183,16 +174,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..01fb1fe8d 100644
--- a/server/tools/peertube-upload.ts
+++ b/server/tools/peertube-upload.ts
@@ -4,9 +4,7 @@ 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, buildVideoAttributesFromCommander, getServerCredentials } from './cli'
+import { assignToken, buildCommonVideoOptions, buildServer, buildVideoAttributesFromCommander, getServerCredentials } from './cli'
let command = program
.name('upload')
@@ -46,22 +44,25 @@ getServerCredentials(command)
.catch(err => console.error(err))
async function run (url: string, username: string, password: string) {
- const accessToken = await getAccessToken(url, username, password)
+ const server = buildServer(url)
+ await assignToken(server, username, password)
await access(options.file, constants.F_OK)
console.log('Uploading %s video...', options.videoName)
- const videoAttributes = await buildVideoAttributesFromCommander(url, 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, accessToken, videoAttributes)
+ await server.videos.upload({ attributes })
console.log(`Video ${options.videoName} uploaded.`)
process.exit(0)
} catch (err) {
diff --git a/server/tools/test.ts b/server/tools/test-live.ts
similarity index 59%
rename from server/tools/test.ts
rename to server/tools/test-live.ts
index fbdbae0b0..0cb0c3668 100644
--- a/server/tools/test.ts
+++ b/server/tools/test-live.ts
@@ -1,26 +1,23 @@
-import { registerTSPaths } from '../helpers/register-ts-paths'
-registerTSPaths()
-
-import { LiveVideo, LiveVideoCreate, VideoPrivacy } from '@shared/models'
import { program } from 'commander'
+import { LiveVideoCreate, VideoPrivacy } from '@shared/models'
import {
- createLive,
- flushAndRunServer,
- getLive,
+ createSingleServer,
killallServers,
sendRTMPStream,
- ServerInfo,
+ PeerTubeServer,
setAccessTokensToServers,
- setDefaultVideoChannel,
- updateCustomSubConfig
+ 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')
+ .name('test-live')
.option('-t, --type ', 'live-muxing|live-transcoding')
.parse(process.argv)
@@ -39,11 +36,11 @@ 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 = () => {
+ const cleanup = async () => {
console.log('Killing server')
- killallServers([ server ])
+ await killallServers([ server ])
}
process.on('exit', cleanup)
@@ -57,17 +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 res = await createLive(server.url, server.accessToken, attributes)
- const liveVideoUUID = res.body.video.uuid
+ const { uuid: liveVideoUUID } = await server.live.create({ fields: attributes })
- const resLive = await getLive(server.url, server.accessToken, liveVideoUUID)
- const live: LiveVideo = resLive.body
+ const live = await server.live.get({ videoId: liveVideoUUID })
console.log('Sending RTMP stream.')
@@ -86,19 +81,21 @@ async function run () {
// ----------------------------------------------------------------------------
-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'
+async function buildConfig (server: PeerTubeServer, commandType: CommandType) {
+ await server.config.updateCustomSubConfig({
+ newConfig: {
+ instance: {
+ customizations: {
+ javascript: '',
+ css: ''
+ }
+ },
+ live: {
+ enabled: true,
+ allowReplay: true,
+ transcoding: {
+ enabled: commandType === 'live-transcoding'
+ }
}
}
})
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/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
new file mode 100644
index 000000000..b5c5673ce
--- /dev/null
+++ b/shared/extra-utils/bulk/bulk-command.ts
@@ -0,0 +1,20 @@
+import { BulkRemoveCommentsOfBody, HttpStatusCode } from '@shared/models'
+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,
+ implicitToken: true,
+ 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 b6f437b8b..000000000
--- a/shared/extra-utils/bulk/bulk.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-import { BulkRemoveCommentsOfBody } from "@shared/models/bulk/bulk-remove-comments-of-body.model"
-import { makePostBodyRequest } from "../requests/requests"
-import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes'
-
-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'
-
- return makePostBodyRequest({
- url,
- path,
- token,
- fields: attributes,
- statusCodeExpected: expectedStatus || HttpStatusCode.NO_CONTENT_204
- })
-}
-
-export {
- bulkRemoveCommentsOf
-}
diff --git a/shared/extra-utils/bulk/index.ts b/shared/extra-utils/bulk/index.ts
new file mode 100644
index 000000000..391597243
--- /dev/null
+++ b/shared/extra-utils/bulk/index.ts
@@ -0,0 +1 @@
+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 c62e170bb..000000000
--- a/shared/extra-utils/cli/cli.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-import { exec } from 'child_process'
-
-import { ServerInfo } from '../server/servers'
-
-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)
-
- return res(stdout)
- })
- })
-}
-
-// ---------------------------------------------------------------------------
-
-export {
- execCLI,
- getEnvCli
-}
diff --git a/shared/extra-utils/cli/index.ts b/shared/extra-utils/cli/index.ts
new file mode 100644
index 000000000..91b5abfbe
--- /dev/null
+++ b/shared/extra-utils/cli/index.ts
@@ -0,0 +1 @@
+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..cd869a8de
--- /dev/null
+++ b/shared/extra-utils/custom-pages/custom-pages-command.ts
@@ -0,0 +1,33 @@
+import { CustomPage, HttpStatusCode } from '@shared/models'
+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,
+ implicitToken: false,
+ 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 },
+ implicitToken: true,
+ 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 bf2d16c70..000000000
--- a/shared/extra-utils/custom-pages/custom-pages.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes'
-import { makeGetRequest, makePutBodyRequest } from '../requests/requests'
-
-function getInstanceHomepage (url: string, statusCodeExpected = HttpStatusCode.OK_200) {
- const path = '/api/v1/custom-pages/homepage/instance'
-
- return makeGetRequest({
- url,
- path,
- statusCodeExpected
- })
-}
-
-function updateInstanceHomepage (url: string, token: string, content: string) {
- const path = '/api/v1/custom-pages/homepage/instance'
-
- return makePutBodyRequest({
- url,
- path,
- token,
- fields: { content },
- statusCodeExpected: HttpStatusCode.NO_CONTENT_204
- })
-}
-
-// ---------------------------------------------------------------------------
-
-export {
- getInstanceHomepage,
- updateInstanceHomepage
-}
diff --git a/shared/extra-utils/custom-pages/index.ts b/shared/extra-utils/custom-pages/index.ts
new file mode 100644
index 000000000..58aed04f2
--- /dev/null
+++ b/shared/extra-utils/custom-pages/index.ts
@@ -0,0 +1 @@
+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..3c95f9536
--- /dev/null
+++ b/shared/extra-utils/feeds/feeds-command.ts
@@ -0,0 +1,44 @@
+
+import { HttpStatusCode } from '@shared/models'
+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',
+ implicitToken: false,
+ 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',
+ implicitToken: false,
+ 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 ce0a98c6d..000000000
--- a/shared/extra-utils/feeds/feeds.ts
+++ /dev/null
@@ -1,33 +0,0 @@
-import * as request from 'supertest'
-import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes'
-
-type FeedType = 'videos' | 'video-comments' | 'subscriptions'
-
-function getXMLfeed (url: string, feed: FeedType, format?: string) {
- const path = '/feeds/' + feed + '.xml'
-
- return request(url)
- .get(path)
- .query((format) ? { format: format } : {})
- .set('Accept', 'application/xml')
- .expect(HttpStatusCode.OK_200)
- .expect('Content-Type', /xml/)
-}
-
-function getJSONfeed (url: string, feed: FeedType, query: any = {}, statusCodeExpected = HttpStatusCode.OK_200) {
- const path = '/feeds/' + feed + '.json'
-
- return request(url)
- .get(path)
- .query(query)
- .set('Accept', 'application/json')
- .expect(statusCodeExpected)
- .expect('Content-Type', /json/)
-}
-
-// ---------------------------------------------------------------------------
-
-export {
- getXMLfeed,
- getJSONfeed
-}
diff --git a/shared/extra-utils/feeds/index.ts b/shared/extra-utils/feeds/index.ts
new file mode 100644
index 000000000..662a22b6f
--- /dev/null
+++ b/shared/extra-utils/feeds/index.ts
@@ -0,0 +1 @@
+export * from './feeds-command'
diff --git a/shared/extra-utils/index.ts b/shared/extra-utils/index.ts
index 87ee8abba..4b3636d06 100644
--- a/shared/extra-utils/index.ts
+++ b/shared/extra-utils/index.ts
@@ -1,51 +1,15 @@
-export * from './bulk/bulk'
-
-export * from './cli/cli'
-
-export * from './custom-pages/custom-pages'
-
-export * from './feeds/feeds'
-
-export * from './mock-servers/mock-instances-index'
-
-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'
-
-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 './server/activitypub'
-export * from './server/clients'
-export * from './server/config'
-export * from './server/debug'
-export * from './server/follows'
-export * from './server/jobs'
-export * from './server/plugins'
-export * from './server/servers'
-
-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'
-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 './bulk'
+export * from './cli'
+export * from './custom-pages'
+export * from './feeds'
+export * from './logs'
+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 './videos'
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..5912e814f
--- /dev/null
+++ b/shared/extra-utils/logs/logs-command.ts
@@ -0,0 +1,43 @@
+import { HttpStatusCode } from '@shared/models'
+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 },
+ implicitToken: true,
+ 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 },
+ implicitToken: true,
+ 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/miscs/checks.ts b/shared/extra-utils/miscs/checks.ts
new file mode 100644
index 000000000..7fc92f804
--- /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/models'
+import { makeGetRequest } from '../requests'
+import { PeerTubeServer } 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,
+ expectedStatus: 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: PeerTubeServer, directory: string, filePath: string, exist: boolean) {
+ const base = server.servers.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..8d6435481
--- /dev/null
+++ b/shared/extra-utils/miscs/generate.ts
@@ -0,0 +1,61 @@
+import * as ffmpeg from 'fluent-ffmpeg'
+import { ensureDir, pathExists } from 'fs-extra'
+import { dirname } from 'path'
+import { buildAbsoluteFixturePath } from './tests'
+
+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
new file mode 100644
index 000000000..4474661de
--- /dev/null
+++ b/shared/extra-utils/miscs/index.ts
@@ -0,0 +1,5 @@
+export * from './checks'
+export * from './generate'
+export * from './sql-command'
+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
new file mode 100644
index 000000000..80c8cd271
--- /dev/null
+++ b/shared/extra-utils/miscs/sql-command.ts
@@ -0,0 +1,142 @@
+import { QueryTypes, Sequelize } from 'sequelize'
+import { AbstractCommand } from '../shared/abstract-command'
+
+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
deleted file mode 100644
index d1eb0e3b2..000000000
--- a/shared/extra-utils/miscs/stubs.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-function buildRequestStub (): any {
- return { }
-}
-
-function buildResponseStub (): any {
- return {
- locals: {}
- }
-}
-
-export {
- buildResponseStub,
- buildRequestStub
-}
diff --git a/shared/extra-utils/miscs/tests.ts b/shared/extra-utils/miscs/tests.ts
new file mode 100644
index 000000000..3dfb2487e
--- /dev/null
+++ b/shared/extra-utils/miscs/tests.ts
@@ -0,0 +1,94 @@
+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'
+}
+
+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 {
+ FIXTURE_URLS,
+
+ 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..815ea3d56
--- /dev/null
+++ b/shared/extra-utils/miscs/webtorrent.ts
@@ -0,0 +1,30 @@
+import { readFile } from 'fs-extra'
+import * as parseTorrent from 'parse-torrent'
+import { join } from 'path'
+import * as WebTorrent from 'webtorrent'
+import { PeerTubeServer } from '../server'
+
+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))
+}
+
+async function parseTorrentVideo (server: PeerTubeServer, videoUUID: string, resolution: number) {
+ const torrentName = videoUUID + '-' + resolution + '.torrent'
+ const torrentPath = server.servers.buildDirectory(join('torrents', torrentName))
+
+ const data = await readFile(torrentPath)
+
+ return parseTorrent(data)
+}
+
+export {
+ webtorrentAdd,
+ parseTorrentVideo
+}
diff --git a/shared/extra-utils/mock-servers/index.ts b/shared/extra-utils/mock-servers/index.ts
new file mode 100644
index 000000000..0ec07f685
--- /dev/null
+++ b/shared/extra-utils/mock-servers/index.ts
@@ -0,0 +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/miscs/email.ts b/shared/extra-utils/mock-servers/mock-email.ts
similarity index 92%
rename from shared/extra-utils/miscs/email.ts
rename to shared/extra-utils/mock-servers/mock-email.ts
index 9fc9a5ad0..ffd62e325 100644
--- a/shared/extra-utils/miscs/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/mock-servers/joinpeertube-versions.ts b/shared/extra-utils/mock-servers/mock-joinpeertube-versions.ts
similarity index 100%
rename from shared/extra-utils/mock-servers/joinpeertube-versions.ts
rename to shared/extra-utils/mock-servers/mock-joinpeertube-versions.ts
diff --git a/shared/extra-utils/plugins/mock-blocklist.ts b/shared/extra-utils/mock-servers/mock-plugin-blocklist.ts
similarity index 100%
rename from shared/extra-utils/plugins/mock-blocklist.ts
rename to shared/extra-utils/mock-servers/mock-plugin-blocklist.ts
diff --git a/shared/extra-utils/moderation/abuses-command.ts b/shared/extra-utils/moderation/abuses-command.ts
new file mode 100644
index 000000000..7b3abb056
--- /dev/null
+++ b/shared/extra-utils/moderation/abuses-command.ts
@@ -0,0 +1,228 @@
+import { pick } from 'lodash'
+import {
+ AbuseFilter,
+ AbuseMessage,
+ AbusePredefinedReasonsString,
+ AbuseState,
+ AbuseUpdate,
+ AbuseVideoIs,
+ AdminAbuse,
+ HttpStatusCode,
+ ResultList,
+ UserAbuse
+} from '@shared/models'
+import { unwrapBody } from '../requests/requests'
+import { AbstractCommand, OverrideCommandOptions } from '../shared'
+
+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,
+ implicitToken: true,
+ 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,
+ implicitToken: true,
+ 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,
+ implicitToken: true,
+ 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,
+ implicitToken: true,
+ defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
+ })
+ }
+
+ delete (options: OverrideCommandOptions & {
+ abuseId: number
+ }) {
+ const { abuseId } = options
+ const path = '/api/v1/abuses/' + abuseId
+
+ return this.deleteRequest({
+ ...options,
+
+ path,
+ implicitToken: true,
+ 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,
+ implicitToken: true,
+ 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,
+ implicitToken: true,
+ 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 },
+ implicitToken: true,
+ 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/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..06b4892d2
--- /dev/null
+++ b/shared/extra-utils/overviews/overviews-command.ts
@@ -0,0 +1,23 @@
+import { HttpStatusCode, VideosOverview } from '@shared/models'
+import { AbstractCommand, OverrideCommandOptions } from '../shared'
+
+export class OverviewsCommand extends AbstractCommand {
+
+ getVideos (options: OverrideCommandOptions & {
+ page: number
+ }) {
+ const { page } = options
+ const path = '/api/v1/overviews/videos'
+
+ const query = { page }
+
+ return this.getRequestBody({
+ ...options,
+
+ path,
+ query,
+ implicitToken: false,
+ 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/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/requests/check-api-params.ts b/shared/extra-utils/requests/check-api-params.ts
index 7f5ff775c..26ba1e913 100644
--- a/shared/extra-utils/requests/check-api-params.ts
+++ b/shared/extra-utils/requests/check-api-params.ts
@@ -1,14 +1,13 @@
+import { HttpStatusCode } from '@shared/models'
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' }),
- statusCodeExpected: HttpStatusCode.BAD_REQUEST_400
+ query: { ...query, start: 'hello' },
+ expectedStatus: HttpStatusCode.BAD_REQUEST_400
})
}
@@ -17,16 +16,16 @@ async function checkBadCountPagination (url: string, path: string, token?: strin
url,
path,
token,
- query: immutableAssign(query, { count: 'hello' }),
- statusCodeExpected: HttpStatusCode.BAD_REQUEST_400
+ query: { ...query, count: 'hello' },
+ expectedStatus: HttpStatusCode.BAD_REQUEST_400
})
await makeGetRequest({
url,
path,
token,
- query: immutableAssign(query, { count: 2000 }),
- statusCodeExpected: HttpStatusCode.BAD_REQUEST_400
+ query: { ...query, count: 2000 },
+ expectedStatus: HttpStatusCode.BAD_REQUEST_400
})
}
@@ -35,8 +34,8 @@ function checkBadSortPagination (url: string, path: string, token?: string, quer
url,
path,
token,
- query: immutableAssign(query, { sort: 'hello' }),
- statusCodeExpected: HttpStatusCode.BAD_REQUEST_400
+ query: { ...query, sort: 'hello' },
+ expectedStatus: HttpStatusCode.BAD_REQUEST_400
})
}
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/requests/requests.ts b/shared/extra-utils/requests/requests.ts
index 38e24d897..70f790222 100644
--- a/shared/extra-utils/requests/requests.ts
+++ b/shared/extra-utils/requests/requests.ts
@@ -1,103 +1,82 @@
-/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/no-floating-promises */
+/* eslint-disable @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 { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes'
+import * as request from 'supertest'
+import { URL } from 'url'
+import { HttpStatusCode } from '@shared/models'
+import { buildAbsoluteFixturePath } 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)
-
- 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
-}) {
- if (!options.statusCodeExpected) options.statusCodeExpected = HttpStatusCode.BAD_REQUEST_400
- if (options.contentType === undefined) options.contentType = 'application/json'
+ host?: string
+ token?: string
+ headers?: { [ name: string ]: string }
+ type?: string
+ xForwardedFor?: string
+ expectedStatus?: HttpStatusCode
+}
+function makeRawRequest (url: string, expectedStatus?: HttpStatusCode, range?: string) {
+ const { host, protocol, pathname } = new URL(url)
+
+ return makeGetRequest({ url: `${protocol}//${host}`, path: pathname, expectedStatus, range })
+}
+
+function makeGetRequest (options: CommonRequestParams & {
+ query?: any
+}) {
const req = request(options.url).get(options.path)
+ .query(options.query)
- 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.redirects) req.redirects(options.redirects)
-
- return req.expect(options.statusCodeExpected)
+ return buildRequest(req, { contentType: 'application/json', expectedStatus: HttpStatusCode.BAD_REQUEST_400, ...options })
}
-function makeDeleteRequest (options: {
- url: string
- path: string
- token?: string
- statusCodeExpected?: HttpStatusCode
-}) {
- if (!options.statusCodeExpected) options.statusCodeExpected = HttpStatusCode.BAD_REQUEST_400
-
- const req = request(options.url)
- .delete(options.path)
- .set('Accept', 'application/json')
-
- if (options.token) req.set('Authorization', 'Bearer ' + options.token)
-
- return req.expect(options.statusCodeExpected)
+function makeHTMLRequest (url: string, path: string) {
+ return makeGetRequest({
+ url,
+ path,
+ accept: 'text/html',
+ expectedStatus: HttpStatusCode.OK_200
+ })
}
-function makeUploadRequest (options: {
- url: string
+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 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[] }
- statusCodeExpected?: HttpStatusCode
}) {
- if (!options.statusCodeExpected) 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.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 {
@@ -105,27 +84,16 @@ function makeUploadRequest (options: {
}
})
- return req.expect(options.statusCodeExpected)
+ return req
}
-function makePostBodyRequest (options: {
- url: string
- path: string
- token?: string
+function makePostBodyRequest (options: CommonRequestParams & {
fields?: { [ fieldName: string ]: any }
- statusCodeExpected?: HttpStatusCode
}) {
- if (!options.fields) options.fields = {}
- if (!options.statusCodeExpected) options.statusCodeExpected = HttpStatusCode.BAD_REQUEST_400
+ const req = request(options.url).post(options.path)
+ .send(options.fields)
- const req = request(options.url)
- .post(options.path)
- .set('Accept', 'application/json')
-
- if (options.token) req.set('Authorization', 'Bearer ' + options.token)
-
- return req.send(options.fields)
- .expect(options.statusCodeExpected)
+ return buildRequest(req, { accept: 'application/json', expectedStatus: HttpStatusCode.BAD_REQUEST_400, ...options })
}
function makePutBodyRequest (options: {
@@ -133,59 +101,29 @@ function makePutBodyRequest (options: {
path: string
token?: string
fields: { [ fieldName: string ]: any }
- statusCodeExpected?: HttpStatusCode
+ expectedStatus?: HttpStatusCode
}) {
- if (!options.statusCodeExpected) options.statusCodeExpected = HttpStatusCode.BAD_REQUEST_400
+ const req = request(options.url).put(options.path)
+ .send(options.fields)
- 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 updateImageRequest (options: {
- url: string
- path: string
- accessToken: string
- fixture: string
- fieldname: string
-}) {
- let filePath = ''
- if (isAbsolute(options.fixture)) {
- filePath = options.fixture
- } else {
- filePath = join(root(), 'server', 'tests', 'fixtures', options.fixture)
- }
-
- 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) {
return decode(path.split('?')[1])
}
+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 {
- get4KFileUrl,
makeHTMLRequest,
makeGetRequest,
decodeQueryString,
@@ -194,5 +132,51 @@ export {
makePutBodyRequest,
makeDeleteRequest,
makeRawRequest,
- updateImageRequest
+ makeActivityPubGetRequest,
+ unwrapBody,
+ 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/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..0fbbcd6ef
--- /dev/null
+++ b/shared/extra-utils/search/search-command.ts
@@ -0,0 +1,98 @@
+import {
+ HttpStatusCode,
+ ResultList,
+ Video,
+ VideoChannel,
+ VideoChannelsSearchQuery,
+ VideoPlaylist,
+ VideoPlaylistsSearchQuery,
+ VideosSearchQuery
+} from '@shared/models'
+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 } = options
+ const path = '/api/v1/search/video-channels'
+
+ return this.getRequestBody>({
+ ...options,
+
+ path,
+ query: search,
+ implicitToken: false,
+ defaultExpectedStatus: HttpStatusCode.OK_200
+ })
+ }
+
+ searchPlaylists (options: OverrideCommandOptions & {
+ search: string
+ }) {
+ return this.advancedPlaylistSearch({
+ ...options,
+
+ search: { search: options.search }
+ })
+ }
+
+ advancedPlaylistSearch (options: OverrideCommandOptions & {
+ search: VideoPlaylistsSearchQuery
+ }) {
+ const { search } = options
+ const path = '/api/v1/search/video-playlists'
+
+ return this.getRequestBody>({
+ ...options,
+
+ path,
+ query: search,
+ implicitToken: false,
+ 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 } = options
+ const path = '/api/v1/search/videos'
+
+ return this.getRequestBody>({
+ ...options,
+
+ path,
+ query: search,
+ implicitToken: false,
+ 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/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
-}
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/config-command.ts b/shared/extra-utils/server/config-command.ts
new file mode 100644
index 000000000..11148aa46
--- /dev/null
+++ b/shared/extra-utils/server/config-command.ts
@@ -0,0 +1,263 @@
+import { merge } from 'lodash'
+import { DeepPartial } from '@shared/core-utils'
+import { About, HttpStatusCode, 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,
+
+ path,
+ implicitToken: false,
+ defaultExpectedStatus: HttpStatusCode.OK_200
+ })
+ }
+
+ getAbout (options: OverrideCommandOptions = {}) {
+ const path = '/api/v1/config/about'
+
+ return this.getRequestBody({
+ ...options,
+
+ path,
+ implicitToken: false,
+ defaultExpectedStatus: HttpStatusCode.OK_200
+ })
+ }
+
+ getCustomConfig (options: OverrideCommandOptions = {}) {
+ const path = '/api/v1/config/custom'
+
+ return this.getRequestBody({
+ ...options,
+
+ path,
+ implicitToken: true,
+ defaultExpectedStatus: HttpStatusCode.OK_200
+ })
+ }
+
+ updateCustomConfig (options: OverrideCommandOptions & {
+ newCustomConfig: CustomConfig
+ }) {
+ const path = '/api/v1/config/custom'
+
+ return this.putBodyRequest({
+ ...options,
+
+ path,
+ fields: options.newCustomConfig,
+ implicitToken: true,
+ defaultExpectedStatus: HttpStatusCode.OK_200
+ })
+ }
+
+ deleteCustomConfig (options: OverrideCommandOptions = {}) {
+ const path = '/api/v1/config/custom'
+
+ return this.deleteRequest({
+ ...options,
+
+ path,
+ implicitToken: true,
+ 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/contact-form-command.ts b/shared/extra-utils/server/contact-form-command.ts
new file mode 100644
index 000000000..0e8fd6d84
--- /dev/null
+++ b/shared/extra-utils/server/contact-form-command.ts
@@ -0,0 +1,31 @@
+import { HttpStatusCode } from '@shared/models'
+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,
+ fields: body,
+ implicitToken: false,
+ 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/debug-command.ts b/shared/extra-utils/server/debug-command.ts
new file mode 100644
index 000000000..3c5a785bb
--- /dev/null
+++ b/shared/extra-utils/server/debug-command.ts
@@ -0,0 +1,33 @@
+import { Debug, HttpStatusCode, SendDebugCommand } from '@shared/models'
+import { AbstractCommand, OverrideCommandOptions } from '../shared'
+
+export class DebugCommand extends AbstractCommand {
+
+ getDebug (options: OverrideCommandOptions = {}) {
+ const path = '/api/v1/server/debug'
+
+ return this.getRequestBody({
+ ...options,
+
+ path,
+ implicitToken: true,
+ 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,
+ implicitToken: true,
+ 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/directories.ts b/shared/extra-utils/server/directories.ts
new file mode 100644
index 000000000..b6465cbf4
--- /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 { PeerTubeServer } from './server'
+
+async function checkTmpIsEmpty (server: PeerTubeServer) {
+ 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: PeerTubeServer, 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/follows-command.ts b/shared/extra-utils/server/follows-command.ts
new file mode 100644
index 000000000..2b889cf66
--- /dev/null
+++ b/shared/extra-utils/server/follows-command.ts
@@ -0,0 +1,141 @@
+import { pick } from 'lodash'
+import { ActivityPubActorType, ActorFollow, FollowState, HttpStatusCode, ResultList, ServerFollowCreate } from '@shared/models'
+import { AbstractCommand, OverrideCommandOptions } from '../shared'
+import { PeerTubeServer } from './server'
+
+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,
+
+ path,
+ query,
+ implicitToken: false,
+ 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,
+
+ path,
+ query,
+ implicitToken: false,
+ defaultExpectedStatus: HttpStatusCode.OK_200
+ })
+ }
+
+ follow (options: OverrideCommandOptions & {
+ hosts?: string[]
+ handles?: string[]
+ }) {
+ const path = '/api/v1/server/following'
+
+ 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,
+ implicitToken: true,
+ defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
+ })
+ }
+
+ async unfollow (options: OverrideCommandOptions & {
+ target: PeerTubeServer | string
+ }) {
+ const { target } = options
+
+ const handle = typeof target === 'string'
+ ? target
+ : target.host
+
+ const path = '/api/v1/server/following/' + handle
+
+ return this.deleteRequest({
+ ...options,
+
+ path,
+ implicitToken: true,
+ defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
+ })
+ }
+
+ acceptFollower (options: OverrideCommandOptions & {
+ follower: string
+ }) {
+ const path = '/api/v1/server/followers/' + options.follower + '/accept'
+
+ return this.postBodyRequest({
+ ...options,
+
+ path,
+ implicitToken: true,
+ defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
+ })
+ }
+
+ rejectFollower (options: OverrideCommandOptions & {
+ follower: string
+ }) {
+ const path = '/api/v1/server/followers/' + options.follower + '/reject'
+
+ return this.postBodyRequest({
+ ...options,
+
+ path,
+ implicitToken: true,
+ defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
+ })
+ }
+
+ removeFollower (options: OverrideCommandOptions & {
+ follower: PeerTubeServer
+ }) {
+ const path = '/api/v1/server/followers/peertube@' + options.follower.host
+
+ return this.deleteRequest({
+ ...options,
+
+ path,
+ implicitToken: true,
+ defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
+ })
+ }
+}
diff --git a/shared/extra-utils/server/follows.ts b/shared/extra-utils/server/follows.ts
index 6aae4a31d..698238f29 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'
+import { PeerTubeServer } from './server'
-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)
-}
-
-async function doubleFollow (server1: ServerInfo, server2: ServerInfo) {
+async function doubleFollow (server1: PeerTubeServer, server2: PeerTubeServer) {
await Promise.all([
- follow(server1.url, [ server2.url ], server1.accessToken),
- follow(server2.url, [ server1.url ], server2.accessToken)
+ server1.follows.follow({ hosts: [ server2.url ] }),
+ server2.follows.follow({ hosts: [ 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
new file mode 100644
index 000000000..9055dfc57
--- /dev/null
+++ b/shared/extra-utils/server/index.ts
@@ -0,0 +1,15 @@
+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'
+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-command.ts b/shared/extra-utils/server/jobs-command.ts
new file mode 100644
index 000000000..09a299e5b
--- /dev/null
+++ b/shared/extra-utils/server/jobs-command.ts
@@ -0,0 +1,36 @@
+import { pick } from 'lodash'
+import { HttpStatusCode } from '@shared/models'
+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,
+ implicitToken: true,
+ 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 763374e03..64a0353eb 100644
--- a/shared/extra-utils/server/jobs.ts
+++ b/shared/extra-utils/server/jobs.ts
@@ -1,66 +1,17 @@
-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 { wait } from '../miscs/miscs'
-import { ServerInfo } from './servers'
-function buildJobsUrl (state?: JobState) {
- let path = '/api/v1/jobs'
+import { JobState } from '../../models'
+import { wait } from '../miscs'
+import { PeerTubeServer } from './server'
- 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) {
+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' ]
@@ -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.jobs.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
@@ -90,9 +39,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.debug.getDebug()
+ .then(obj => {
if (obj.activityPubMessagesWaiting !== 0) {
pendingRequests = true
}
@@ -123,7 +71,5 @@ async function waitJobs (serversArg: ServerInfo[] | ServerInfo) {
// ---------------------------------------------------------------------------
export {
- getJobsList,
- waitJobs,
- getJobsListPaginationAndSort
+ waitJobs
}
diff --git a/shared/extra-utils/server/plugins-command.ts b/shared/extra-utils/server/plugins-command.ts
new file mode 100644
index 000000000..b944475a2
--- /dev/null
+++ b/shared/extra-utils/server/plugins-command.ts
@@ -0,0 +1,256 @@
+/* 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,
+ PeerTubePlugin,
+ PeerTubePluginIndex,
+ PeertubePluginIndexList,
+ PluginPackageJson,
+ PluginTranslation,
+ PluginType,
+ PublicServerSetting,
+ RegisteredServerSettings,
+ ResultList
+} from '@shared/models'
+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
+ },
+ implicitToken: true,
+ 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,
+ implicitToken: true,
+ defaultExpectedStatus: HttpStatusCode.OK_200
+ })
+ }
+
+ get (options: OverrideCommandOptions & {
+ npmName: string
+ }) {
+ const path = '/api/v1/plugins/' + options.npmName
+
+ return this.getRequestBody({
+ ...options,
+
+ path,
+ implicitToken: true,
+ 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 },
+ implicitToken: true,
+ defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
+ })
+ }
+
+ getRegisteredSettings (options: OverrideCommandOptions & {
+ npmName: string
+ }) {
+ const path = '/api/v1/plugins/' + options.npmName + '/registered-settings'
+
+ return this.getRequestBody({
+ ...options,
+
+ path,
+ implicitToken: true,
+ 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,
+ implicitToken: false,
+ defaultExpectedStatus: HttpStatusCode.OK_200
+ })
+ }
+
+ getTranslations (options: OverrideCommandOptions & {
+ locale: string
+ }) {
+ const { locale } = options
+ const path = '/plugins/translations/' + locale + '.json'
+
+ return this.getRequestBody({
+ ...options,
+
+ path,
+ implicitToken: false,
+ 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 },
+ implicitToken: true,
+ 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 },
+ implicitToken: true,
+ 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 },
+ implicitToken: true,
+ defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
+ })
+ }
+
+ getCSS (options: OverrideCommandOptions = {}) {
+ const path = '/plugins/global.css'
+
+ return this.getRequestText({
+ ...options,
+
+ path,
+ implicitToken: false,
+ 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,
+ implicitToken: false,
+ 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 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 d53e5b382..0f5fabd5a 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'
+import { PeerTubeServer } from '../server/server'
-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
- })
-}
-
-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
+async function testHelloWorldRegisteredSettings (server: PeerTubeServer) {
+ const body = await server.plugins.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/redundancy-command.ts b/shared/extra-utils/server/redundancy-command.ts
new file mode 100644
index 000000000..e7a8b3c29
--- /dev/null
+++ b/shared/extra-utils/server/redundancy-command.ts
@@ -0,0 +1,80 @@
+import { HttpStatusCode, ResultList, VideoRedundanciesTarget, VideoRedundancy } from '@shared/models'
+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 },
+ implicitToken: true,
+ 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
+ },
+
+ implicitToken: true,
+ 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 },
+ implicitToken: true,
+ 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,
+ implicitToken: true,
+ 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/server.ts b/shared/extra-utils/server/server.ts
new file mode 100644
index 000000000..b33bb9d1e
--- /dev/null
+++ b/shared/extra-utils/server/server.ts
@@ -0,0 +1,378 @@
+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 => {
+ const self = this
+
+ 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') 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]
+ }
+ }
+
+ // 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 {
+ self.app.stdout.removeListener('data', onStdout)
+ }
+
+ process.on('exit', () => {
+ try {
+ process.kill(self.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
new file mode 100644
index 000000000..107e2b4ad
--- /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/models'
+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.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.servers.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.servers.buildDirectory(subPath)
+
+ return getFileSize(path)
+ }
+}
diff --git a/shared/extra-utils/server/servers.ts b/shared/extra-utils/server/servers.ts
index 28e431e94..87d7e9449 100644
--- a/shared/extra-utils/server/servers.ts
+++ b/shared/extra-utils/server/servers.ts
@@ -1,384 +1,49 @@
-/* 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 { expect } from 'chai'
-import { ChildProcess, exec, fork } from 'child_process'
-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 { buildServerDirectory, getFileSize, isGithubCI, root, wait } from '../miscs/miscs'
-import { makeGetRequest } from '../requests/requests'
+async function createSingleServer (serverNumber: number, configOverride?: Object, args = [], options: RunServerOptions = {}) {
+ const server = new PeerTubeServer({ serverNumber })
-interface ServerInfo {
- app: ChildProcess
-
- url: string
- host: string
- hostname: string
- port: number
-
- rtmpPort: number
-
- parallel: boolean
- internalServerNumber: number
- serverNumber: number
-
- client: {
- id: string
- secret: string
- }
-
- user: {
- username: string
- password: string
- email?: string
- }
-
- customConfigFile?: string
-
- accessToken?: string
- refreshToken?: string
- videoChannel?: VideoChannel
-
- video?: {
- id: number
- uuid: string
- shortUUID: string
- name?: string
- url?: string
-
- account?: {
- name: string
- }
-
- embedPath?: string
- }
-
- remoteVideo?: {
- id: number
- uuid: string
- }
-
- videos?: { id: number, uuid: string }[]
-}
-
-function parallelTests () {
- return process.env.MOCHA_PARALLEL === 'true'
-}
-
-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 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
-
- 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 flushTests(internalServerNumber)
-
- const server: ServerInfo = {
- app: null,
- port,
- internalServerNumber,
- rtmpPort,
- parallel,
- serverNumber,
- url: `http://localhost:${port}`,
- host: `localhost:${port}`,
- hostname: 'localhost',
- client: {
- id: null,
- secret: null
- },
- user: {
- username: null,
- password: null
- }
- }
-
- return runServer(server, configOverride, args, options)
-}
-
-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)
-
- const forkOptions = {
- silent: true,
- env,
- detached: true,
- execArgv: options.execArgv || []
- }
-
- 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.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]
- }
- }
-
- // 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 */ }
- })
-
- res(server)
- })
- })
-}
-
-async function reRunServer (server: ServerInfo, configOverride?: any) {
- const newServer = await runServer(server, configOverride)
- server.app = newServer.app
+ await server.flushAndRun(configOverride, args, options)
return server
}
-async function checkTmpIsEmpty (server: ServerInfo) {
- await checkDirectoryIsEmpty(server, 'tmp', [ 'plugins-global.css', 'hls', 'resumable-uploads' ])
+function createMultipleServers (totalServers: number, configOverride?: Object) {
+ const serverPromises: Promise[] = []
- if (await pathExists(join('test' + server.internalServerNumber, 'tmp', 'hls'))) {
- await checkDirectoryIsEmpty(server, 'tmp/hls')
+ for (let i = 1; i <= totalServers; i++) {
+ serverPromises.push(createSingleServer(i, configOverride))
}
+
+ return Promise.all(serverPromises)
}
-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: PeerTubeServer[]) {
+ return Promise.all(servers.map(s => s.kill()))
}
-function killallServers (servers: ServerInfo[]) {
- for (const server of servers) {
- if (!server.app) continue
-
- process.kill(-server.app.pid)
- server.app = null
- }
-}
-
-async function cleanupTests (servers: ServerInfo[]) {
- killallServers(servers)
+async function cleanupTests (servers: PeerTubeServer[]) {
+ await killallServers(servers)
if (isGithubCI()) {
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.servers.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,
+ createSingleServer,
+ createMultipleServers,
cleanupTests,
- flushAndRunMultipleServers,
- flushTests,
- makePingRequest,
- flushAndRunServer,
- killallServers,
- reRunServer,
- waitUntilLog
+ killallServers
}
diff --git a/shared/extra-utils/server/stats-command.ts b/shared/extra-utils/server/stats-command.ts
new file mode 100644
index 000000000..64a452306
--- /dev/null
+++ b/shared/extra-utils/server/stats-command.ts
@@ -0,0 +1,25 @@
+import { HttpStatusCode, ServerStats } from '@shared/models'
+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,
+ implicitToken: false,
+ 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
-}
diff --git a/shared/extra-utils/shared/abstract-command.ts b/shared/extra-utils/shared/abstract-command.ts
new file mode 100644
index 000000000..021045e49
--- /dev/null
+++ b/shared/extra-utils/shared/abstract-command.ts
@@ -0,0 +1,199 @@
+import { isAbsolute, join } from 'path'
+import { root } from '../miscs/tests'
+import {
+ makeDeleteRequest,
+ makeGetRequest,
+ makePostBodyRequest,
+ makePutBodyRequest,
+ makeUploadRequest,
+ unwrapBody,
+ unwrapText
+} from '../requests/requests'
+import { PeerTubeServer } from '../server/server'
+
+export interface OverrideCommandOptions {
+ token?: string
+ expectedStatus?: number
+}
+
+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
+ defaultExpectedStatus: number
+
+ // 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 {
+
+ constructor (
+ protected server: PeerTubeServer
+ ) {
+
+ }
+
+ protected getRequestBody (options: InternalGetCommandOptions) {
+ return unwrapBody(this.getRequest(options))
+ }
+
+ protected getRequestText (options: InternalGetCommandOptions) {
+ 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.buildExpectedStatus(options),
+
+ url: `${protocol}//${host}`,
+ path: pathname,
+ range
+ })
+ }
+
+ protected getRequest (options: InternalGetCommandOptions) {
+ const { query } = options
+
+ return makeGetRequest({
+ ...this.buildCommonRequestOptions(options),
+
+ query
+ })
+ }
+
+ protected deleteRequest (options: InternalCommonCommandOptions) {
+ return makeDeleteRequest(this.buildCommonRequestOptions(options))
+ }
+
+ protected putBodyRequest (options: InternalCommonCommandOptions & {
+ fields?: { [ fieldName: string ]: any }
+ }) {
+ const { fields } = options
+
+ return makePutBodyRequest({
+ ...this.buildCommonRequestOptions(options),
+
+ fields
+ })
+ }
+
+ protected postBodyRequest (options: InternalCommonCommandOptions & {
+ fields?: { [ fieldName: string ]: any }
+ }) {
+ const { fields } = options
+
+ return makePostBodyRequest({
+ ...this.buildCommonRequestOptions(options),
+
+ fields
+ })
+ }
+
+ protected postUploadRequest (options: InternalCommonCommandOptions & {
+ fields?: { [ fieldName: string ]: any }
+ attaches?: { [ fieldName: string ]: any }
+ }) {
+ const { fields, attaches } = options
+
+ return makeUploadRequest({
+ ...this.buildCommonRequestOptions(options),
+
+ method: 'POST',
+ fields,
+ attaches
+ })
+ }
+
+ protected putUploadRequest (options: InternalCommonCommandOptions & {
+ fields?: { [ fieldName: string ]: any }
+ attaches?: { [ fieldName: string ]: any }
+ }) {
+ const { fields, attaches } = options
+
+ return makeUploadRequest({
+ ...this.buildCommonRequestOptions(options),
+
+ method: 'PUT',
+ fields,
+ attaches
+ })
+ }
+
+ protected updateImageRequest (options: InternalCommonCommandOptions & {
+ fixture: string
+ fieldname: string
+ }) {
+ const filePath = isAbsolute(options.fixture)
+ ? options.fixture
+ : join(root(), 'server', 'tests', 'fixtures', options.fixture)
+
+ return this.postUploadRequest({
+ ...options,
+
+ fields: {},
+ attaches: { [options.fieldname]: filePath }
+ })
+ }
+
+ protected buildCommonRequestOptions (options: InternalCommonCommandOptions) {
+ const { url, path, redirects, contentType, accept, range, host, headers, requestType, xForwardedFor } = options
+
+ return {
+ url: url ?? this.server.url,
+ path,
+
+ token: this.buildCommonRequestToken(options),
+ expectedStatus: this.buildExpectedStatus(options),
+
+ redirects,
+ contentType,
+ range,
+ host,
+ accept,
+ headers,
+ type: requestType,
+ xForwardedFor
+ }
+ }
+
+ protected buildCommonRequestToken (options: Pick) {
+ const { token } = options
+
+ const fallbackToken = options.implicitToken
+ ? this.server.accessToken
+ : undefined
+
+ return token !== undefined ? token : fallbackToken
+ }
+
+ protected buildExpectedStatus (options: Pick) {
+ const { expectedStatus, defaultExpectedStatus } = options
+
+ return expectedStatus !== undefined ? 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'
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..c277ead28
--- /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: options.token ?? 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/accounts-command.ts b/shared/extra-utils/users/accounts-command.ts
new file mode 100644
index 000000000..2f586104e
--- /dev/null
+++ b/shared/extra-utils/users/accounts-command.ts
@@ -0,0 +1,56 @@
+import { HttpStatusCode, ResultList } from '@shared/models'
+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 },
+ implicitToken: false,
+ defaultExpectedStatus: HttpStatusCode.OK_200
+ })
+ }
+
+ get (options: OverrideCommandOptions & {
+ accountName: string
+ }) {
+ const path = '/api/v1/accounts/' + options.accountName
+
+ return this.getRequestBody({
+ ...options,
+
+ path,
+ implicitToken: false,
+ 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,
+ implicitToken: true,
+ defaultExpectedStatus: HttpStatusCode.OK_200
+ })
+ }
+}
diff --git a/shared/extra-utils/users/accounts.ts b/shared/extra-utils/users/accounts.ts
deleted file mode 100644
index 4ea7f1402..000000000
--- a/shared/extra-utils/users/accounts.ts
+++ /dev/null
@@ -1,87 +0,0 @@
-/* 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 { 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)
-}
-
-async function checkActorFilesWereRemoved (filename: string, serverNumber: number) {
- const testDirectory = 'test' + serverNumber
-
- for (const directory of [ 'avatars' ]) {
- const directoryPath = join(root(), testDirectory, directory)
-
- const directoryExists = existsSync(directoryPath)
- expect(directoryExists).to.be.true
-
- const files = await readdir(directoryPath)
- for (const file of files) {
- expect(file).to.not.contain(filename)
- }
- }
-}
-
-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
-}
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/blocklist-command.ts b/shared/extra-utils/users/blocklist-command.ts
new file mode 100644
index 000000000..14491a1ae
--- /dev/null
+++ b/shared/extra-utils/users/blocklist-command.ts
@@ -0,0 +1,139 @@
+/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */
+
+import { AccountBlock, HttpStatusCode, 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
+ },
+ implicitToken: true,
+ 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
+ },
+ implicitToken: true,
+ 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,
+ implicitToken: true,
+ 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,
+ implicitToken: true,
+ 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 },
+ implicitToken: true,
+ 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
new file mode 100644
index 000000000..460a06f70
--- /dev/null
+++ b/shared/extra-utils/users/index.ts
@@ -0,0 +1,9 @@
+export * from './accounts-command'
+export * from './actors'
+export * from './blocklist-command'
+export * from './login'
+export * from './login-command'
+export * from './notifications'
+export * from './notifications-command'
+export * from './subscriptions-command'
+export * from './users-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..143f72a59
--- /dev/null
+++ b/shared/extra-utils/users/login-command.ts
@@ -0,0 +1,132 @@
+import { HttpStatusCode, 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.store.client, user = this.server.store.user } = options
+ const path = '/api/v1/users/token'
+
+ const body = {
+ client_id: client.id,
+ client_secret: client.secret,
+ username: user.username,
+ password: user.password ?? 'password',
+ response_type: 'code',
+ grant_type: 'password',
+ scope: 'upload'
+ }
+
+ return unwrapBody<{ access_token: string, refresh_token: string } & PeerTubeProblemDocument>(this.postBodyRequest({
+ ...options,
+
+ path,
+ requestType: 'form',
+ fields: body,
+ implicitToken: false,
+ defaultExpectedStatus: HttpStatusCode.OK_200
+ }))
+ }
+
+ 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.store.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. (${err})`)
+ }
+ }
+
+ loginUsingExternalToken (options: OverrideCommandOptions & {
+ username: string
+ externalAuthToken: string
+ }) {
+ const { username, externalAuthToken } = options
+ const path = '/api/v1/users/token'
+
+ const body = {
+ client_id: this.server.store.client.id,
+ client_secret: this.server.store.client.secret,
+ username: username,
+ response_type: 'code',
+ grant_type: 'password',
+ scope: 'upload',
+ externalAuthToken
+ }
+
+ return this.postBodyRequest({
+ ...options,
+
+ path,
+ requestType: '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,
+ requestType: 'form',
+ implicitToken: false,
+ defaultExpectedStatus: HttpStatusCode.OK_200
+ }))
+ }
+
+ refreshToken (options: OverrideCommandOptions & {
+ refreshToken: string
+ }) {
+ const path = '/api/v1/users/token'
+
+ const body = {
+ 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'
+ }
+
+ return this.postBodyRequest({
+ ...options,
+
+ path,
+ requestType: '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 39e1a2747..f1df027d3 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 { PeerTubeServer } from '../server/server'
-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[]) {
+function setAccessTokensToServers (servers: PeerTubeServer[]) {
const tasks: Promise[] = []
for (const server of servers) {
- const p = serverLogin(server).then(t => { server.accessToken = t })
+ const p = server.login.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-command.ts b/shared/extra-utils/users/notifications-command.ts
new file mode 100644
index 000000000..2d79a3747
--- /dev/null
+++ b/shared/extra-utils/users/notifications-command.ts
@@ -0,0 +1,86 @@
+import { HttpStatusCode, ResultList } from '@shared/models'
+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/user-notifications.ts b/shared/extra-utils/users/notifications.ts
similarity index 88%
rename from shared/extra-utils/users/user-notifications.ts
rename to shared/extra-utils/users/notifications.ts
index 844f4442d..4c42fad3e 100644
--- a/shared/extra-utils/users/user-notifications.ts
+++ b/shared/extra-utils/users/notifications.ts
@@ -3,91 +3,36 @@
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 '../miscs/email'
-import { makeGetRequest, makePostBodyRequest, makePutBodyRequest } from '../requests/requests'
+import { MockSmtpServer } from '../mock-servers/mock-email'
+import { PeerTubeServer } from '../server'
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'
+import { createMultipleServers } from '../server/servers'
+import { setAccessTokensToServers } from './login'
-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
+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
+ server: PeerTubeServer
emails: any[]
socketNotifications: UserNotification[]
token: string
@@ -105,7 +50,7 @@ async function checkNotification (
const check = base.check || { web: true, mail: true }
if (check.web) {
- const notification = await getLastNotification(base.server.url, base.token)
+ const notification = await base.server.notifications.getLastest({ token: base.token })
if (notification || checkType !== 'absence') {
notificationChecker(notification, checkType)
@@ -681,27 +626,6 @@ async function checkNewPluginVersion (base: CheckerBaseParams, pluginType: Plugi
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[] = []
@@ -719,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)
@@ -727,42 +651,33 @@ 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 userAccessToken = await userLogin(servers[0], user)
+ const user = { username: 'user_1', password: 'super password' }
+ await servers[0].users.create({ ...user, videoQuota: 10 * 1000 * 1000 })
+ const userAccessToken = await servers[0].login.getAccessToken(user)
- await updateMyNotificationSettings(servers[0].url, userAccessToken, getAllNotificationsSettings())
- await updateMyNotificationSettings(servers[0].url, servers[0].accessToken, getAllNotificationsSettings())
+ await servers[0].notifications.updateMySettings({ token: userAccessToken, settings: getAllNotificationsSettings() })
+ await servers[0].notifications.updateMySettings({ settings: getAllNotificationsSettings() })
if (serversCount > 1) {
- await updateMyNotificationSettings(servers[1].url, servers[1].accessToken, getAllNotificationsSettings())
+ await servers[1].notifications.updateMySettings({ settings: getAllNotificationsSettings() })
}
{
- const socket = getUserNotificationSocket(servers[0].url, userAccessToken)
+ const socket = servers[0].socketIO.getUserNotificationSocket({ token: userAccessToken })
socket.on('new-notification', n => userNotifications.push(n))
}
{
- const socket = getUserNotificationSocket(servers[0].url, servers[0].accessToken)
+ const socket = servers[0].socketIO.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].socketIO.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
+ const { videoChannels } = await servers[0].users.getMyInfo()
+ const channelId = videoChannels[0].id
return {
userNotifications,
@@ -778,11 +693,11 @@ async function prepareNotificationsTest (serversCount = 3, overrideConfigArg: an
// ---------------------------------------------------------------------------
export {
+ getAllNotificationsSettings,
+
CheckerBaseParams,
CheckerType,
- getAllNotificationsSettings,
checkNotification,
- markAsReadAllNotifications,
checkMyVideoImportIsFinished,
checkUserRegistered,
checkAutoInstanceFollowing,
@@ -792,14 +707,10 @@ export {
checkNewCommentOnMyVideo,
checkNewBlacklistOnMyVideo,
checkCommentMention,
- updateMyNotificationSettings,
checkNewVideoAbuseForModerators,
checkVideoAutoBlacklistForModerators,
checkNewAbuseMessage,
checkAbuseStateChange,
- getUserNotifications,
- markAsReadNotifications,
- getLastNotification,
checkNewInstanceFollower,
prepareNotificationsTest,
checkNewCommentAbuseForModerators,
diff --git a/shared/extra-utils/users/subscriptions-command.ts b/shared/extra-utils/users/subscriptions-command.ts
new file mode 100644
index 000000000..edc60e612
--- /dev/null
+++ b/shared/extra-utils/users/subscriptions-command.ts
@@ -0,0 +1,99 @@
+import { HttpStatusCode, ResultList, Video, VideoChannel } from '@shared/models'
+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 },
+ implicitToken: true,
+ 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
+ },
+ implicitToken: true,
+ 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 },
+ implicitToken: true,
+ defaultExpectedStatus: HttpStatusCode.OK_200
+ })
+ }
+
+ get (options: OverrideCommandOptions & {
+ uri: string
+ }) {
+ const path = '/api/v1/users/me/subscriptions/' + options.uri
+
+ return this.getRequestBody({
+ ...options,
+
+ path,
+ implicitToken: true,
+ defaultExpectedStatus: HttpStatusCode.OK_200
+ })
+ }
+
+ remove (options: OverrideCommandOptions & {
+ uri: string
+ }) {
+ const path = '/api/v1/users/me/subscriptions/' + options.uri
+
+ return this.deleteRequest({
+ ...options,
+
+ path,
+ implicitToken: true,
+ 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 },
+ implicitToken: true,
+ 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
-}
diff --git a/shared/extra-utils/users/users-command.ts b/shared/extra-utils/users/users-command.ts
new file mode 100644
index 000000000..d66ad15f2
--- /dev/null
+++ b/shared/extra-utils/users/users-command.ts
@@ -0,0 +1,414 @@
+import { omit, pick } from 'lodash'
+import {
+ HttpStatusCode,
+ 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.login.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.login.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
deleted file mode 100644
index 0f15962ad..000000000
--- a/shared/extra-utils/users/users.ts
+++ /dev/null
@@ -1,415 +0,0 @@
-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'
-import { userLogin } from './login'
-
-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 userLogin(server, { 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 userLogin(server, { 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) {
- 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/)
-}
-
-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
-}
diff --git a/shared/extra-utils/videos/blacklist-command.ts b/shared/extra-utils/videos/blacklist-command.ts
new file mode 100644
index 000000000..3a2ef89ba
--- /dev/null
+++ b/shared/extra-utils/videos/blacklist-command.ts
@@ -0,0 +1,76 @@
+
+import { HttpStatusCode, ResultList } from '@shared/models'
+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/captions-command.ts b/shared/extra-utils/videos/captions-command.ts
new file mode 100644
index 000000000..a65ea99e3
--- /dev/null
+++ b/shared/extra-utils/videos/captions-command.ts
@@ -0,0 +1,65 @@
+import { HttpStatusCode, ResultList, VideoCaption } from '@shared/models'
+import { buildAbsoluteFixturePath } from '../miscs'
+import { AbstractCommand, OverrideCommandOptions } from '../shared'
+
+export class CaptionsCommand extends AbstractCommand {
+
+ add (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
+ })
+ }
+
+ list (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
+ })
+ }
+
+ delete (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..ff8a43366
--- /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 '@shared/models'
+
+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/change-ownership-command.ts b/shared/extra-utils/videos/change-ownership-command.ts
new file mode 100644
index 000000000..ad4c726ef
--- /dev/null
+++ b/shared/extra-utils/videos/change-ownership-command.ts
@@ -0,0 +1,68 @@
+
+import { HttpStatusCode, ResultList, VideoChangeOwnership } from '@shared/models'
+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/channels-command.ts b/shared/extra-utils/videos/channels-command.ts
new file mode 100644
index 000000000..f8eb3f885
--- /dev/null
+++ b/shared/extra-utils/videos/channels-command.ts
@@ -0,0 +1,156 @@
+import { pick } from 'lodash'
+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'
+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..756c47453
--- /dev/null
+++ b/shared/extra-utils/videos/channels.ts
@@ -0,0 +1,18 @@
+import { PeerTubeServer } from '../server/server'
+
+function setDefaultVideoChannel (servers: PeerTubeServer[]) {
+ const tasks: Promise[] = []
+
+ for (const server of servers) {
+ const p = server.users.getMyInfo()
+ .then(user => { server.store.channel = user.videoChannels[0] })
+
+ tasks.push(p)
+ }
+
+ return Promise.all(tasks)
+}
+
+export {
+ setDefaultVideoChannel
+}
diff --git a/shared/extra-utils/videos/comments-command.ts b/shared/extra-utils/videos/comments-command.ts
new file mode 100644
index 000000000..f0d163a07
--- /dev/null
+++ b/shared/extra-utils/videos/comments-command.ts
@@ -0,0 +1,152 @@
+import { pick } from 'lodash'
+import { HttpStatusCode, ResultList, VideoComment, VideoCommentThreads, VideoCommentThreadTree } from '@shared/models'
+import { unwrapBody } from '../requests'
+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
+ 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
+ }))
+
+ this.lastThreadId = body.comment?.id
+ this.lastVideoId = videoId
+
+ 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
+ }))
+
+ 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
+ }) {
+ 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/history-command.ts b/shared/extra-utils/videos/history-command.ts
new file mode 100644
index 000000000..13b7150c1
--- /dev/null
+++ b/shared/extra-utils/videos/history-command.ts
@@ -0,0 +1,58 @@
+import { HttpStatusCode, ResultList, Video } from '@shared/models'
+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/imports-command.ts b/shared/extra-utils/videos/imports-command.ts
new file mode 100644
index 000000000..e4944694d
--- /dev/null
+++ b/shared/extra-utils/videos/imports-command.ts
@@ -0,0 +1,47 @@
+
+import { HttpStatusCode, ResultList } from '@shared/models'
+import { VideoImport, VideoImportCreate } from '../../models/videos'
+import { unwrapBody } from '../requests'
+import { AbstractCommand, OverrideCommandOptions } from '../shared'
+
+export class ImportsCommand extends AbstractCommand {
+
+ 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
new file mode 100644
index 000000000..26e663f46
--- /dev/null
+++ b/shared/extra-utils/videos/index.ts
@@ -0,0 +1,19 @@
+export * from './blacklist-command'
+export * from './captions-command'
+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'
+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 './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
new file mode 100644
index 000000000..bf9486a05
--- /dev/null
+++ b/shared/extra-utils/videos/live-command.ts
@@ -0,0 +1,154 @@
+/* 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 { HttpStatusCode, LiveVideo, LiveVideoCreate, LiveVideoUpdate, VideoCreateResult, VideoDetails, VideoState } from '@shared/models'
+import { wait } from '../miscs'
+import { unwrapBody } from '../requests'
+import { AbstractCommand, OverrideCommandOptions } from '../shared'
+import { sendRTMPStream, testFfmpegStreamError } from './live'
+
+export class LiveCommand extends AbstractCommand {
+
+ get (options: OverrideCommandOptions & {
+ videoId: number | string
+ }) {
+ const path = '/api/v1/videos/live'
+
+ return this.getRequestBody({
+ ...options,
+
+ path: path + '/' + options.videoId,
+ implicitToken: true,
+ defaultExpectedStatus: HttpStatusCode.OK_200
+ })
+ }
+
+ update (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,
+ implicitToken: true,
+ defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
+ })
+ }
+
+ async create (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'),
+ implicitToken: true,
+ defaultExpectedStatus: HttpStatusCode.OK_200
+ }))
+
+ return body.video
+ }
+
+ async sendRTMPStreamInVideo (options: OverrideCommandOptions & {
+ videoId: number | string
+ fixtureName?: string
+ }) {
+ const { videoId, fixtureName } = options
+ const videoLive = await this.get({ videoId })
+
+ return sendRTMPStream(videoLive.rtmpUrl, videoLive.streamKey, fixtureName)
+ }
+
+ async runAndTestStreamError (options: OverrideCommandOptions & {
+ videoId: number | string
+ shouldHaveError: boolean
+ }) {
+ const command = await this.sendRTMPStreamInVideo(options)
+
+ return testFfmpegStreamError(command, options.shouldHaveError)
+ }
+
+ waitUntilPublished (options: OverrideCommandOptions & {
+ videoId: number | string
+ }) {
+ const { videoId } = options
+ return this.waitUntilState({ videoId, state: VideoState.PUBLISHED })
+ }
+
+ waitUntilWaiting (options: OverrideCommandOptions & {
+ videoId: number | string
+ }) {
+ const { videoId } = options
+ return this.waitUntilState({ videoId, state: VideoState.WAITING_FOR_LIVE })
+ }
+
+ waitUntilEnded (options: OverrideCommandOptions & {
+ videoId: number | string
+ }) {
+ const { videoId } = options
+ return this.waitUntilState({ videoId, state: VideoState.LIVE_ENDED })
+ }
+
+ waitUntilSegmentGeneration (options: OverrideCommandOptions & {
+ videoUUID: string
+ resolution: number
+ segment: number
+ }) {
+ const { resolution, segment, videoUUID } = options
+ const segmentName = `${resolution}-00000${segment}.ts`
+
+ return this.server.servers.waitUntilLog(`${videoUUID}/${segmentName}`, 2, false)
+ }
+
+ async waitUntilSaved (options: OverrideCommandOptions & {
+ videoId: number | string
+ }) {
+ let video: VideoDetails
+
+ do {
+ video = await this.server.videos.getWithToken({ token: options.token, id: options.videoId })
+
+ await wait(500)
+ } while (video.isLive === true && video.state.id !== VideoState.PUBLISHED)
+ }
+
+ async countPlaylists (options: OverrideCommandOptions & {
+ videoUUID: string
+ }) {
+ const basePath = this.server.servers.buildDirectory('streaming-playlists')
+ const hlsPath = join(basePath, 'hls', options.videoUUID)
+
+ const files = await readdir(hlsPath)
+
+ return files.filter(f => f.endsWith('.m3u8')).length
+ }
+
+ private async waitUntilState (options: OverrideCommandOptions & {
+ videoId: number | string
+ state: VideoState
+ }) {
+ let video: VideoDetails
+
+ do {
+ 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 c0384769b..502964b1a 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 { buildAbsoluteFixturePath, wait } from '../miscs'
+import { PeerTubeServer } from '../server/server'
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,53 +70,14 @@ 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) {
+async function waitUntilLivePublishedOnAllServers (servers: PeerTubeServer[], videoId: string) {
for (const server of servers) {
- await waitUntilLivePublished(server.url, server.accessToken, videoId)
+ await server.live.waitUntilPublished({ videoId })
}
}
-async function checkLiveCleanup (server: ServerInfo, videoUUID: string, resolutions: number[] = []) {
- const basePath = buildServerDirectory(server, 'streaming-playlists')
+async function checkLiveCleanup (server: PeerTubeServer, videoUUID: string, resolutions: number[] = []) {
+ const basePath = server.servers.buildDirectory('streaming-playlists')
const hlsPath = join(basePath, 'hls', videoUUID)
if (resolutions.length === 0) {
@@ -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,
- waitFfmpegUntilError,
- waitUntilLivePublishedOnAllServers,
sendRTMPStream,
- testFfmpegStreamError
+ waitFfmpegUntilError,
+ testFfmpegStreamError,
+ stopFfmpeg,
+ waitUntilLivePublishedOnAllServers,
+ checkLiveCleanup
}
diff --git a/shared/extra-utils/videos/playlists-command.ts b/shared/extra-utils/videos/playlists-command.ts
new file mode 100644
index 000000000..6f329800e
--- /dev/null
+++ b/shared/extra-utils/videos/playlists-command.ts
@@ -0,0 +1,279 @@
+import { omit, pick } from 'lodash'
+import {
+ BooleanBothQuery,
+ HttpStatusCode,
+ ResultList,
+ VideoExistInPlaylist,
+ VideoPlaylist,
+ VideoPlaylistCreate,
+ VideoPlaylistCreateResult,
+ VideoPlaylistElement,
+ VideoPlaylistElementCreate,
+ VideoPlaylistElementCreateResult,
+ VideoPlaylistElementUpdate,
+ VideoPlaylistReorder,
+ VideoPlaylistType,
+ VideoPlaylistUpdate
+} from '@shared/models'
+import { unwrapBody } from '../requests'
+import { AbstractCommand, OverrideCommandOptions } from '../shared'
+
+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 this.server.videos.getId({ ...options, uuid: 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..3dde52bb9
--- /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 '../miscs'
+
+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/services-command.ts b/shared/extra-utils/videos/services-command.ts
new file mode 100644
index 000000000..06760df42
--- /dev/null
+++ b/shared/extra-utils/videos/services-command.ts
@@ -0,0 +1,29 @@
+import { HttpStatusCode } from '@shared/models'
+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,
+ implicitToken: false,
+ 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
-}
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..9662685da
--- /dev/null
+++ b/shared/extra-utils/videos/streaming-playlists-command.ts
@@ -0,0 +1,44 @@
+import { HttpStatusCode } from '@shared/models'
+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 unwrapBody(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..1ae3fefc1
--- /dev/null
+++ b/shared/extra-utils/videos/streaming-playlists.ts
@@ -0,0 +1,75 @@
+import { expect } from 'chai'
+import { sha256 } from '@server/helpers/core-utils'
+import { HttpStatusCode, VideoStreamingPlaylist } from '@shared/models'
+import { PeerTubeServer } from '../server'
+
+async function checkSegmentHash (options: {
+ server: PeerTubeServer
+ baseUrlPlaylist: string
+ baseUrlSegment: string
+ videoUUID: string
+ resolution: number
+ hlsPlaylist: VideoStreamingPlaylist
+}) {
+ const { server, baseUrlPlaylist, baseUrlSegment, videoUUID, resolution, hlsPlaylist } = options
+ const command = server.streamingPlaylists
+
+ 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: PeerTubeServer
+ baseUrlSegment: string
+ videoUUID: string
+ segmentName: string
+ hlsPlaylist: VideoStreamingPlaylist
+}) {
+ const { server, baseUrlSegment, videoUUID, segmentName, hlsPlaylist } = options
+ const command = server.streamingPlaylists
+
+ 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: PeerTubeServer
+ playlistUrl: string
+ resolutions: number[]
+}) {
+ const { server, playlistUrl, resolutions } = options
+
+ const masterPlaylist = await server.streamingPlaylists.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-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
-}
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
-}
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
-}
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/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/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
-}
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
-}
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/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
-}
diff --git a/shared/extra-utils/videos/videos-command.ts b/shared/extra-utils/videos/videos-command.ts
new file mode 100644
index 000000000..98465e8f6
--- /dev/null
+++ b/shared/extra-utils/videos/videos-command.ts
@@ -0,0 +1,598 @@
+/* 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,
+ ResultList,
+ UserVideoRateType,
+ Video,
+ VideoCreate,
+ VideoCreateResult,
+ VideoDetails,
+ VideoFileMetadata,
+ VideoPrivacy,
+ VideosCommonQuery,
+ VideosWithSearchCommonQuery
+} from '@shared/models'
+import { buildAbsoluteFixturePath, wait } from '../miscs'
+import { unwrapBody } from '../requests'
+import { PeerTubeServer, 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: PeerTubeServer) {
+ 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 & {
+ handle: string
+ }) {
+ const { handle, search } = options
+ const path = '/api/v1/accounts/' + handle + '/videos'
+
+ return this.getRequestBody>({
+ ...options,
+
+ path,
+ query: { search, ...this.buildListQuery(options) },
+ implicitToken: true,
+ defaultExpectedStatus: HttpStatusCode.OK_200
+ })
+ }
+
+ listByChannel (options: OverrideCommandOptions & VideosWithSearchCommonQuery & {
+ handle: string
+ }) {
+ const { handle } = options
+ const path = '/api/v1/video-channels/' + handle + '/videos'
+
+ return this.getRequestBody>({
+ ...options,
+
+ path,
+ query: this.buildListQuery(options),
+ implicitToken: true,
+ defaultExpectedStatus: HttpStatusCode.OK_200
+ })
+ }
+
+ // ---------------------------------------------------------------------------
+
+ 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
+ }) {
+ 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 unwrapBody(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' } = options
+ let defaultChannelId = 1
+
+ try {
+ const { videoChannels } = await this.server.users.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 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: created.uuid })
+
+ await wait(50)
+ } while (!video.files[0].torrentUrl)
+ }
+
+ return created
+ }
+
+ 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
+ }): Promise {
+ 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'
+ }
+ }
+
+ // 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) {
+ 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 || result.body as any
+ }
+
+ const expectedInitStatus = expectedStatus === HttpStatusCode.OK_200
+ ? HttpStatusCode.CREATED_201
+ : expectedStatus
+
+ expect(initStatus).to.equal(expectedInitStatus)
+
+ return initializeSessionRes.body.video || initializeSessionRes.body
+ }
+
+ 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) },
+ // Fixture will be sent later
+ attaches: this.buildUploadAttaches(omit(options.attributes, 'fixture')),
+ 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 }
+
+ const result = await this.upload({ ...options, attributes })
+
+ if (wait) await waitJobs([ this.server ])
+
+ 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, [ 'fixture', '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 469ea4d63..9a9bfb3cf 100644
--- a/shared/extra-utils/videos/videos.ts
+++ b/shared/extra-utils/videos/videos.ts
@@ -1,348 +1,20 @@
/* 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 { 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 { makeGetRequest, makePutBodyRequest, makeRawRequest, makeUploadRequest } from '../requests/requests'
-import { waitJobs } from '../server/jobs'
-import { ServerInfo } from '../server/servers'
-import { getMyUserInformation } from '../users/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?: boolean } = {}) {
- const path = '/api/v1/videos'
-
- return request(url)
- .get(path)
- .set('Authorization', 'Bearer ' + token)
- .query(immutableAssign(query, { sort: 'name' }))
- .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?: boolean
- search?: string
- } = {}
-) {
- const path = '/api/v1/accounts/' + accountName + '/videos'
-
- return makeGetRequest({
- url,
- path,
- query: immutableAssign(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?: boolean } = {}
-) {
- const path = '/api/v1/video-channels/' + videoChannelName + '/videos'
-
- return makeGetRequest({
- url,
- path,
- query: immutableAssign(query, {
- start,
- count,
- sort
- }),
- token: accessToken,
- statusCodeExpected: HttpStatusCode.OK_200
- })
-}
-
-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'
-
- 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 { 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'
+import { waitJobs } from '../server'
+import { PeerTubeServer } from '../server/server'
+import { VideoEdit } from './videos-command'
async function checkVideoFilesWereRemoved (
videoUUID: string,
- serverNumber: number,
+ server: PeerTubeServer,
directories = [
'redundancy',
'videos',
@@ -355,7 +27,7 @@ async function checkVideoFilesWereRemoved (
]
) {
for (const directory of directories) {
- const directoryPath = buildServerDirectory({ internalServerNumber: serverNumber }, directory)
+ const directoryPath = server.servers.buildDirectory(directory)
const directoryExists = await pathExists(directoryPath)
if (directoryExists === false) continue
@@ -367,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 getMyUserInformation(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: PeerTubeServer,
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 = buildServerDirectory(server, join('torrents', torrentName))
-
- readFile(torrentPath, (err, data) => {
- if (err) return rej(err)
-
- return res(parseTorrent(data))
- })
- })
+ ? server.videos.buildLegacyUpload({ token, attributes, expectedStatus })
+ : server.videos.buildResumeUpload({ token, attributes, expectedStatus })
}
async function completeVideoCheck (
- url: string,
+ server: PeerTubeServer,
video: any,
attributes: {
name: string
@@ -682,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)
@@ -719,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.videos.get({ id: video.uuid })
expect(videoDetails.files).to.have.lengthOf(attributes.files.length)
expect(videoDetails.tags).to.deep.equal(attributes.tags)
@@ -776,149 +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: PeerTubeServer[],
+ 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.videos.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,
- getPlaylistVideos,
- 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/core-utils/miscs/http-error-codes.ts b/shared/models/http/http-error-codes.ts
similarity index 100%
rename from shared/core-utils/miscs/http-error-codes.ts
rename to shared/models/http/http-error-codes.ts
diff --git a/shared/core-utils/miscs/http-methods.ts b/shared/models/http/http-methods.ts
similarity index 100%
rename from shared/core-utils/miscs/http-methods.ts
rename to shared/models/http/http-methods.ts
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/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/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 {
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/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 {
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/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
+ }
+}
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
+}
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
-}
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
+}
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
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:
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",